Change options in select with JavaScript without loosing chosen - javascript

I'm trying to reload the options list of a select with JavaScript and JQuery, but I need to preserve previous chosen values.
This is my code:
var temp = $('#SelectName').chosen().val();
select = document.getElementById('SelectName');
if (select.options.length > 0) {
$('#SelectName').find('option').remove();
}
for (var i = 0; i < result.length; i++) {
var option = document.createElement('option');
option.value = result[i].myIdVariable;
option.text = result[i].myTextVariable;
select.appendChild(option);
}
$('#SelectName').chosen(temp);
$('#SelectName').trigger('chosen:updated');
With this code I loose all the chosen values.

I solved with this code:
var temp = $('#SelectName').val();
select = document.getElementById('SelectName');
if (select.options.length > 0) {
$('#SelectName').find('option').remove();
}
for (var i = 0; i < result.length; i++) {
var option = document.createElement('option');
option.value = result[i].myIdVariable;
option.text = result[i].myTextVariable;
select.appendChild(option);
}
$('#SelectName').val(temp);
$('#SelectName').trigger('chosen:updated');
The difference is that now I use:
var temp = $('#SelectName').val();
and
$('#SelectName').val(temp);
previously:
var temp = $('#SelectName').chosen().val();
and
$('#SelectName').chosen(temp);

Related

Replacing option in select field (not adding)

I have a select field as follows:
<select id="field">
I add options based on values found in another div (OtherDiv) on my page like this:
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}
However, I would like to set up some alternative value for the field to show, if there are no matches to the regex. How would I best achieve that?
Use if condition
window.onload = function onload()
{
var OtherDiv = document.getElementById('OtherDiv').innerHTML;
var result = OtherDiv.match(/SomeRegex/gi);
var select = document.getElementById("field");
if(result.length){
for(var i = 0; i < result.length; i++)
{
var option = document.createElement("option");
option.value = i+1;
option.innerHTML = result[i];
select.add(option);
}
}else{
//add alternative options here
var option = document.createElement("option");
option.innerHTML = "No records found"; //whatever text you want to show
select.add(option);
}
}

Auto populate option tag not working java script

I'm trying to populate number in select - option tag .But my script fills number at only one select tag
HTML :
<div class="form_row">
<label>Week Num</label>
<select class="form_select1" id="weeknum"></select>
<b class="bold1">&nbsp TO &nbsp</b>
<select class="form_select1" id="weeknum1"></select>
</div>
Javascript :
<script>
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
select1.add(option, 0);
}
</script>
How do i achieve that ?
You can add an element only once to a parent node, so you need to create another option element:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
option.text = option.value = i;
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}
Here's the JSFIddle.
Try this ...
var option1 = document.createElement('option');
option1.text = option1.value = i;
select.add(option1, 0);
var option2 = document.createElement('option');
option2.text = option2.value = i;
select1.add(option2, 0);
... creating a distinct "option" for each select list. The created elements cannot be reused.
You need to create a distinct option element for each list. A given DOM element can only be in one place in the DOM.
edit: I see it's already answered... well, my first answer :)
try this:
var select = document.getElementById("weeknum");
var select1 = document.getElementById("weeknum1");
for (var i = 52; i >= 1; i--) {
var option = document.createElement('option');
var option1 = document.createElement('option');
option.text = option.value = option1.text = option1.value = i;
select.add(option, 0);
select1.add(option1, 0);
}

Fill html select using javascript array

I want to fill a select with and array values. I don't see why my code doesnt work. I am a beginner.This is my script
var mes = new Array();
for(i = 0; i < 12; i++){
mes[i] = i;
}
var sel = document.getElementById('mes');
for(var i = 0; i < mes.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = mes[i];
opt.value = mes[i];
sel.appendChild(opt);
}
And this is the html select:
<select name="mes" id="mes"></select>

Why won't the addEventListener trigger on change?

Trying to get the eventlistener to run, i.e. when I select United Kingdom, another selection box will appear to select county (county() function), but for some reason the addEventListener will not call the function, and I can't fathom how to pass the selected country to the county function? Any ideas please.
function countries() {
xmlRequest("countries.xml");
var country_selector = document.createElement("SELECT");
country_selector.id = "cou n tryselection";
document.getElementById("quiz").appendChild(country_selector);
var t = document.getElementById("countryselection");
var c_opt = document.createElement("option");
c_opt.text = "Please select";
c_opt.selected = true;
t.add(c_opt);
c_opt = document.createElement("option");
c_opt.text = "United Kingdom";
c_opt.value = "1";
t.add(c_opt);
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
var x = xmlDoc.getElementsByTagName("country");
for (i = 0; i < x.length; i++) {
var opt = document.createElement("option");
opt.text = x[i].getElementsByTagName("country_name ")[0].childNodes[0].nodeValue;
t.add(opt);
}
}
function county(Country) {
if (!document.getElementById("countyselection")) {
if (Country === "1") {
xmlRequest("counties.xml");
document.getElementById("quiz").innerHTML += "<select id='countyselection'></select>";
var t = document.getElementById("countyselection");
var y = xmlDoc.getElementsByTagName("county");
for (j = 0; j < y.length; j++)
{
var opt = document.createElement("option");
var txt = y[j].getElementsByTagName("county_name")[0].childNodes[0].nodeValue;
opt.text = txt;
t.add(opt);
}
}
} else {
var f = document.getElementById("countyselection");
document.getElementById("countyselection").parentNode.removeChild(f);
}
}
Because you're calling the function, not referencing it, and you have a space in the function name.
change
document.getElementById("countryselection").addEventListener("change", count y(this.value), false);
to
document.getElementById("countryselection").addEventListener("change", function() {
county(this.value);
}, false);
Also note that things like this
country_selector.id = "cou n tryselection";
is completely invalid, you can't use random text with spaces as an ID

Add item to dropdown list in HTML using JavaScript

I have this JavaScript+HTML to populate a dropdown menu but it is not working, am i doing anything wrong? Note I want the drop down menu to be filled on page Load
<!DOCTYPE html>
<html>
<head>
<script>
function addList(){
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
}
</script>
</head>
<body>
<select id="year" name="year"></select>
</body>
</html>
Since your script is in <head>, you need to wrap it in window.onload:
window.onload = function () {
var select = document.getElementById("year");
for(var i = 2011; i >= 1900; --i) {
var option = document.createElement('option');
option.text = option.value = i;
select.add(option, 0);
}
};
You can also do it in this way
<body onload="addList()">
For higher performance, I recommend this:
var select = document.getElementById("year");
var options = [];
var option = document.createElement('option');
//for (var i = 2011; i >= 1900; --i)
for (var i = 1900; i < 2012; ++i)
{
//var data = '<option value="' + escapeHTML(i) +'">" + escapeHTML(i) + "</option>';
option.text = option.value = i;
options.push(option.outerHTML);
}
select.insertAdjacentHTML('beforeEnd', options.join('\n'));
This avoids a redraw after each appendChild, which speeds up the process considerably, especially for a larger number of options.
Optional for generating the string by hand:
function escapeHTML(str)
{
var div = document.createElement('div');
var text = document.createTextNode(str);
div.appendChild(text);
return div.innerHTML;
}
However, I would not use these kind of methods at all.
It seems crude. You best do this with a documentFragment:
var docfrag = document.createDocumentFragment();
for (var i = 1900; i < 2012; ++i)
{
docfrag.appendChild(new Option(i, i));
}
var select = document.getElementById("year");
select.appendChild(docfrag);
Try this
<script type="text/javascript">
function AddItem()
{
// Create an Option object
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = "New Value";
opt.value = "New Value";
// Add an Option object to Drop Down List Box
document.getElementById('<%=DropDownList.ClientID%>').options.add(opt);
}
<script />
The Value will append to the drop down list.
Try to use appendChild method:
select.appendChild(option);
i think you have only defined the function. you are not triggering it anywhere.
please do
window.onload = addList();
or trigger it on some other event
after its definition
see this fiddle

Categories

Resources