使用自定义选项(data-)属性的内容填充输入 [英] Populate an input with the contents of a custom option (data-) attribute
本文介绍了使用自定义选项(data-)属性的内容填充输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的例子中,我试图用option.data-foo属性的内容来填充输入。我感觉就像这样......但我在某个地方有一些东西......有什么想法吗?
我的代码:
function updateText(type){var id = type + '文本'; document.getElementById(id).data-foo = document.getElementById(type).value;}
< form id =examplename =example> < select id =sensoronchange =updateText('sensor')> < option value =Jvaldata-foo =Jfoo> Joption< / option> < option value =Kvaldata-foo =Kfoo> Koption< / option> < /选择> < br /> < input type =textvalue =id =sensorText/>< / form>
解决方案
如果您使用的是jQuery,请使用以下命令:
$('#sensor')。change(function(){
$('#sensorText')。val($(this).find('option:selected')。data 'foo'))
})
$('#sensor')。change(function(){$('#sensorText').val($(this).find('option:selected')。data('foo'))}) code>
< script src =https://ajax.googleapis。 com / ajax / libs / jquery / 1.11.1 / jquery.min.js>< / script>< form id =examplename =example> < select id =sensor> < option value =Jvaldata-foo =Jfoo> Joption< / option> < option value =Kvaldata-foo =Kfoo> Koption< / option> < /选择> < br /> < input type =textvalue =id =sensorText/>< / form>
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>
解决方案
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>
这篇关于使用自定义选项(data-)属性的内容填充输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文