How do I select an option by class? - javascript

I tried using $('.className').show(); and $('.className').hide(); but it doesn't seem to work in IE. Is there another way to group options by class in a drop down list? I found this question but the answer is looking for the value "a" or "c".
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
How do I look for the actual class?
EDIT
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>

I've never seen anyone try to call hide/show on option elements before, and I imagine IE just doesn't allow you to do that. The selection is probably matching just fine, but IE is not hiding the elements. The selection for removing would be the same as for calling show hide...
$('.className').remove();
or
$('option.className').remove();
or
$('#theSelect option.className').remove();

You can add the disabled attribute to the options you don't want to use:
http://jsfiddle.net/sadmicrowave/Fnvqb/

$('select[class~="cactus"]')
$('option[class~="cactus"]')
javascript:(function(){
var out = "hi\n";
out += $('*[class~="cactus"]').html2string() ;
alert( out );
})()
For future reference, instead of describing in words the html ... show actual html

This demonstration code shows one way of how you can achieve option filtering... it would need modification to determine which candidate items are removed as I just hardcoded for purpose of demonstration, but it shows you what you need to consider - when you remove the items, you need to consider the ordering by which they're added back. The easiest way to bypass this problem is to keep a copy of the original list and then when you unfilter, just remove the remaining items, replacing them with what was originally there - otherwise you have to worry about keeping sort data.
So here's my drop down definition:
<select id="mySelector">
<option class="group1">Item 1</option>
<option class="group2">Item 2</option>
<option class="group1">Item 3</option>
<option class="group2">Item 4</option>
<option class="group1">Item 5</option>
</select>
<input type="button" id="removeItems" value="Remove candidate items" />
<input type="button" id="addItems" value="Add them back" />
And the jquery to filter/restore the items:
$(function () {
var originalOptionData;
$("#removeItems").bind('click', function () {
/* store original copy for rollback */
originalOptionData = $("#mySelector option");
$("#mySelector option.group2").remove();
});
$("#addItems").bind('click', function () {
var selector = $("#mySelector");
selector.children().remove();
selector.append(originalOptionData);
});
});
This could be turned into a select filter jquery plugin relatively simply I suppose, but I didn't go that far...

Related

Changing a textbox based on a dropdown html array with jQuery

So I am finding issues doing this, I am curious if its because I am using HTML form arrays.
Anywho so heres my problem, I want to change a dropdown box and have it change the text in a textbox to that value! Sound's simple enough right?
Well here's my failed attempt:
<select id=discount[0] name=discount[0]>
<option value=1>option 1</option>
<option value=2>option 2</option>
</select>
<input type=text id=postdiscount[0]>
And my JS:
$("#discount[0]").change(function () {
$("#postdiscount[0]").val(this.value);
});
JSFiddle if you guys wanna play about:
http://jsfiddle.net/t75ut97f/3/
EDIT:
Has nothing to do with form items being in an array :X!
You need to escape the brackets, then just use this.value
$("#discount\\[0\\]").change(function () {
$("#postdiscount\\[0\\]").val(this.value);
});
http://jsfiddle.net/t75ut97f/2/

Change a Select Option value with no id/class

There's this website that I want to change how they display their dropdown menu.
http://i.stack.imgur.com/Wu718.jpg
I wanted to make it so that the default value is "Items for Sale", instead of "Forum Topics"
Here's their source code.
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
Since I don't really care about how it looks, I just want to change the value="topics" to value="s" even without changing the texts.
I've read some tutorials, but they mostly use IDs and Classes as a selector, in this case, how do I target this Select from many other in their website and change the value.
You can use:
$('select[name=sec]').val('s');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
I think this is what you're describing in the comments below:
var dropdown = $('select[name=sec]');
// change the s option to items
dropdown.find('option[value=s]').attr('value', 'items');
// change the topics option to s
dropdown.find('option[value=topics]').attr('value', 's');
// change the dropdown's value to s
// (first option should continue to be selected because its value is now s)
dropdown.val('s');
// (this is for demo purposes only)
dropdown.after($("<div>").text("New HTML is: " + dropdown[0].outerHTML));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You can use the name or any other attribute.
for css
select[name="sec"]
or jquery
$('select[name="sec"]').
DEMO inspect element from your browser to see the changes
you can select a select dropdown list with select[name=sec] and select the first option with option:first
$('select[name=sec] option:first').val('s');
and if you need to change any of options just use .eq()
$('select[name=sec] option').eq(0).val('s'); // eq(0) for the first option element . eq(1) for the second option element ...
If you want to make selected an other option use this code:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
This script removes the default selection (the first option) and select the option which has "s" value. For the Demo:
$('select[name="sec"]').find('option:selected').removeAttr('selected');
$('select[name="sec"]').find('option[value="s"]').attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<select name="sec" style="margin-top:5px;width:138px;">
<option value="topics">Forum Topics</option>
<option value="s">Items for Sale</option>
<option value="b">Want to Buys</option>
<option value="users">Members</option>
</select>
You have to find this element in the DOM. For this you should find the first parent container element of the which has ID or CLASS attribute. From that element you can create a search for the element what you want by using the .find() method.
If there're more element which has name attribute with "sec" value you should build a chain of find which separate that you want. For that you can use these function templates:
$(#CONTAINER_ID).find(.SUBCONTAINER_CLASS).find(ELEMENT_TYPE);
$(#CONTAINER_ID).find(SUBCONTAINER_TYPE).find(OTHER_SUBCONTAINER_TYPE:eq(X));

Execute some Javascript onChange using options?

I've been lurking a bit and couldn't find the answer. Basically I have a bunch of buttons that I want to turn into a drop down menu and have the code be executed onChange. But, I'm new to javascript and I am having a hard time figuring out how this would work. I somewhat got it to work, but I couldn't get it to work with more than one option. Here's what I have:
<button class="lightbutton" onclick="lightswitch(1,true);lightswitch(2,true);lightswitch(3,true);">
All lights on</button>
<button class="lightbutton" onclick="lightswitch(1,false);lightswitch(2,false);lightswitch(3,false);">
All lights off</button>
I got the lights to turn on by doing this:
<form name="functions">
<select name="jumpmenu" onChange="lightswitch(1,true);lightswitch(2,true);lightswitch(3,true);">
<option>LightFunctions</option>
<option value="*";>Light 1 On</option>
<option value="*";>Light 1 Off</option>
</select>
</form>
Now, I see why it works -- it's just telling it that whenever it changes to turn on all the lights. But how do I change the "onChange" to make it so it gets whichever option I have chosen?
I think I'm missing some JS but unsure.
I appreciate the help.
To have that select element control just the first lightswitch you can do this:
<select name="jumpmenu" onChange="lightswitch(1,this.value==='on');">
<option value="on";>Light 1 On</option>
<option value="off";>Light 1 Off</option>
</select>
That is, instead of hardcoding true as the second parameter to lightswitch() test the current value of the select element. (Note that I've changed the value attributes to something more meaningful. The expression this.value==='on' will evaluate to either true or false.)
Within the select's onChange attribute this will refer to the select element itself.
EDIT: To have the same select control multiple parameters you can add some data- attributes to the option elements to store as many extra parameters per option as needed (in this case I think you only need one extra). And I'd move the logic out of the inline attribute:
<select name="jumpmenu" onChange="jumpChange(this);">
<option value="">LightFunctions</option>
<option data-switchNo="1" value="on";>Light 1 On</option>
<option data-switchNo="1" value="off";>Light 1 Off</option>
<option data-switchNo="2" value="on";>Light 2 On</option>
<option data-switchNo="2" value="off";>Light 2 Off</option>
<option data-switchNo="3" value="on";>Light 3 On</option>
<option data-switchNo="3" value="off";>Light 3 Off</option>
</select>
function jumpChange(sel) {
if (sel.value === "") return; // do nothing if user selected first option
var whichLight = +sel.options[sel.selectedIndex].getAttribute("data-switchNo");
lightswitch(whichLight, sel.value==='on');
sel.value = ""; // reset select to display the "Light Functions" option
}
Demo: http://jsfiddle.net/N7b8j/2/
Within the jumpChange(sel) function that I added the parameter sel will be the select element (set as this from the onChange attribute). The "magic" happens on this line:
var whichLight = +sel.options[sel.selectedIndex].getAttribute("data-switchNo");
To explain that line: sel.options[sel.selectedIndex] gets a reference to the currently selected option, and .getAttribute("data-switchNo") gets that option's data- attribute. The + converts the attribute from a string to a number.

Showing alert dialog on dropdown select in jQuery

I'm trying to show an alert dialog on dropdown select in jQuery but it doesn't seem to be working. What am I doing wrong? My code is here: http://jsfiddle.net/AyCFt/6/
HTML
<select>
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager">Project Manager</option>
<option id="#projectmanager2">Project Manager 2</option>
</select>​
JS
$(document).ready(function() {
$("#projectmanager").click(function(){
alert("Hello");
});
$("#projectmanager 2").click(function(){
alert("Hello to you too!");
});
});
​
This way you can show a unique alert box for each projectmanager.
<select id='ddselect'>
<option selected="selected" >Please select your Login</option>
<option>--------------------------</option>
<option id="projectmanager">Project Manager</option>
<option id="projectmanager2">Project Manager 2</option>
</select>
$(document).ready(function() {
$("#ddselect").change(function(){
if($("#ddselect option:selected").attr("id") == "projectmanager"){
alert("Project manager 1 alert");
}
if($("#ddselect option:selected").attr("id") == "projectmanager2"){
alert("Project manager 2 alert");
}
});
});
An elegant and also flexible way of doing this: http://jsfiddle.net/AyCFt/13/
The jsFiddle just tackles the question asked (displaying the alerts). The code below shows that the code is much more flexible, but avoids the if/switch statements of other answers if they are not needed.
HTML: I added an id in the select element and custom attributesnamed data-alert containing the message for each option that needs to display an alert upon being selected. These attributes are valid in HTML5 and forward, but they work fine in earlier HTML versions also:
<select id="selectAlert">
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager" data-alert="Hello">Project Manager</option>
<option id="#projectmanager2" data-alert="Hello to you too">Project Manager 2</option>ello
</select>
Javascript (version 1): If you just want the alerts and are a fan of brevity and clean code:
$(function() {
$("#selectAlert").change(function(){
var alertMsg = $(this).find(":selected").attr("data-alert");
if(alertMsg) alert(alertMsg);
});
});
Note that this solution does not force you display the text or the value of options. You are free to choose any alert message exactly as you wanted.
WHY DO THINGS THIS WAY? This kind of solution decouples logic from data. So if you are producing the select using server-side code (either as part of a dynamically generated page or through AJAX) you ideally do not want to have to produce your Javascript in the same way if you can avoid it. Whereas your code and the code in some other solutions puts the alert messages in the Javascript code, this solution puts them inside each option, in the HTML.
Javascript (version 2): If there are more things you need to do:
$(document).ready(function() {
$("#selectAlert").change(function(){
var $selected = $(this).find(":selected"); //faster than $("#selectAlert :selected") as it only searches among the options in the select and not the whole DOM like another answer's solution
//some code: you can do what you want with $selected here get it's value, its id, etc etc
var alertMsg = $selected.attr("data-alert")
if(alertMsg) alert(alertMsg);
//some more code here
});
});
PROBLEM WITH CODE POSTED IN THE QUESTION:
The problem with the code you posted was that you were using click on the options of the select element. As you discovered this event is not defined for the individual options.
A GENERAL POINT ABOUT UI EVENTS: In general, it is best to try to work with device-independent, more "semantic" events wherever possibly. In this case the event we are using is one that tells us that the value of the select has changed. It does not matter if the user did so using the mouse, the keyboard, or touch!!!
Try with the following code. It will work for you.
<select id='ddselect'>
<option selected="selected" >Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager">Project Manager</option>
<option id="#projectmanager2">Project Manager 2</option>
</select>
$(document).ready(function() {
$("#ddselect").change(function(){
alert("Hello");
});
});
Make the below change to html:
<select id="SelectOptions">
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager">Project Manager</option>
<option id="#projectmanager2">Project Manager 2</option>
</select>​​​​​​​​​​
Make the below change to the javascript:
$(document).ready(function() {
$("#SelectOptions").change(function(){
alert($("#SelectOptions option:selected")[0].text);
});
});
This will display the selected option.
As stated above you can use onchange on the select element. to respond uniquely to each value you can use a switch statement like so:
http://jsfiddle.net/AyCFt/11/
This is but one way to do it (and depending on your final implementation, there's probably a better way to go about this).
Add value attributes to your markup so that the message is contained in the value:
<select id="changeMe">
<option selected="selected">Please select your Login</option>
<option disabled="disabled">--------------------------</option>
<option id="projectmanager" value="Hello">Project Manager</option>
<option id="projectmanager2" value="Hello to you too">Project Manager 2</option>
</select>​
Since option elements don't [often] receive .click() events, it's much better to add a .change() handler to the select element and go from there:
$(document).ready(function() {
$('select#changeMe').change(function(e) {
var self = $(this), //cache lookup
selected = self.children('option:selected'), //get the selected option
i = selected.index('select#changeMe option'), //grab the index, relative to all options
message = selected.val(); //get the message
if (i > 1) { //ignore "Please select" and "---"
alert(message);
}
});
});​
Updated fiddle: http://jsfiddle.net/AyCFt/12/
To customise the alert message, you would either need to run a 'switch' statement (or a switch-like series of 'if' statements) in the Javascript code, or encode the alert message into the HTML and access that (example here http://jsfiddle.net/AFguq/):
<select id="SelectOptions">
<option selected="selected">Please select your Login</option>
<option>--------------------------</option>
<option id="#projectmanager" alertText="Hello">Project Manager</option>
<option id="#projectmanager2" alertText="Hello to you too">Project Manager 2</option>
</select>​
(javascript:)
$(document).ready(function() {
$("#SelectOptions").change(function(){
alert($("#SelectOptions option:selected").attr('alertText'));
});
});​

Change the selected value of a drop-down list with jQuery

I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using jQuery.
Using regular JavaScript, I would do something like:
ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
However, I need to do this with jQuery, because I'm using a CSS class for my selector (stupid ASP.NET client ids...).
Here are a few things I've tried:
$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
How can I do it with jQuery?
Update
So as it turns out, I had it right the first time with:
$("._statusDDL").val(2);
When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error
Could not set the selected property. Invalid Index
I'm not sure if it's a bug with jQuery or Internet Explorer 6 (I'm guessing Internet Explorer 6), but it's terribly annoying.
jQuery's documentation states:
[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in jQuery versions 1.2 and above.
You most likely want this:
$("._statusDDL").val('2');
Add .change() to see the option in the dropdown list frontend:
$("._statusDDL").val('2').change();
With hidden field you need to use like this:
$("._statusDDL").val(2);
$("._statusDDL").change();
or
$("._statusDDL").val(2).change();
These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.
Things are a little more complicated if this isn't the case.
To read the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex");
To set the selected index of a drop down list, you would use this:
$("#dropDownList").prop("selectedIndex", 1);
Note that the prop() feature requires JQuery v1.6 or later.
Let's see how you would use these two functions.
Supposing you had a drop down list of month names.
<select id="listOfMonths">
<option id="JAN">January</option>
<option id="FEB">February</option>
<option id="MAR">March</option>
</select>
You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:
<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />
And here's the JavaScript which these buttons would run:
function btnPrevMonth_Click() {
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
if (selectedIndex > 0) {
$("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
}
}
function btnNextMonth_Click() {
// Note: the JQuery "prop" function requires JQuery v1.6 or later
var selectedIndex = $("#listOfMonths").prop("selectedIndex");
var itemsInDropDownList = $("#listOfMonths option").length;
// If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
if (selectedIndex < (itemsInDropDownList - 1)) {
$("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
}
}
My site is also useful for showing how to populate a drop down list with JSON data:
http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm
Just an FYI, you don't need to use CSS classes to accomplish this.
You can write the following line of code to get the correct control name on the client:
$("#<%= statusDDL.ClientID %>").val("2");
ASP.NET will render the control ID correctly inside the jQuery.
Just try with
$("._statusDDL").val("2");
and not with
$("._statusDDL").val(2);
After looking at some solutions, this worked for me.
I have one drop-down list with some values and I want to select the same value from another drop-down list... So first I put in a variable the selectIndex of my first drop-down.
var indiceDatos = $('#myidddl')[0].selectedIndex;
Then, I select that index on my second drop-down list.
$('#myidddl2')[0].selectedIndex = indiceDatos;
Note:
I guess this is the shortest, reliable, general and elegant solution.
Because in my case, I'm using selected option's data attribute instead of value attribute.
So if you do not have unique value for each option, above method is the shortest and sweet!!
I know this is a old question and the above solutions works fine except in some cases.
Like
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
So Item 4 will show as "Selected" in the browser and now you want to change the value as 3 and show "Item3" as selected instead of Item4.So as per the above solutions,if you use
jQuery("#select_selector").val(3);
You will see that Item 3 as selected in browser.But when you process the data either in php or asp , you will find the selected value as "4".The reason is that , your html will look like this.
<select id="select_selector">
<option value="1">Item1</option>
<option value="2">Item2</option>
<option value="3" selected="selected">Item3</option>
<option value="4" selected="selected">Item4</option>
<option value="5">Item5</option>
</select>
and it gets the last value as "4" in sever side language.
SO MY FINAL SOLUTION ON THIS REGARD
newselectedIndex = 3;
jQuery("#select_selector option:selected").removeAttr("selected");
jQuery("#select_selector option[value='"+newselectedIndex +"']").attr('selected', 'selected');
EDIT: Add single quote around "+newselectedIndex+" so that the same functionality can be used for non-numerical values.
So what I do is actually ,removed the selected attribute and then make the new one as selected.
I would appreciate comments on this from senior programmers like #strager , #y0mbo , #ISIK and others
If we have a dropdown with a title of "Data Classification":
<select title="Data Classification">
<option value="Top Secret">Top Secret</option>
<option value="Secret">Secret</option>
<option value="Confidential">Confidential</option>
</select>
We can get it into a variable:
var dataClsField = $('select[title="Data Classification"]');
Then put into another variable the value we want the dropdown to have:
var myValue = "Top Secret"; // this would have been "2" in your example
Then we can use the field we put into dataClsField, do a find for myValue and make it selected using .prop():
dataClsField.find('option[value="'+ myValue +'"]').prop('selected', 'selected');
Or, you could just use .val(), but your selector of . can only be used if it matches a class on the dropdown, and you should use quotes on the value inside the parenthesis, or just use the variable we set earlier:
dataClsField.val(myValue);
So I changed it so that now it
executes after a 300 miliseconds using
setTimeout. Seems to be working now.
I have run into this many times when loading data from an Ajax call. I too use .NET, and it takes time to get adjusted to the clientId when using the jQuery selector. To correct the problem that you're having and to avoid having to add a setTimeout property, you can simply put "async: false" in the Ajax call, and it will give the DOM enough time to have the objects back that you are adding to the select. A small sample below:
$.ajax({
type: "POST",
url: document.URL + '/PageList',
data: "{}",
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var pages = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$('#locPage' + locId).find('option').remove();
$.each(pages, function () {
$('#locPage' + locId).append(
$('<option></option>').val(this.PageId).html(this.Name)
);
});
}
});
I use an extend function to get client ids, like so:
$.extend({
clientID: function(id) {
return $("[id$='" + id + "']");
}
});
Then you can call ASP.NET controls in jQuery like this:
$.clientID("_statusDDL")
Another option is to set the control param ClientID="Static" in .net and then you can access the object in JQuery by the ID you set.
<asp:DropDownList id="MyDropDown" runat="server" />
Use $("select[name$='MyDropDown']").val().
Just a note - I've been using wildcard selectors in jQuery to grab items that are obfuscated by ASP.NET Client IDs - this might help you too:
<asp:DropDownList id="MyDropDown" runat="server" />
$("[id* = 'MyDropDown']").append("<option value='-1'> </option>"); //etc
Note the id* wildcard- this will find your element even if the name is "ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder1$MyDropDown"
How are you loading the values into the drop down list or determining which value to select? If you are doing this using Ajax, then the reason you need the delay before the selection occurs could be because the values were not loaded in at the time that the line in question executed. This would also explain why it worked when you put an alert statement on the line before setting the status since the alert action would give enough of a delay for the data to load.
If you are using one of jQuery's Ajax methods, you can specify a callback function and then put $("._statusDDL").val(2); into your callback function.
This would be a more reliable way of handling the issue since you could be sure that the method executed when the data was ready, even if it took longer than 300 ms.
<asp:DropDownList ID="DropUserType" ClientIDMode="Static" runat="server">
<asp:ListItem Value="1" Text="aaa"></asp:ListItem>
<asp:ListItem Value="2" Text="bbb"></asp:ListItem>
</asp:DropDownList>
ClientIDMode="Static"
$('#DropUserType').val('1');
In my case I was able to get it working using the .attr() method.
$("._statusDDL").attr("selected", "");
Pure JS
For modern browsers using CSS selectors is not a problem for pure JS
document.querySelector('._statusDDL').value = 2;
function change() {
document.querySelector('._statusDDL').value = 2;
}
<select class="_statusDDL">
<option value="1" selected>A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<button onclick="change()">Change</button>
If we want to find from the option name and then selected options with the jQuery please see below code:-
<div class="control">
<select name="country_id" id="country" class="required-entry" title="Country" data-validate="{'validate-select':true}" aria-required="true">
<option value=""> </option>
<option value="SA">Saudi Arabia</option>
<option value="AF">Afghanistan</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="IS">Iceland</option>
<option value="IN">India</option>
<option value="ID">Indonesia</option>
<option value="IR">Iran</option>
<option value="IQ">Iraq</option>
<option value="IE">Ireland</option>
<option value="IM">Isle of Man</option>
<option value="IL">Israel</option>
<option value="IT">Italy</option>
<option value="JM">Jamaica</option>
<option value="JP">Japan</option>
<option value="JE">Jersey</option>
<option value="JO">Jordan</option>
<option value="AE">United Arab Emirates</option>
<option value="GB">United Kingdom</option>
<option value="US" selected="selected">United States</option>
</select>
</div>
<script type='text/javascript'>
let countryRegion="India";
jQuery("#country option:selected").removeAttr("selected");
let cValue= jQuery("#country option:contains("+countryRegion+")").val();
jQuery("#country option[value='"+cValue +"']").attr('selected', 'selected');
</script>
I hope this will help!

Categories