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') )
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><formid="example"name="example"><selectid="sensor"><optionvalue="Jval"data-foo="Jfoo">Joption</option><optionvalue="Kval"data-foo="Kfoo">Koption</option></select><br /><inputtype="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 pageupdateTextField();
// Update your text field when an option is selected
selectField.addEventListener('change', updateTextField);
<formid="example"name="example"><selectid="sensor"><optionvalue="Jval"data-foo="Jfoo">Joption</option><optionvalue="Kval"data-foo="Kfoo">Koption</option></select><br /><inputtype="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);
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><formid="example"name="example"><selectid="sensor"><optionvalue="Jval"data-foo="Jfoo">Joption</option><optionvalue="Kval"data-foo="Kfoo">Koption</option></select><br /><inputtype="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"