Select not displaying correct selected value after update - javascript

This is my select in html:
<select id="bgPosition">
<option value="left top" selected="selected">Left Top</option>
<option value="center top">Center Top</option>
..
</select>
On page load I need to update the selected value with another one, so I tried with .each .prop and this:
function setActiveOption(el,val){
$(el).find('option:selected').removeAttr('selected');
$(el).find('option[value="'+val+'"]').attr('selected','selected');
console.log('selected: '+$('#bgPosition').val())
}
All ok for other select boxes, but not for #bgPosition I think because values contains spaces.
selected attribute is in right place, but is displaying first option as selected
Any idea how can this be fixed?
I also tried with different jQuery libraries
UPDATE: This is my fiddle and how I am running functions.

Given your example fiddle, the only select element that doesn't respect the value you set is the middle one, #bgRepeat, and that's because by default you've got two option set with the selected attribute.
To fix the problem, only provide one option with the selected attribute.
That being said, a better solution would be to just use .val() as a setter on the select itself, which is a one-liner and therefore renders the setActiveOption() function redundant. Try this:
var template = [{
"mainBgImgPosition": "right bottom",
"mainBgImgRepeat": "no-repeat",
"mainBgImgSize": "cover"
}]
jQuery(function($) {
var Builder = {
initialized: false,
initialize: function() {
if (this.initialized)
return;
this.initialized = true;
$('#bgPosition').val(template[0].mainBgImgPosition);
$('#bgRepeat').val(template[0].mainBgImgRepeat);
$('#bgSize').val(template[0].mainBgImgSize);
}
}
Builder.initialize();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="bgPosition" id="bgPosition">
<option value="left top" selected="selected">Left Top</option>
<option value="left center">Left Center</option>
<option value="left bottom">Left Bottom</option>
<option value="center top">Center Top</option>
<option value="center center">Center Center</option>
<option value="center bottom">Center Bottom</option>
<option value="right top">Right Top</option>
<option value="right center">Right Center</option>
<option value="right bottom">Right Bottom</option>
</select>
<select name="bgRepeat" id="bgRepeat">
<option value="repeat" selected="selected">Repeat All</option>
<option value="repeat-x">Repeat X</option>
<option value="repeat-y">Repeat Y</option>
<option value="no-repeat">No Repeat</option>
</select>
<select name="bgSize" id="bgSize">
<option value="auto" selected="selected">Auto</option>
<option value="cover">Cover</option>
</select>

i tried your code in a fiddle and it worked for me.
https://jsfiddle.net/b8t1yavu/
What are you passing into the function setActiveOption for el. It might now be working because of that. You could call the function in two ways.
setActiveOption('#bgPosition','center top')
OR
setActiveOption(bgPosition,'center top')
If you want it call it with the second method, you have to modify your code a bit. here is a fiddle for that https://jsfiddle.net/b8t1yavu/1/

I don't know how you call your function but it seemed to work fine when I run it in JSFiddle. You need to call your function with the id of the element as the first parameter and the FULL value of the option as the second parameter as HTML does not concider words as seperate values.
setActiveOption('#bgPosition', 'center'); // Does not work
setActiveOption('#bgPosition', 'center top'); // Works fine
https://jsfiddle.net/Youmy001/uyun2soo

Related

Select dropdown value by index using JQuery [duplicate]

If you know the Index, Value or Text. also if you don't have an ID for a direct reference.
This, this and this are all helpful answers.
Example markup
<div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
A selector to get the middle option-element by value is
$('.selDiv option[value="SEL1"]')
For an index:
$('.selDiv option:eq(1)')
For a known text:
$('.selDiv option:contains("Selection 1")')
EDIT: As commented above the OP might have been after changing the selected item of the dropdown. In version 1.6 and higher the prop() method is recommended:
$('.selDiv option:eq(1)').prop('selected', true)
In older versions:
$('.selDiv option:eq(1)').attr('selected', 'selected')
EDIT2: after Ryan's comment. A match on "Selection 10" might be unwanted. I found no selector to match the full text, but a filter works:
$('.selDiv option')
.filter(function(i, e) { return $(e).text() == "Selection 1"})
EDIT3: Use caution with $(e).text() as it can contain a newline making the comparison fail. This happens when the options are implicitly closed (no </option> tag):
<select ...>
<option value="1">Selection 1
<option value="2">Selection 2
:
</select>
If you simply use e.text any extra whitespace like the trailing newline will be removed, making the comparison more robust.
None of the methods above provided the solution I needed so I figured I would provide what worked for me.
$('#element option[value="no"]').attr("selected", "selected");
You can just use val() method:
$('select').val('the_value');
By value, what worked for me with jQuery 1.7 was the below code, try this:
$('#id option[value=theOptionValue]').prop('selected', 'selected').change();
There are a number of ways to do this, but the cleanest approach has been lost among the top answers and loads of arguments over val(). Also some methods changed as of jQuery 1.6, so this needs an update.
For the following examples I will assume the variable $select is a jQuery object pointing at the desired <select> tag, e.g. via the following:
var $select = $('.selDiv .opts');
Note 1 - use val() for value matches:
For value matching, using val() is far simpler than using an attribute selector: https://jsfiddle.net/yz7tu49b/6/
$select.val("SEL2");
The setter version of .val() is implemented on select tags by setting the selected property of a matching option with the same value, so works just fine on all modern browsers.
Note 2 - use prop('selected', true):
If you want to set the selected state of an option directly, you can use prop (not attr) with a boolean parameter (rather than the text value selected):
e.g. https://jsfiddle.net/yz7tu49b/
$option.prop('selected', true); // Will add selected="selected" to the tag
Note 3 - allow for unknown values:
If you use val() to select an <option>, but the val is not matched (might happen depending on the source of the values), then "nothing" is selected and $select.val() will return null.
So, for the example shown, and for the sake of robustness, you could use something like this https://jsfiddle.net/1250Ldqn/:
var $select = $('.selDiv .opts');
$select.val("SEL2");
if ($select.val() == null) {
$select.val("DEFAULT");
}
Note 4 - exact text match:
If you want to match by exact text, you can use a filter with function. e.g. https://jsfiddle.net/yz7tu49b/2/:
var $select = $('.selDiv .opts');
$select.children().filter(function(){
return this.text == "Selection 2";
}).prop('selected', true);
although if you may have extra whitespace you may want to add a trim to the check as in
return $.trim(this.text) == "some value to match";
Note 5 - match by index
If you want to match by index just index the children of the select e.g. https://jsfiddle.net/yz7tu49b/3/
var $select = $('.selDiv .opts');
var index = 2;
$select.children()[index].selected = true;
Although I tend to avoid direct DOM properties in favour of jQuery nowadays, to future-proof code, so that could also be done as https://jsfiddle.net/yz7tu49b/5/:
var $select = $('.selDiv .opts');
var index = 2;
$select.children().eq(index).prop('selected', true);
Note 6 - use change() to fire the new selection
In all the above cases, the change event does not fire. This is by design so that you do not wind up with recursive change events.
To generate the change event, if required, just add a call to .change() to the jQuery select object. e.g. the very first simplest example becomes https://jsfiddle.net/yz7tu49b/7/
var $select = $('.selDiv .opts');
$select.val("SEL2").change();
There are also plenty of other ways to find the elements using attribute selectors, like [value="SEL2"], but you have to remember attribute selectors are relatively slow compared to all these other options.
Using jquery-2.1.4, I found the following answer to work for me:
$('#MySelectionBox').val(123).change();
If you have a string value try the following:
$('#MySelectionBox').val("extra thing").change();
Other examples did not work for me so that's why I'm adding this answer.
I found the original answer at:
https://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
Exactly it will work try this below methods
For normal select option
<script>
$(document).ready(function() {
$("#id").val('select value here');
});
</script>
For select 2 option trigger option need to use
<script>
$(document).ready(function() {
$("#id").val('select value here').trigger('change');
});
</script>
$(elem).find('option[value="' + value + '"]').attr("selected", "selected");
You could name the select and use this:
$("select[name='theNameYouChose']").find("option[value='theValueYouWantSelected']").attr("selected",true);
It should select the option you want.
Answering my own question for documentation. I'm sure there are other ways to accomplish this, but this works and this code is tested.
<html>
<head>
<script language="Javascript" src="javascript/jquery-1.2.6.min.js"></script>
<script type="text/JavaScript">
$(function() {
$(".update").bind("click", // bind the click event to a div
function() {
var selectOption = $('.selDiv').children('.opts') ;
var _this = $(this).next().children(".opts") ;
$(selectOption).find("option[index='0']").attr("selected","selected");
// $(selectOption).find("option[value='DEFAULT']").attr("selected","selected");
// $(selectOption).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[value='DEFAULT']").attr("selected","selected");
// $(_this).find("option[text='Default']").attr("selected","selected");
// $(_this).find("option[index='0']").attr("selected","selected");
}); // END Bind
}); // End eventlistener
</script>
</head>
<body>
<div class="update" style="height:50px; color:blue; cursor:pointer;">Update</div>
<div class="selDiv">
<select class="opts">
<option selected value="DEFAULT">Default</option>
<option value="SEL1">Selection 1</option>
<option value="SEL2">Selection 2</option>
</select>
</div>
</body>
</html>
For setting select value with triggering selected:
$('select.opts').val('SEL1').change();
For setting option from a scope:
$('.selDiv option[value="SEL1"]')
.attr('selected', 'selected')
.change();
This code use selector to find out the select object with condition, then change the selected attribute by attr().
Futher, I recommend to add change() event after setting attribute to selected, by doing this the code will close to changing select by user.
$('#select option[data-id-estado="3"]').prop("selected",true).trigger("change");
// or
$('#select option[value="myValue"]').prop("selected",true).trigger("change");
Try this
you just use select field id instead of #id (ie.#select_name)
instead of option value use your select option value
<script>
$(document).ready(function() {
$("#id option[value='option value']").attr('selected',true);
});
</script>
I use this, when i know the index of the list.
$("#yourlist :nth(1)").prop("selected","selected").change();
This allows the list to change, and fire the change event.
The ":nth(n)" is counting from index 0
i'll go with:-
$("select#my-select option") .each(function() { this.selected = (this.text == myVal); });
/* This will reset your select box with "-- Please Select --" */
<script>
$(document).ready(function() {
$("#gate option[value='']").prop('selected', true);
});
</script>
For Jquery chosen if you send the attribute to function and need to update-select option
$('#yourElement option[value="'+yourValue+'"]').attr('selected', 'selected');
$('#editLocationCity').chosen().change();
$('#editLocationCity').trigger('liszt:updated');
if you want to not use jQuery, you can use below code:
document.getElementById("mySelect").selectedIndex = "2";
The $('select').val('the_value'); looks the right solution and if you have data table rows then:
$row.find('#component').val('All');
Thanks for the question. Hope this piece of code will work for you.
var val = $("select.opts:visible option:selected ").val();
There are a few suggestions why you should use prop instead of attr. Definitely use prop as I've tested both and attr will give you weird results except for the simplest of cases.
I wanted a solution where selecting from an arbitrarily grouped select options automatically selected another select input on that same page. So for instance, if you have 2 dropdowns - one for countries, and the other for continents. In this scenario, selecting any country automatically selected that country's continent on the other continent dropdown.
$("#country").on("change", function() {
//get continent
var originLocationRegion = $(this).find(":selected").data("origin-region");
//select continent correctly with prop
$('#continent option[value="' + originLocationRegion + '"]').prop('selected', true);
});
$("#country2").on("change", function() {
//get continent
var originLocationRegion = $(this).find(":selected").data("origin-region");
//select continent wrongly with attr
$('#continent2 option[value="' + originLocationRegion + '"]').attr('selected', true);
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<form>
<h4 class="text-success">Props to the good stuff ;) </h4>
<div class="form-row">
<div class="form-group col-md-6 col-sm-6">
<label>Conuntries</label>
<select class="custom-select country" id="country">
<option disabled selected>Select Country </option>
<option data-origin-region="Asia" value="Afghanistan">Afghanistan</option>
<option data-origin-region="Antartica" value="Antartica">Antartica</option>
<option data-origin-region="Australia" value="Australia">Australia</option>
<option data-origin-region="Europe" value="Austria">Austria</option>
<option data-origin-region="Asia" value="Bangladesh">Bangladesh</option>
<option data-origin-region="South America" value="Brazil">Brazil</option>
<option data-origin-region="Africa" value="Cameroon">Cameroon</option>
<option data-origin-region="North America" value="Canada">Canada</option>
<option data-origin-region="South America" value="Chile">Chile</option>
<option data-origin-region="Asia" value="China">China</option>
<option data-origin-region="South America" value="Ecuador">Ecuador</option>
<option data-origin-region="Australia" value="Fiji">Fiji</option>
<option data-origin-region="North America" value="Mexico">Mexico</option>
<option data-origin-region="Australia" value="New Zealand">New Zealand</option>
<option data-origin-region="Africa" value="Nigeria">Nigeria</option>
<option data-origin-region="Europe" value="Portugal">Portugal</option>
<option data-origin-region="Africa" value="Seychelles">Seychelles</option>
<option data-origin-region="North America" value="United States">United States</option>
<option data-origin-region="Europe" value="United Kingdom">United Kingdom</option>
</select>
</div>
<div class="form-group col-md-6 col-sm-6">
<label>Continent</label>
<select class="custom-select" id="continent">
<option disabled selected>Select Continent</option>
<option disabled value="Africa">Africa</option>
<option disabled value="Antartica">Antartica</option>
<option disabled value="Asia">Asia</option>
<option disabled value="Europe">Europe</option>
<option disabled value="North America">North America</option>
<option disabled value="Australia">Australia</option>
<option disabled value="South America">South America</option>
</select>
</div>
</div>
</form>
<hr>
<form>
<h4 class="text-danger"> Attributing the bad stuff to attr </h4>
<div class="form-row">
<div class="form-group col-md-6 col-sm-6">
<label>Conuntries</label>
<select class="custom-select country-2" id="country2">
<option disabled selected>Select Country </option>
<option data-origin-region="Asia" value="Afghanistan">Afghanistan</option>
<option data-origin-region="Antartica" value="Antartica">Antartica</option>
<option data-origin-region="Australia" value="Australia">Australia</option>
<option data-origin-region="Europe" value="Austria">Austria</option>
<option data-origin-region="Asia" value="Bangladesh">Bangladesh</option>
<option data-origin-region="South America" value="Brazil">Brazil</option>
<option data-origin-region="Africa" value="Cameroon">Cameroon</option>
<option data-origin-region="North America" value="Canada">Canada</option>
<option data-origin-region="South America" value="Chile">Chile</option>
<option data-origin-region="Asia" value="China">China</option>
<option data-origin-region="South America" value="Ecuador">Ecuador</option>
<option data-origin-region="Australia" value="Fiji">Fiji</option>
<option data-origin-region="North America" value="Mexico">Mexico</option>
<option data-origin-region="Australia" value="New Zealand">New Zealand</option>
<option data-origin-region="Africa" value="Nigeria">Nigeria</option>
<option data-origin-region="Europe" value="Portugal">Portugal</option>
<option data-origin-region="Africa" value="Seychelles">Seychelles</option>
<option data-origin-region="North America" value="United States">United States</option>
<option data-origin-region="Europe" value="United Kingdom">United Kingdom</option>
</select>
</div>
<div class="form-group col-md-6 col-sm-6">
<label>Continent</label>
<select class="custom-select" id="continent2">
<option disabled selected>Select Continent</option>
<option disabled value="Africa">Africa</option>
<option disabled value="Antartica">Antartica</option>
<option disabled value="Asia">Asia</option>
<option disabled value="Europe">Europe</option>
<option disabled value="North America">North America</option>
<option disabled value="Australia">Australia</option>
<option disabled value="South America">South America</option>
</select>
</div>
</div>
</form>
</div>
As seen in the code snippet, prop works correctly every time, but attr fails to select properly once the option has been selected once.
Keypoint: We're usually interested in the property of the attribute, so its safer to use prop over attr in most situations.

Remove Selected Value in Dropdown List Using JavaScript

I have an HTML list that I want to remove elements from as the user chooses. I've tried using this code from this thread but my issue seems to be accessing the element.
Here's my HTML:
<div id="ShipPlacement">
Ship:
<select name="shipSelec" id="shipSelec">
<option value="aircraftCarrier">Aircraft Carrier</option>
<option value="battleship">Battleship</option>
<option value="cruiser">Cruiser</option>
<option value="destroyer">Destroyer</option>
<option value="destroyer">Destroyer</option>
<option value="submarine">Submarine</option>
<option value="submarine">Submarine</option>
</select>
<button type="button" onclick="placeShip()">Remove Selected Ship</button>
And here's my JavaScript:
$( document ).ready(function() {
var shipList=document.getElementById('shipSelec');
});
function placeShip() {
shipList.remove(shipList.options[shipList.selectedIndex].value;);
shipList.remove(shipList.options[shipList.selectedIndex]);
shipList.remove(shipList.options[selectedIndex]);
shiplist.remove([shipList.selectedIndex])
}
I have several instances of the remove() method but that none of them work.
However, the best way I can convey my error to you is through JSFiddle.
As you've jQuery loaded on the page, use it to bind events and remove element from DOM.
First, bind click event on the button using click. Use the :selected pseudo-selector to select the selected option from the dropdown and remove() to remove it from DOM.
$('button').click(function() {
$('#shipSelec option:selected').remove();
});
$(document).ready(function() {
$('button').click(function() {
$('#shipSelec option:selected').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ShipPlacement">
Ship:
<select name="shipSelec" id="shipSelec">
<option value="aircraftCarrier">Aircraft Carrier</option>
<option value="battleship">Battleship</option>
<option value="cruiser">Cruiser</option>
<option value="destroyer">Destroyer</option>
<option value="destroyer">Destroyer</option>
<option value="submarine">Submarine</option>
<option value="submarine">Submarine</option>
</select>
<button type="button">Remove Selected Ship</button>
</div>
Updated Fiddle
Note that there are several issues in your code
In fiddle "LOAD TYPE" option should be selected to "No Wrap".
jQuery is not included. This can be included using the "Frameworks & Extensions" option in the JavaScript tab
Syntax error in the first statement in the placeShip() near .value;);
shipList is local to the ready callback and hence not accessible from outside of it. Not even in placeShip()
With pure JavaScript
var shipList = document.getElementById('shipSelec');
shipList.options[shipList.selectedIndex].remove();
Fiddle
$("#btn").click(function() {
$("#shipSelec option:disabled").prop("disabled", false)
$("#shipSelec option:selected").prop("disabled", true)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ShipPlacement">
Ship:
<select name="shipSelec" id="shipSelec">
<option value="aircraftCarrier">Aircraft Carrier</option>
<option value="battleship">Battleship</option>
<option value="cruiser">Cruiser</option>
<option value="destroyer">Destroyer</option>
<option value="destroyer">Destroyer</option>
<option value="submarine">Submarine</option>
<option value="submarine">Submarine</option>
</select>
<button type="button" id="btn">Remove Selected Ship</button>
I suggest just disable the option not remove

Multiple options from one drop down giving alternate results - Javascript/html

I'm looking to have separate sections of my form become visible dependant on the selection from a drop down menu.
Currently i'm having two issues, its only hiding the first area i want hidden and also i'm struggling with the syntax to get the multiple options working using if statements.
Am i looking at this the right way or is there an easier way of doing this.
In the code below i've only got 2 if statements as i've been struggling to get that correct so haven't done it for all 8 options i need to.
function showfield(name){
if (name=='Supplier meetings') {
document.getElementById('div1').style.display="block";
} else {
document.getElementById('div1').style.display="none";
if (name=='Product meetings') {
document.getElementById('div2').style.display="block";
} else {
document.getElementById('div2').style.display="none";
}
}
}
function hidefield() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
document.getElementById('div4').style.display='none';
document.getElementById('div5').style.display='none';
document.getElementById('div6').style.display='none';
document.getElementById('div7').style.display='none';
document.getElementById('div8').style.display='none';
}
in my html i have:
<body onload="hidefield()">
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1">Worked hours</option>
<option value="2">Overtime</option>
<option value="3">Sickness</option>
<option value="4">Unpaid leave</option>
<option value="5">Compassionate leave</option>
<option value="6">Holiday inc bank holidays</option>
<option value="7">Team meetings</option>
<option value="8">One to ones</option>
<option value="9">One to one prep</option>
<option value="10">Huddles</option>
<option value="Supplier meetings">Supplier meetings</option>
<option value="Product meetings">Product meetings</option>
<option value="Training/coaching">Training/coaching</option>
<option value="Handling other peoples cases">Handling other peoples cases</option>
<option value="15">Project work</option>
<option value="16">Surgery time for GK</option>
<option value="17">Letter checks and feedback</option>
<option value="18">MI/Reporting/RCA</option>
</select>
Then divs that contain the parts i need displayed off each option.
Hope that makes sense.
Thanks
Instead of writing condition for each option value, you can use the value directly in selecting the div that is to be shown:
function showfield(name){
hidefield();
document.getElementById( 'div-' + name).style.display="block";
}
For this to work, your id's should match up with corresponding option values.
e.g. <option value="1">1</option>
corresponding div:
<div id="div-1"></div>
You can add a data-div attribute to every option which will be ID of respective div which will be shown and other divs will be hidden.
You need a class on every div so they can be hidden using that class name except the div which will be shown based on selection.
HTML
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1" data-div="one">Worked hours</option>
<option value="2" data-div="two">Overtime</option>
</select>
<div id="one">First Div</div>
<div id="two">Second Div</div>
Javascript
function showfield(val)
{
var divID = $("select[name=acti]").find("option[value='" + val + "']").attr("data-div");
$(".divClass").hide();//You can also use hidefield() here to hide other divs.
$("#" + divID).show();
}

Select option from selectbox

How can I select an option with javascript (/console in google chrome)?
This is a part of the html code:
<nobr>
Element<br>
<span class="absatz">
<br>
</span>
<select name="element" class="selectbox" style="width:114" size="12" onchange="doDisplayTimetable(NavBar, topDir);">
<option value="0">- All -</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">X</option>
<option value="4">C</option>
<option value="5">D</option>
<option value="6">E</option>
<option value="7">F</option>
<option value="8">G</option>
<option value="9">H</option>
<option value="10">I</option>
<option value="11">J</option>
<option value="12">K</option>
<option value="13">L</option>
<option value="14">M</option>
<option value="15">N</option>
<option value="16">O</option>
<option value="17">P</option>
<option value="18">Q</option>
<option value="19">R</option>
</select>
</nobr>
Or http://pastebin.com/JSaKg4HB
I already tried this:
document.getElementsByName("element")[0].value = 1;
But it gives me this error:
Uncaught TypeError: Cannot set property 'value' of undefined
at :2:48
at Object.InjectedScript._evaluateOn (:875:140)
at Object.InjectedScript._evaluateAndWrap (:808:34)
at Object.InjectedScript.evaluate (:664:21)
EDIT:
I I tried it but it don't works on for the full website. Maybe because there is another html tag inside the first html tag(if I download the website, there is another html file called welcome.html where the selectbox is.) I thinks it's in an iFrame, because chrome gives me the Option "show Frame".
EDIT 2:
I can access the frame where the selectbox is but I still won't find the selectbox. Here is the code of the frame(not the full code): pastebin.com/iVUeDbYV
Try this:
document.querySelectorAll('[name="element"]')[0].value;
Although it is very weird that getElementsByName is not working for you. Are you sure the element is in the same document, and not in an iFrame?
The simple answer:
document.getElementById("select_element").selectedIndex = "option index";
Where option index is the index of the option in the dropdown that you'd like to activate.
You can get the index of an option by using this:
var selected = document.querySelector( '#'+div+' > option[value="'+val+'"]' );
Where div is the ID of the <select> tag.
how this helps!
This will do what you want.
document.querySelector('[name="element"]').value = 4 // The value you want to select
and this will retrieve the value
var value = document.querySelector('[name="element"]').value; // 4
this explains what's going on
var option = document.querySelector('[name="element"]');//option element
option.value; // 4
option.selectedIndex; // 4
option.selectedOptions; // [<option value="4">C</option>]
option.selectedOptions[0].innerText; // C
option.selectedOptions[0].value; // 4
Remember that selectedOptions is an array because more than one option may be selected, in those cases, you will have to loop through the array to get each value. As per Hanlet EscaƱo's comment, make sure your code is set to execute after the DOM has loaded.
window.onload = function() {
document.querySelector('[name="element"]').value = 0; // sets a default value
}

populate second dropdown based on selected value of first dropdown

I have two dropdown i want when i select for example from dropdown test1 option with value a
the second dropdown test2 show only the options that have value a
<select name="test1" id="test1" onchange="document.getElementById('test2').value=this.value">
<option value="Select">Select</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select id="test2" name="test2">
<option value="Select">Select</option>
<option value="a">a</option>
<option value="a">b</option>
<option value="a">c</option>
<option value="b">1</option>
<option value="b">2</option>
<option value="b">3</option>
<option value="c">c</option>
</select>
Or you can go this way:
jQuery(document).ready(function($){
var options = $('#test2 option');
$('#test1').on('change', function(e){
$('#test2').append(options);
$('#test2 option[value!=' + $(this).val() +']').remove();
});
});
fiddle
Since you've tagged this with JQuery, if I were to not alter your HTML at all, you could do this by changing the JS in your onchange from this:
document.getElementById('test2').value=this.value
. . . to this:
$("test2").find("option").hide();
$("test2").find("[value^='" + $("test1").val() + "']").show();
That would hid all of the options in the "test2" dropdown, and then show all of the ones that have a value that starts with the value of the currently selected "test1" option.
Note: this will also work if you chose to update the code to only use the "test1" values as a prefix for the "test2" values. ;)
UPDATE: Fixed a typo in the code.
Like it was said, you really don't want to do it this way as each option should have a unique value....but here is one way to accomplish it: jsFiddle
Using jQuery, you could check for the value of the selected option in test1, hide all those in test2 that don't match then show those with a matching value.
$('#test1').on('change', function() {
$('#test2 option:not(option[value='+$(this).val()+'])').hide();
$('#test2 option[value='+$(this).val()+']').show();
});

Categories