我想在选择列表中选择与某个值匹配的第一个选项,当前选择了最后一个匹配项,如下所示:
jQuery('.edit-item').click(function(){
var id = jQuery(this).attr('id');
var assignee = jQuery('#assignee-'+id).text();
jQuery('#edit-form-'+id+' select[name=item[responsible]]').val(assignee);
return false;
});
<select name="item[responsible]">
<option value="*">Anyone</option>
<option value="'+$user+'">Me ('+$user+')</option>')
-- here a loop with groups --
<option value="">----------</option>
<option value="'+$group+'">'+$group+'</option>')
-- here a loop with all usernames within $group
<option value="'+$username+'">'+$username+'</option>')
-- end loop --
-- end loop --
</select>')
现在,如果最终用户是该用户在他所在的组中被选中的受让人,而不是第二个值“我(用户)”,有没有办法做到这一点,还是我需要一些解决方法?
在用例中,受让人是后端用户,它很简单
<select name="item[responsible]">
<option value="*">Anyone</option>
<option value="mister x" selected=selected>Me (mister x)</option> // this one needs to be selected
<option value="1">1</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="2">2</option>
<option value="c">c</option>
<option value="d">d</option>
<option value="mister x">mister x</option> // this is the one that is selected
</select>
好的,所以selected=selected而不是checked=checked,无论jQuery使用哪个,都不是手动完成的。
所以
$("option[value='mister x']:first").attr("selected", "selected")
诀窍是什么,如果只有一个列表,当有多个表单具有所有唯一 ID 时,这将如何工作 edit-form-# ?ryanulit 的回答:
jQuery('#edit-form-'+id+' option[value='+assignee+']:first').attr("selected", "selected");
最佳答案
I want to select the first option in a select list which matches a certain value...
其中任何一个都应该为您做到这一点。当然,您可以将“mister x”替换为您想要搜索的任何值。
$("option[value='mister x']:first").attr("selected", true);
或者
$("option[value='mister x']:first").attr("selected", "selected");
编辑
这是可能的。只需引用特定的选择元素。此外,我会将您选择的名称更改为 item_responsible,就像其他人推荐的那样,并为其 ID 提供相同的文本。然后你可以这样做:
$("#item_responsible option[value='mister x']:first")
而不是 $("option[value='mister x']:first")
...其中#item_responsible 是您的选择:
<select id="item_responsible" name="item_responsible">
<!-- options here -->
</select>
关于jQuery 返回选择列表中的第一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2049070/