How to give selected value to option with no value - javascript - javascript

I have a select witch is generated dynamically, it looks like this
<select id="elem">
<option value="3">value 1</option>
<option value="6">value 2</option>
<option value="18">value 3</option>
<option>value 4</option>
</select>
The last option has no value. I am trying to make the select to display the "value 4" option on the first position when the page is loaded, using javascript
Here is what i tried in javascript
var elem = document.getElementById("elem"),
selectedNode = elem.options[elem.selectedIndex];
if ( selectedNode.value === "" ) {
selectedNode.setAttribute('selected','');
}
How can it be done ?

When no value is specified, the value will be the text. You can use hasAttribute to check for the value as well:
var select = document.getElementById("elem");
for (var i = 0; i < select.options.length; i++) {
if (!select.options[i].hasAttribute('value')) {
select.options[i].selected = true;
}
}
Demo: http://jsfiddle.net/tymeJV/682Ap/1/

several ways to do it. if you need to find the option first, the code would be like this . It's looking for an option with non numeric value - unfortunately if you omit the value the text of the option becomes its value
var sel = document.getElementById("elem");
var index = 0;
for(var i = 0;i<sel.options.length;i++){
if (isNaN(sel.options[i].value))
index = i;
}
if you know the index, you can set the selected option as
sel.selectedIndex = index;

Related

Two dynamic select boxes with data attribute in both and dependant on them

How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>

How to populate select options from an array based on a select value?

Trying to get my second select element's options to populate from an array based on the value of the first select element. I can't seem to understand why it only populates the items from the array of the first select element. I know the appendChild is causing the items to keep tacking on at the need, but I've tried to clear the variables, but it seems the option elements that were created stay.
Any help would be great, thanks!
<select id="makeSelect" onChange="modelAppend()">
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect">
</select>
<script>
var audiModels = ["TT", "R8", "A4", "A6"]; //audimodels
var mercModels = ["C230", "B28", "LTX",]; //mercmodels
var bmwModels = ["328", "355", "458i",]; //bmwmodels
var selectedMake = document.getElementById("makeSelect"); //grabs the make select
var selectedModel = document.getElementById("modelSelect"); //grabs the model select
var appendedModel = window[selectedMake.value + "Models"]; // appends "Models" to selectedMake.value and converts string into variable
function modelAppend() {
for (var i = 0; i < appendedModel.length; i ++) { // counts items in model array
var models = appendedModel[i]; // // sets "models" to count of model array
var modelOptions = document.createElement("option"); //create the <option> tag
modelOptions.textContent = models; // assigns text to option
modelOptions.value = models; // assigns value to option
selectedModel.appendChild(modelOptions); //appeneds option tag with text and value to "modelSelect" element
}
}
</script>
This line is fishy:
var appendedModel = window[selectedMake.value + "Models"];
You need to get the element when the value has changed, not on page load. Then you need to remove the options on change too, or you will get a very long list if the user selects multiple times. Use an object to store the arrays, that makes it much easier to access them later. Also better use an event listener instead of inline js (though that's not the main problem here).
Try below code:
let models = {
audiModels: ["TT", "R8", "A4", "A6"],
mercModels: ["C230", "B28", "LTX"],
bmwModels: ["328", "355", "458i"]
}
document.getElementById('makeSelect').addEventListener('change', e => {
let el = e.target;
let val = el.value + 'Models';
let appendTo = document.getElementById('modelSelect');
Array.from(appendTo.getElementsByTagName('option')).forEach(c => appendTo.removeChild(c));
if (!models[val] || !Array.isArray(models[val])) {
appendTo.style.display = 'none';
return;
}
models[val].forEach(m => {
let opt = document.createElement('option');
opt.textContent = opt.value = m;
appendTo.appendChild(opt);
});
appendTo.style.display = '';
});
<select id="makeSelect">
<option value=""></option>
<option value="merc">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</select>
<select id="modelSelect" style="display:none">
</select>

Get options select name from other options select name without form tag

I have this short code which works with form tags.
<select id="district" name="lan" class="country_search"
onchange="showSubcomune(this.value,this.form.undercomune)">
<option value="0" selected>choose country </option>
<option value="10">some comue</option>
</select>
<select name="undercomune" id="undercomune" class="country_search">
<option value="0" selected >chhose comune</option>
</select>
this showSubcomune works fine with form tags when i use this.form.undercomune so it collecte comunes to selected country and show them in the undercomune select option.
the problem is i want use same function in other place BUT without html form tag. How can this be this.form.undercomune ?? in the function ?
have tried those :
this.form.undercomune
this.undercomune
$('#undercomune').val()
But no one works .
any help would be much apreciated thanks.
EDIT:
function showSubKommun(subCat,selectObj) {
selectObj.length = 0;
var j = 0,
elm;
for (var k = 0; (elm = kommun[k]); ++k)
if (elm.lankod == subCat)
selectObj[j++] = new Option(elm.namn, elm.kommunkod);
var x = document.getElementById("undercomune");
var option = document.createElement("option");
option.text = " \xAB choose comune \u00bb ";
option.value = 0;
x.add(option,x[0]);
x[0].setAttribute("selected", "selected");
}
You can get it either by document.getElementById
var elem = document.getElementById('undercomune');
or if you're using jQuery
elem = $('#undercomune')[0]; // the indexer returns native html element

Replace option code with another code by using option index

I have a dropdown list
<select name="answers[0][]">
<option value="0" >Beredskap</option>
<option value="1" >Förbundsledning</option>
<option value="2" >Förbundsledning stab</option>
<option value="3" >Ekonomiavdelningen</option>
</select>
What i am seeking for is to get the value getElementsByTagName('select')[1] and then replace it with
<option value="1" disabled >Förbundsledning</option>
the reason for it is that the list is auto generated so i need to modify the html output instead.
what i have sofar that does not work is :
document.getElementsByTagName('select')[0]
.innerHTML.replace('<option value="1" disabled>apple</option>')
The option with the value 1 happens to be at index 1 in your code, should that always be the case other answers than this one will apply.
In the case where you don't know the order of the generated options and thus don't know the index of the option you want to change, it depends on whether you want to change the text based on the value or the original text.
You could do this:
var options = document.getElementsByTagName("option");
for(var e = 0; e < options.length; e++) {
//change by text
if (options[e].text == "Apple") {
options[e].text = "Förbundsledning";
}
//change by value
if (options[e].value == "1") {
options[e].text = "Förbundsledning";
}
}
you could use jQuery and selectors to find your list box $('#myListBox').val();
you can easily change the value by $('#myListBox').val("new value");
You can also easily iterate over the list of options and do whatever you wish.
$("#id option").each(function()
{
// add $(this).val() to your list
});
How about this ?
var sel = document.getElementsByTagName('select')[0];
sel.innerHTML = sel.innerHTML.replace('Förbundsledning', 'apple');
http://jsfiddle.net/VxhvF/
use function ;
function select_text_replace(option_text, replace_text) {
var el = document.getElementsByTagName('select')[0];
el.innerHTML = el.innerHTML.replace(option_text, replace_text);
};
select_text_replace("Förbundsledning", "apple");
select_text_replace("Ekonomiavdelningen", "apple2");
see sample: http://jsfiddle.net/sm94N/
document.getElementsByTagName('select')[0].options[1].text="apple"
[1] is index of your options item. 0 = Beredskap, 1 = Förbundsledning.

JavaScript seeting selectedIndex to be blank for select do not work

I am trying to make default selection of a dropdown selection to be blank.
If I generate a select dropdown with HTML, it works.
However when I generate the same dropdown with javascript, it does not work.
Please see
http://jsfiddle.net/m2HSb/
<select id="myDropdown">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<div id="yo"></div>
document.getElementById("myDropdown").selectedIndex = -1
var my_select = document.createElement("select")
for ( var i = 0 ; i < 3 ; i++ ) {
my_select.options[i] = new Option(i,i)
}
my_select.selectedIndex = -1
document.getElementById("yo").appendChild(my_select)
Note that the first dropdown is blank, and the second is not.
Apparently you can't set the selectedIndex of a select element that hasn't been inserted into the DOM yet.
If you move my_select.selectedIndex = -1 after the append then it works fine.
var my_select = document.createElement("select");
for ( var i = 0 ; i < 3 ; i++ ) {
my_select.options[i] = new Option(i,i);
}
document.getElementById("yo").appendChild(my_select);
my_select.selectedIndex = -1;
Here's the fiddle.

Categories