Reputation: 11841
I have this select
<select name="clients[]" size="20" multiple="multiple" id="clients" style="min-width:275px;">
<option id="first">First</option>
<option id="second">Second</option>
<option id="third">Third</option>
</select>
I am trying to get this alert box to show up when the id = first, I've tried
$(document).ready(function(){
if($('#clients option:selected').val() == 'first'){
alert('hi');
}
});
but nothing appears...what am I doing wrong
Upvotes: 1
Views: 7463
Reputation: 858
You've set the option ids instead of values in the html. Also, in jQuery to find the selected value, you only need to look for the value of the select element.
Do this instead:
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
$(document).ready(function(){
if($('#clients').val() == 'first'){
alert('hi');
}
});
if you want it to show the popup in real time do this:
$(document).ready(function(){
$('#clients').change(function(){
if($(this).val() == 'first'){
alert('hi');
}
});
});
Upvotes: 0
Reputation: 68400
This code triggers an alert in case the select has First
selected on document ready and also when the user changes the selection
$(function(){
checkSelection();
$('#clients').change(function(){
checkSelection();
})
function checkSelection(){
var selectedOptions = $('#clients').val();
if($.inArray('First',selectedOptions) != -1){
alert('hi');
}
}
})
Upvotes: 0
Reputation: 816262
The value is First
, not first
. Since you did not provide a value
attribute, the content of the option
element is taken as value.
Be aware that you use a multiselect field. In this case, the browser won't select an element on page *, so it only makes sense to test for first
when the selection chages.
You have to check whether First
is one of the selected elements:
$('#clients').change(function(){
if($(this).children('option:selected').filter('#first').length) {
alert('hi');
}
});
Another option would be to properly set the value
attribute instead of IDs and see whether the value is in the values array:
HTML:
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
JS:
$('#clients').change(function(){
if($.inArray("first", $(this).val()) != -1) {
alert('hi');
}
});
*: In case you might set the selected
attribute on some elements beforehand and want to run the test on page load, you can simply trigger the change event by calling .change()
on the select element.
Upvotes: 1