我正在构建一个动态网上商店,页面中有超过 30 个“选择”“选项”。
在每个“选择”中,我也有动态值。
每个值都显示为“选项”
<select class="form-control" id="seh" name="eh">
<option value="10">Karton 10 x 1.00 kg</option>
<option value="1.00">Verkoopeenheid 1.00 kg</option>
<option value="1" selected="">Per kg</option>
</select>
当我单击“选择”并选择一个“选项”时,我想将 selectIndex 显示为隐藏的输入类型文本。
<input name="si" value="**?Here i want the index?**" type="hidden">
我希望使用此功能让登录用户在回来并再次登录时记住上次使用的“选项”。
有人可以帮我吗?
**更新**
<form class="form-item">
<select class="form-control" id="sel_1" name="seleh">
<option value="8">Karton 8 x 1.05 kg</option>
<option value="1.05">Verkoopeenheid 1.05 kg</option>
<option value="1">Per kg</option>
</select>
<input name="newsid" id="newsid_1" value="" type="text" hidden>
<button type="submit" class="btn btn-primary"> add</button>
</form>
这是我的表单的输出
在 jquery 部分下面...它可以工作,但会影响所有输入#newsid_#number# 我只想影响属于 select# 的 input#newsid_#
当我点击或在 select#sel_4 中进行更改时,我希望所选项目的值显示在 input#newsid_4 中。
<script>
$("select.form-control").click(function(){
var selectedText = $(this).find("option:selected").val();
var news = $(this).find('input[id^=newsid_]').text();
$('input[id^=newsid_]').attr("value", selectedText);
});
</script>
最佳答案
很简单,只需绑定(bind)到更改事件,然后使用 jQuery 获取“option:selected”选择器即可。那是你所需要的吗?
$("select.form-control).change(function(){
var selectedText = $(this).find("option:selected").text();//the selected text
$("#myHiddenField").attr("value", selectedText); //apply to hidden field
});
此外,如果要在页面加载后动态构建选择列表,则以这种方式绑定(bind):
这将绑定(bind)到当前和 future 的选择列表。
$(document)on("change", "select", function(){
var selectedText = $(this).find("option:selected").text();//the selected text
$("#myHiddenField").attr("value", selectedText); //apply to hidden field
});
没有理由执行您发布的下面的一些代码。将其更改为以下内容:
<script>
$("select.form-control").click(function(){
var selectedText = $(this).find("option:selected").val();
var $newsElement = $(this).find('input[id^=newsid_]');
$newsElement.attr("value", selectedText);
});
关于javascript - 如何从动态 <select> 选项中知道选择 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33226390/