我有 2 个下拉列表-
1) First dropdown list for client ID
2) Second dropdown list for client name
我想要的是,当用户选择客户端 ID 时,应在另一个下拉列表中选择具有所选 ID 的客户端名称。
我想要的第二件事是如果用户选择客户端名称,那么在客户端 ID 下拉列表中应该选择客户端的客户端 ID。
到目前为止我做了什么-
<select class="form-control" id="client_id">
<?php
while($c_id=mysql_fetch_array($client_id))
{
echo "<option>".$c_id['ID']."</option>";
}
?>
</select>
<select class="form-control" id="client_name">
<?php
while($c_name=mysql_fetch_array($client_name))
{
echo "<option value='".$c_name['ID']."'>".$c_name['display_name']."</option>";
}
?>
</select>
Jquery-
$('#client_id').change(function(){
//Client name should be select here base on selected id
});
$('#client_name').change(function(){
//Client id should be select here base on selected client name
});
请帮帮我。
谢谢。
最佳答案
您需要以下代码:
$(function() {
$('#client_id').change(function(){
id = $( "#client_id option:selected" ).text();
$("#client_name > option").each(function() {
name = this.text;
idFromName = name.replace(/(^\d+)(.+$)/i,'$1');
if (id == idFromName){
$('#client_name').val(name);
}
});
});
$('#client_name').change(function(){
name = $( "#client_name option:selected" ).text();
idFromName = name.replace(/(^\d+)(.+$)/i,'$1');
$("#client_id > option").each(function() {
id = this.text;
if (id == idFromName){
$('#client_id').val(idFromName);
}
});
});
});
在上面的代码中,当 clinet_id
下拉列表发生变化时,所选选项的 ID 保存在 id
变量中。然后循环遍历另一个下拉列表 (client_name
) 的选项,对于每个选项,选项的文本都保存在变量 name
中。然后使用正则表达式(使用 this )只有文本中的 id 保存在 idFromName
变量中。如果 id
和 idFromName
相等,它会将 client_name
下拉列表更改为当前选择。使用相同的逻辑,当 client_name
下拉列表更改时也会发生这种情况。
你可以在这个JSFiddle中测试它.
来源:
- > How to select an option in a dropdown list based on a selection in another dropdown list
- > Get the first Int(s) in a string with javascript
- > Iterate through <select> options
- > Set select option 'selected', by value
- > http://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
更新
这是一个完整的工作示例:
<select id="client_id">
<option>125</option>
<option>53</option>
<option>7</option>
</select>
<select id="client_name">
<option>125>asd</option>
<option>53>rty</option>
<option>7>ruu</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#client_id').change(function(){
id = $( "#client_id option:selected" ).text();
$("#client_name > option").each(function() {
name = this.text;
idFromName = name.replace(/(^\d+)(.+$)/i,'$1');
if (id == idFromName){
$('#client_name').val(name);
}
});
});
$('#client_name').change(function(){
name = $( "#client_name option:selected" ).text();
idFromName = name.replace(/(^\d+)(.+$)/i,'$1');
$("#client_id > option").each(function() {
id = this.text;
if (id == idFromName){
$('#client_id').val(idFromName);
}
});
});
});
</script>
复制并粘贴此内容并对您的 ID 和名称进行调整。
关于javascript - 根据另一个下拉菜单选择一个下拉菜单的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42455275/