I want to select the first option in a select list which matches a certain value, currently the last match is selected, like so:
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>')
Now if the enduser is the assignee that user is selected in the group he is in, and not the second value 'me (user)', is there a way to do this or do I need some workaround?
In the usecase the assignee is the backenduser it's simply
<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>
Ok, so selected=selected instead of checked=checked, whichever jQuery uses, it is not done manually.
So $("option[value='mister x']:first").attr("selected", "selected")
does the trick, if there would be one single list, how does this work when there are multiple forms with all their unique ids edit-form-# ?
answer by ryanulit:
jQuery('#edit-form-'+id+' option[value='+assignee+']:first').attr("selected", "selected");