Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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... Any thoughts?


My code :

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...