Skip to content Skip to sidebar Skip to footer

Populate An Input With The Contents Of A Custom Option (data-) Attribute

In the example below, I'm trying to populate an input with the contents of the option.data-foo attribute. I feel like this close... but I've got something back-to-front somewhere..

Solution 1:

If you're using jQuery then use this:

$('#sensor').change(function() {
  $('#sensorText').val( $(this).find('option:selected').data('foo') )
})

$('#sensor').change(function() {
  $('#sensorText').val( $(this).find('option:selected').data('foo') )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="example" name="example">
  <select id="sensor">
    <option value="Jval" data-foo="Jfoo">Joption</option>
    <option value="Kval" data-foo="Kfoo">Koption</option>
  </select>

  <br />
  <input type="text" value="" id="sensorText" />
</form>

Solution 2:

What you're going for, is probably this :

var selectField = document.getElementById('sensor');
var textField = document.getElementById('sensorText');
var updateTextField = function() {
    textField.setAttribute(
        'value',
        selectField.options[selectField.selectedIndex].dataset.foo
    );
}

// Populate your text field when loading your page
updateTextField();

// Update your text field when an option is selected
selectField.addEventListener('change', updateTextField);
<form id="example" name="example">
    <select id="sensor">
        <option value="Jval" data-foo="Jfoo">Joption</option>
        <option value="Kval" data-foo="Kfoo">Koption</option>
    </select>
    <br />
    <input type="text" value="" id="sensorText" />
</form>

(see also this Fiddle)


Solution 3:

You can also resolve it in this way

$("#sensor").on("change", function(){
  var $selectedItem = $(this).find(":selected");
  var dataValue = $selectedItem.data("foo");
  $("#sensorText").val(dataValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="example" name="example">
    <select id="sensor">
        <option value="Jval" data-foo="Jfoo">Joption</option>
        <option value="Kval" data-foo="Kfoo">Koption</option>
    </select>

    <br />
    <input type="text" value="" id="sensorText" />
</form>

Solution 4:

if you are using jquery:

var value = $('#elementId').attr('data-foo');

Post a Comment for "Populate An Input With The Contents Of A Custom Option (data-) Attribute"