Dropdown Select Getting Text Value instead of the assined value - javascript

I'm just wondering if this is possible, supposed I have:
<select name = 'region' id = 'region'>
<option value = '1'>Region 1</option>
<select>
Now, I know I get the value of 1 when I select "Region 1". Is there a way to get
the "Region 1" as the value itself without changing the value = '1'. I need that for javascript for other dropdowns.
Sorry I forgot to mention, I'm referring to PHP. I know that:
$value = $_POST['region'];
will the value of 1, how can I get just the text to pass on $_POST?

var el = document.getElementById('region');
var text = el.selectedIndex == -1 ? null : el.options[el.selectedIndex].text;
console.log(text);

Javascript:
var value1 = document.getElementById("region");
var value2 = value1.options[value1.selectedIndex].text;
alert(value2);

js
$("#region").change(function(){
var domNode = document.getElementById("region");
var value = domNode.selectedIndex;
var selected_text = domNode.options[value].text;
alert(selected_text);
});

First of all, as you haven't mentioned whether you are planning on supporting legacy browsers or not, I've decided to add support for that browsers as well. My script works with all IE versions (IE7 inclusive).
So, first we attach our eventlistener to your select element. Then we retrieve the text of the selected option and return the value;
Have a look at this => DEMO
If you want to submit it via $_POST than do the following ->
Create a hidden input element, set its name attribute to say select, then set its value to the value of our text variable (we will have that variable when one of our options is selected) - See the code below.
After submitting your form you can retrieve the value like so => $_POST['select'] (select is the name attribute we have assigned to our hidden input element)
Javascript
//attaching the eventlistener (modified the code to make it compatible with older IE versions)
function attach(element,listener,ev,tf){
if(element.attachEvent) {
//support for older IE (IE7 inclusive)
element.attachEvent("on"+listener,ev);
}else{
//modern browsers
element.addEventListener(listener,ev,tf);
}
}
function returnTextofTheSelectedElement(sel){
//getting and returning the text of the selected option
selectedIndex = sel[sel.selectedIndex];
return text = selectedIndex.innerText ? selectedIndex.innerText : selectedIndex.textContent;
}
var select = document.getElementById('region');
attach(select,'change',function(){
//pass the select tag you want to get the text of
//*returnTextofTheSelectedElement* function returns our text
alert(returnTextofTheSelectedElement(select));
//so you can store it in a *variable* and use it when submitting your form
text = returnTextofTheSelectedElement(select);
//if you want to submit it via $_POST than do the following
//create a hidden *input* element, set its name attribute to say *select*, then set its value to the value of our *text* variable
input = document.createElement('input');
input.type = 'hidden';
input.name = 'select';
input.value = text;
select.parentNode.appendChild(input);
alert('The value/text of the hidden input is '+input.value);
//when submitting the form, it will also submit out hidden input with the value (text) of the selected option
//you can retrieve the value like so => *$_POST['select']*
},false);
HTML
<select name='region' id='region'>
<option value='1'>Region 1</option>
<option value='2'>Region 2</option>
<option value='3'>Region 3</option>
<select>

Cross Browser:
var select = document.getElementById('region');
if(select.addEventListener) {
select.addEventListener('change', function(evt) {
var target = evt.target || evt.srcElement;
var selected = target[target.selectedIndex];
var text = selected.textContent || selected.innerText;
alert(text);
});
}
else if(select.attachEvent) {
select.attachEvent('onchange', function(evt) {
var target = evt.target || evt.srcElement;
var selected = target[target.selectedIndex];
var text = selected.textContent || selected.innerText;
alert(text);
});
}
http://jsfiddle.net/LrETq/

$(select#region option).click(function(){
var textOfTheSelectedOption= $(this).text();
alert( textOfTheSelectedOption);
});

You can get text value like this. Is it helpful?
var e = document.getElementById("region");
var value = e.options[e.selectedIndex].text;
console.log(value);

<script>
function getSelectedText(){
var theSelect= document.getElementById("region");
var theText= theSelect.options[theSelect.selectedIndex].text;
alert(theText);
}
</script>
<select name = 'region' id = 'region' onchange="getSelectedText()">
<option value = '1'>Region 1</option>
<option value = '2'>Region 2</option>
<select>

<form method="post" action="action.php">
<select name = 'region' id = 'region' onchange="fnc()">
<option value = '1'>Region 1</option>
<option value = '2'>Region 2</option>
<select>
<input type="hidden" name="hidden_region" id="hidden_region">
<input type="submit" value="Send">
</form>
<script type="text/javascript">
function fnc(){
var el = document.getElementById('region');
var text = el.selectedIndex == -1 ? '' : el.options[el.selectedIndex].text;
document.getElementById('hidden_region').value = text;
}
</script>
in php post will be like
$value = $_POST['hidden_region'];

Related

how to get dropdown (HTML Select) text against it value from local storage?

I am working on an existing project where I have to get the dropdown (HTML select) Text against its selected value in jquery.
I am storing the dropdown value in localstorage to get the value again if the user refreshed the page so I can maintain the same text against its value.
For demonstration, I created a similar code. My desired output will be:
If the value is 0 then in the console it should print Select Value...
<select class="form-control " id="test" name="test" placeholder="Select Value...">
<option value="0">Select Value...</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
</select>
$(document).ready(function() {
debugger;
var value = $("#test").val(),
currentTestValue = localStorage.getItem("test_selected_value");
if (currentTestValue === undefined || currentTestValue === '' || currentTestValue === null) {
localStorage.setItem("test_selected_value", 0);
} else {
localStorage.setItem("test_selected_value", value);
}
var textValue = $("#test").options[value.selectedIndex].text;
console.log(textValue);
});
find() is used to retrieve child elements from the DOM. Using an integer (in a string) is not a valid selector.
To find an option within a select by its value you can use an attribute selector or filter():
var textValue = $("#test option").filter((i, opt) => opt.value == value).text();
Also note that the logic to set the localStorage item can be simplified. Here's an updated version of your code:
$(document).ready(function() {
var value = $("#test").val();
var currentTestValue = localStorage.getItem("test_selected_value");
localStorage.setItem("test_selected_value", currentTestValue || value);
var textValue = $("#test option").filter((i, opt) => opt.value == value).text();
console.log(textValue);
});
Example in jsFiddle - as the SO snippet editor restricts access to localStorage.
Since you already have set the value of the select - The selected text value will be:
$("#test option:selected").text();

Displaying key and values of the options in a dropdown using javascript

function keyy(id)
{
var value;
var selected;
var select = document.getElementById(id);
if(value != null)
select.options[selected].text = value;
selected = select.selectedIndex;
var key;
key =select.options[selected].value;
value= select.options[selected].text;
select.options[selected].innerHTML = key;
}
<select id="Carss" name="Cars" onchange="keyy(this.id)" >
<option value="A">Audi</option>
<option value="M">Mercedes</option>
</select>
I have n dropdown values. When I select one value, the corresponding key should be displayed. The drop down should be the values and the display item shoud be the coresponding key.
Have atached the image for the reference.
My code :
var value;
var selected;
function keyy(id) {
var select = document.getElementById(id);
if(value != null)
select.options[selected].text = value;
selected = select.selectedIndex;
var key;
key =select.options[selected].value;
value= select.options[selected].text;
select.options[selected].text = key;
}
What you're trying to do is impossible (with a native <select>). The item you see in the closed <select> is simply the <option> that is currently selected. When you open the drop-down, you see the same <option> in two places - in the "selection" and in the "list". You cannot see a different value in each of the places, when it's the same <option>.
You could, however, show the selected value somewhere else, e.g. in a second element next to the <select>.
This is not a perfect answer..
But a possible work around..
function key() {
document.getElementById("Carss").style.width = "100px"
}
function key2() {
document.getElementById("Carss").style.width = "34px"
document.getElementById("Carss").blur();
}
<select id="Carss" name="Cars" onfocus="key()" onchange="key2()" style="width:34px">
<option value="A">Audi</option>
<option value="M">Mercedes</option>
</select>

How would I dynamically create input boxes on the fly?

I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.
What programming language would I need to do this in? I'm using PHP for the overall website.
Here is an example that uses jQuery to achieve your goals:
Assume you have following html:
<div>
<select id="input_count">
<option value="1">1 input</option>
<option value="2">2 inputs</option>
<option value="3">3 inputs</option>
</select>
<div>
<div id="inputs"> </div>
And this is the js code for your task:
$('#input_count').change(function() {
var selectObj = $(this);
var selectedOption = selectObj.find(":selected");
var selectedValue = selectedOption.val();
var targetDiv = $("#inputs");
targetDiv.html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
You can simplify this code as follows:
$('#input_count').change(function() {
var selectedValue = $(this).val();
var targetDiv = $("#inputs").html("");
for(var i = 0; i < selectedValue; i++) {
targetDiv.append($("<input />"));
}
});
Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/
You can read more about jQuery: http://jquery.com/
I would go for jQuery.
To start with look at change(), empty() and append()
http://api.jquery.com/change/
http://api.jquery.com/empty/
http://api.jquery.com/append/
Doing it in javascript is quite easy. Assuming you've got a number and an html element where to insert. You can obtain the parent html element by using document.getElementById or other similar methods. The method assumes the only children of the parentElement is going to be these input boxes. Here's some sample code:
function addInput = function( number, parentElement ) {
// clear all previous children
parentElement.innerHtml = "";
for (var i = 0; i < number; i++) {
var inputEl = document.createElement('input');
inputEl['type'] = 'text';
// set other styles here
parentElement.appendChild(inputEl);
}
}
for the select change event, look here: javascript select input event
you would most likely use javascript(which is what jquery is), here is an example to show you how it can be done to get you on your way
<select name="s" onchange="addTxtInputs(this)" onkeyup="addTxtInputs(this)">
<option value="0">Add</option>
<option value="1">1</option>
<option value="3">3</option>
<option value="7">7</option>
</select>
<div id="inputPlaceHolder"></div>
javascript to dynamically create a selected number of inputs on the fly, based on Mutahhir answer
<script>
function addTxtInputs(o){
var n = o.value; // holds the value from the selected option (dropdown)
var p = document.getElementById("inputPlaceHolder"); // this is to get the placeholder element
p.innerHTML = ""; // clears the contents of the place holder each time the select option is chosen.
// loop to create the number of inputs based apon `n`(selected value)
for (var i=0; i < n; i++) {
var odiv = document.createElement("div"); //create a div so each input can have there own line
var inpt = document.createElement("input");
inpt['type'] = "text"; // the input type is text
inpt['id'] = "someInputId_" + i; // set a id for optional reference
inpt['name'] = "someInputName_" + i; // an unique name for each of the inputs
odiv.appendChild(inpt); // append the each input to a div
p.appendChild(odiv); // append the div and inputs to the placeholder (inputPlaceHolder)
}
}
</script>

update existing option in select list

Let's say that I have select list with 3 options inside:
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
Now, I want to update one of these options, so i create textfield & button.
The option appear inside the textfield everytime i press on one of the options at the select list.
Can someone direct me what do i need to do?
thanks
Adding up to the first example that we had this morning jsfiddle
HTML:
<select id='myselect'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<input type='text' value='1' name='mytext' id='mytext' />
<button value='add' id='addbtn' name='addbtn'>add</button>
<button value='edit' id='editbtn' name='editbtn'>edit</button>
<button value='delete' id='deletebtn' name='deletebtn'>delete</button>
JavaScript:
var myselect = document.getElementById('myselect');
function createOption() {
var currentText = document.getElementById('mytext').value;
var objOption = document.createElement("option");
objOption.text = currentText;
objOption.value = currentText;
//myselect.add(objOption);
myselect.options.add(objOption);
}
function editOption() {
myselect.options[myselect.selectedIndex].text = document.getElementById('mytext').value;
myselect.options[myselect.selectedIndex].value = document.getElementById('mytext').value;
}
function deleteOption() {
myselect.options[myselect.selectedIndex] = null;
if (myselect.options.length == 0) document.getElementById('mytext').value = '';
else document.getElementById('mytext').value = myselect.options[myselect.selectedIndex].text;
}
document.getElementById('addbtn').onclick = createOption;
document.getElementById('editbtn').onclick = editOption;
document.getElementById('deletebtn').onclick = deleteOption;
myselect.onchange = function() {
document.getElementById('mytext').value = myselect.value;
}
Basically i added an edit field that when clicked it'll edit the value and text of the currently selected option, and when you select a new option it'll propogate the textfield with the currently selected option so you can edit it. Additionally, i also added a delete function since i figure you might need it in the future.
Use jquery :selected selector and val() method.
$('select:selected').val($('input_textbox').val());
First of all always give an ID to your input tags. For eg in this case you can do something like: <select id='myDropDown'>
Once you have the ID's in place its simple matter of picking up the new value from textbox and inserting it into the dropdown:
Eg:
// Lets assume the textbox is called 'myTextBox'
// grab the value in the textbox
var textboxValue = document.getElementById('myTextBox').value;
// Create a new DOM element to be inserted into Select tag
var newOption = document.createElement('option');
newOption.text = textboxValue;
newOption.value = textboxValue;
// get handle to the dropdown
var dropDown = document.getElementById('myDropDown');
// insert the new option tag into the dropdown.
try {
dropDown.add(newOption, null); // standards compliant; doesn't work in some versions of IE
}
catch(ex) {
dropDown.add(newOption); // IE only
}
Below is a pure js example using your markup.
EDIT
After rereading your question Im not sure if you wanted the option to update when a user clicked the button or not.. To just put the option into an input you can do this.
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
}
To update the option to what the user typed in is below.
http://jsfiddle.net/loktar/24cHN/6/
Markup
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<br/>
<input type="text" id="inputEl"/>
<button id="button">Update</button>
Javascript
var select = document.getElementsByTagName("select")[0],
input = document.getElementById("inputEl"),
button = document.getElementById("button");
select.onchange = function(){
input.value = this[this.selectedIndex].text;
var selected = this,
selectedIndex = this.selectedIndex;
button.onclick = function(){
selected[selectedIndex].text = input.value;
}
}

set option "selected" attribute from dynamic created option

I have a dynamically created select option using a javascript function. the select object is
<select name="country" id="country">
</select>
when the js function is executed, the "country" object is
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
...
<option value="ID">Indonesia</option>
...
<option value="ZW">Zimbabwe</option>
</select>
and displaying "Indonesia" as default selected option. note : there is no selected="selected" attribute in that option.
then I need to set selected="selected" attribute to "Indonesia", and I use this
var country = document.getElementById("country");
country.options[country.options.selectedIndex].setAttribute("selected", "selected");
using firebug, I can see the "Indonesia" option is like this
<option value="ID" selected="selected">Indonesia</option>
but it fails in IE (tested in IE 8).
and then I have tried using jQuery
$( function() {
$("#country option:selected").attr("selected", "selected");
});
it fails both in FFX and IE.
I need the "Indonesia" option to have selected="selected" attribute so when I click reset button, it will select "Indonesia" again.
changing the js function to dynamically create "country" options is not an option. the solution must work both in FFX and IE.
thank you
You're overthinking it:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;
Good question. You will need to modify the HTML itself rather than rely on DOM properties.
var opt = $("option[val=ID]"),
html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>.
It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.
I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/
Instead of modifying the HTML itself, you should just set the value you want from the relative option element:
$(function() {
$("#country").val("ID");
});
In this case "ID" is the value of the option "Indonesia"
So many wrong answers!
To specify the value that a form field should revert to upon resetting the form, use the following properties:
Checkbox or radio button: defaultChecked
Any other <input> control: defaultValue
Option in a drop down list: defaultSelected
So, to specify the currently selected option as the default:
var country = document.getElementById("country");
country.options[country.selectedIndex].defaultSelected = true;
It may be a good idea to set the defaultSelected value for every option, in case one had previously been set:
var country = document.getElementById("country");
for (var i = 0; i < country.options.length; i++) {
country.options[i].defaultSelected = i == country.selectedIndex;
}
Now, when the form is reset, the selected option will be the one you specified.
// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);​​
What you want to do is set the selectedIndex attribute of the select box.
country.options.selectedIndex = index_of_indonesia;
Changing the 'selected' attribute will generally not work in IE. If you really want the behavior you're describing, I suggest you write a custom javascript reset function to reset all the other values in the form to their default.
This works in FF, IE9
var x = document.getElementById("country").children[2];
x.setAttribute("selected", "selected");
Make option defaultSelected
HTMLOptionElement.defaultSelected = true; // JS
$('selector').prop({defaultSelected: true}); // jQuery
HTMLOptionElement MDN
If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:
const EL_country = document.querySelector('#country');
EL_country.value = 'ID'; // Set SELECT value to 'ID' ("Indonesia")
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
</select>
</form>
The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia',
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, '');
EL_country.value = 'ID';
EL_country.options[EL_country.selectedIndex].defaultSelected = true;
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
Make option defaultSelected while dynamically creating options
To make an option selected while populating the SELECT Element, use the Option() constructor MDN
var optionElementReference = new Option(text, value, defaultSelected, selected);
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia', // <<< make this one defaultSelected
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
const DF_options = document.createDocumentFragment();
Object.keys(countries).forEach(key => {
const isIndonesia = key === 'ID'; // Boolean
DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))
});
EL_country.appendChild(DF_options);
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.
SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected
Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness
The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness
one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.
Comparison test of the different methods
const EL_select = document.querySelector('#country');
const TPL_options = `
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
`;
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver
const mutationCB = (mutationsList, observer) => {
mutationsList.forEach(mu => {
const EL = mu.target;
if (mu.type === 'attributes') {
return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);
}
});
};
// (PREPARE SOME TEST FUNCTIONS)
const testOptionsSelectedByProperty = () => {
const test = 'OPTION with Property selected:';
try {
const EL = [...EL_select.options].find(opt => opt.selected);
console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testOptionsSelectedByAttribute = () => {
const test = 'OPTION with Attribute selected:'
try {
const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));
console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testSelect = () => {
console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);
}
const formReset = () => {
EL_select.value = '';
EL_select.innerHTML = TPL_options;
// Attach MutationObserver to every Option to track if Attribute will change
[...EL_select.options].forEach(EL_option => {
const observer = new MutationObserver(mutationCB);
observer.observe(EL_option, {attributes: true});
});
}
// -----------
// LET'S TEST!
console.log('\n1. Set SELECT value');
formReset();
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n2. Set HTMLElement.setAttribute()');
formReset();
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n3. Set HTMLOptionElement.defaultSelected');
formReset();
EL_select.options[3].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');
formReset();
EL_select.value = 'ZW'
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
/* END */
console.log('\n*. Getting MutationObservers out from call-stack...');
<form>
<select name="country" id="country"></select>
</form>
Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:
EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!
will actually make the option selected
Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?
Instead test 3. (and 4.) using defaultSelected gives the expected results:
Attribute selected as a named Selectedness state.
Property selected on the Element Object, with a Boolean value.
select = document.getElementById('selectId');
var opt = document.createElement('option');
opt.value = 'value';
opt.innerHTML = 'name';
opt.selected = true;
select.appendChild(opt);
// Get <select> object
var sel = $('country');
// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }
// Select index
sel.options.selectedIndex = i;
Begitu loh.
This should work.
$("#country [value='ID']").attr("selected","selected");
If you have function calls bound to the element just follow it with something like
$("#country").change();
You could search all the option values until it finds the correct one.
var defaultVal = "Country";
$("#select").find("option").each(function () {
if ($(this).val() == defaultVal) {
$(this).prop("selected", "selected");
}
});
Vanilla JS
Use this for Vanilla Javascript, keeping in mind that you can feed the example "numbers" array with any data from a fetch function (for example).
The initial HTML code:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
</select>
</label>
Some values select tag:
const selectionList = document.getElementById('the_selection_id');
const numbers = ['1','3','5'];
numbers.forEach(number => {
const someOption = document.createElement('option');
someOption.setAttribute('value', number);
someOption.innerText = number;
if (number == '3') someOption.defaultSelected = true;
selectionList.appendChild(someOption);
})
You'll get:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
<option value="1">1</option>
<option value="3" selected>3</option>
<option value="5">5</option>
</select>
</label>
You can solve this on ES6 like this:
var defaultValue = "ID";
[...document.getElementById('country').options].map(e => e.selected = (e.value == defaultValue));
I haven't test in other browsers but in Chrome works just fine.
...document.getElementById('country').options using the spread operator you cast options as an array.
.map allows you to apply a function to each element of your array.
e represents each <option> element of your object so you can access its attributes like .select and .value as getter and setter.
Because you .select receives a boolean option you want to assign when its value is equal to your default value.
To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)
elem.checked=true;
Where elem is a reference to the option to be selected.
So for the above issue:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].checked=true;
This works for me, even when the options are not wrapped in a .
If all of the tags share the same name, they should uncheck when the new one is checked.
Realize this is an old question, but with the newer version of JQuery you can now do the following:
$("option[val=ID]").prop("selected",true);
This accomplishes the same thing as Box9's selected answer in one line.
The ideas on this page were helpful, yet as ever my scenario was different. So, in modal bootstrap / express node js / aws beanstalk, this worked for me:
var modal = $(this);
modal.find(".modal-body select#cJourney").val(vcJourney).attr("selected","selected");
Where my select ID = "cJourney" and the drop down value was stored in variable: vcJourney
I was trying something like this using the $(...).val() function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>:
// Set value to Indonesia ("ID"):
$('#country').value = 'ID'
...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.
To set value in JavaScript using set attribute , for selected option tag
var newvalue = 10;
var x = document.getElementById("optionid").selectedIndex;
document.getElementById("optionid")[x].setAttribute('value', newvalue);

Categories