如何从一个动态的<select>选择

how to know the select id from an dynamic <select> option?

本文关键字:select 选择 动态 一个      更新时间:2023-09-26

我正在建立一个动态网店,在我的页面上有超过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#

的输入#newsid_#

当我点击或更改select#sel_4时,我希望所选项的值显示在输入#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>

很简单,只需绑定到change事件,然后使用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  
});

此外,如果选择列表将在页面加载后动态构建,则以这种方式绑定:

这将绑定到所有当前和未来的选择列表。

  $(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);  
});