Reputation: 32321
I have got a drop down as
<select id="BrandNames">
<option value="3000">General</option>
<option value="3001">KFC</option>
<option value="3002">Chutneys</option>
</select>
Once forming the drodown successfully
I am trying to change its value , this way
var setthisvalue = 'KFC' ;
$("#BrandNames").val(setthisvalue);
This is my jsfiddle
http://jsfiddle.net/y9cyag0n/1/
This is not setting the value of combobox ?
My requirement is that i need to set the value of created combobox based on the setthisvalue Value and after that the combobox shouldn't be editable ??
Could anybody please let me know why it isn't setting the value ??
Upvotes: 0
Views: 46
Reputation: 28387
You are trying to set the value to "KFC" which is not the value of the option
. The value is "3001".
So, you need to set it to the proper value.
On the other hand, if all you have is the text string and you want to set the value based on that string, then you need to find the string in the options and use the found value to set.
Once done, you can set the "disabled" property to "true", to disable the select.
Snippet:
var value = 'KFC' ;
var $opt = $("#BrandNames").children(":contains(" + value + ")");
$("#BrandNames").val($opt.val());
$("#BrandNames").prop("disabled", true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="BrandNames">
<option value="3000">General</option>
<option value="3001">KFC</option>
<option value="3002">Chutneys</option>
</select>
Note: This is just an idea. Be warned that if there are multiple options with similar text, then you need to find workarounds. Also, note that :contains
is not exact match, it literally means "contains" i.e. even if part of the string matches. Ideally you should be doing a filter
on options.
.
Upvotes: 1
Reputation: 136114
You have the text not the value, you can find the right option by text, and use that to set the value and then disable the dropdown:
var value = 'KFC' ;
var option = $("#BrandNames option").filter(function(){
return $(this).text() == value;
});
$("#BrandNames").val(option.val()).prop('disabled',true);
Updated fiddle: http://jsfiddle.net/y9cyag0n/3/
Upvotes: 1
Reputation: 24001
$("#BrandNames option:contains('"+ value +"')").prop('selected', true).parent().prop('disabled', true);
SeeDEMO
Upvotes: 1
Reputation: 34556
Because "KFC" is not a value; the corresponding value is "3001".
$("#BrandNames").val('3001').prop('disabled', true);
Upvotes: 1