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

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - 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... 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...