Reputation:
I am using a select dropdown. I used ids in value and in option tag content i used a string. Now i want to match a string with jQuery
here is the code:
<select id="options-1" class=" product3090 options" name="products[3090][options][]">
<option value="">Select an option</option>
<option value="1">Personal Use - Digital</option>
<option value="2">Small Organisational License</option>
<option value="4">Medium Organisational License</option>
<option value="5">Large Organisational License</option>
<option value="6">University/College License</option>
<option value="7">Personal Use - DVD</option>
</select>
When i change a drop down in jQuery it alerts me all values correctly. Now i want to match "Organisational" word that if this match it alerts me "yes" else "No"
Here is my jQuery code:
<script type="text/javascript">
$(document).change( function () {
var theValue = $("#options-1").text();
//alert(theValue);
if(theValue.indexOf("Organisational") > -1){
alert("Yes");
}
else{
alert("No");
}
});
</script>
When i select any of them it always alert me yes. What can i do any idea
Upvotes: 2
Views: 78
Reputation: 38112
$("#options-1").text()
will give you text content of every option inside select
.
In your case, you need to get text of the selected option only, so you can do:
var theValue = $("#options-1").find('option:selected').text();
instead of:
var theValue = $("#options-1").text();
Also, you need to attach change event to the select
element instead of document
:
$("#options-1").change( function () {
Upvotes: 1
Reputation: 15393
$("#options-1").change( function () {
var theValue = $("option:selected").text();
alert(theValue);
if(theValue.indexOf("Organisational") > -1){
alert("Yes");
}
else{
alert("No");
}
});
Upvotes: 1
Reputation: 82251
use $("#options-1 option:selected").text();
to get selected option text.
$("#options-1").text()
returns text off all the option that are there in select
.
also change $(document).change
to $('#options-1').change
:
$('#options-1').change( function () {
var theValue = $("#options-1 option:selected").text();
if(theValue.indexOf("Organisational") > -1){
alert("Yes");
}
else{
alert("No");
}});
Upvotes: 2
Reputation: 57105
Try
var theValue = $("#options-1 option:selected").text();
Get the selected option.
You can attach change handler to the select element
$('#options-1').change(function () {
var theValue = $(this).find('option:selected').text();
if (theValue.indexOf("Organisational") > -1) {
alert("Yes");
} else {
alert("No");
}
});
Upvotes: 1