Fill in the tab with the contents of the attribute of the user option (data-)

In the example below, I am trying to populate the input with the contents of the option.data-foo attribute. I feel this is close ... but I have something ahead of me ... Any thoughts?


My code is:

function updateText(type) {
    var id = type+'Text';
    document.getElementById(id).data-foo = document.getElementById(type).value;
}
<form id="example" name="example">
    <select id="sensor" onchange="updateText('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>
Run codeHide result
-2
source share
3 answers

If you are using jQuery, 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>
Run codeHide result
+1
source

What are you going to do, maybe 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>
Run codeHide result

(see also this script )

+1
source

jquery:

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

Source: https://habr.com/ru/post/1629777/


All Articles