problem with dynamicallly adding values to dropdown box - javascript

i want to dynamically add options to drop down boxes
var x =document.getElementById("c");
var optn = document.createElement("OPTION");
optn.text="hhh"
optn.value="val"
x.options.add(optn);
I am doing it inside a loop,with diff values of for val and hhh.Bur sometime i dont see any any values in drop down box , what may be the problem?

Try this one:
var objSelect = document.getElementById("subComponentOSID");
objSelect.options[objSelect.options.length] = new Option('1','1');
objSelect.options[objSelect.options.length] = new Option('2','2');

add is a method of HTMLSelectElement objects, not of HTMLCollection objects.
x.add(optn)

Assuming the element with the id "subComponentOSID", the only apparent issues in your javascript are missing semicolons on the lines where you assign values to optn.text and optn.value. Also, while most browsers will resolve what you mean when calling the add function on an options collection for a select element, you should move your add to the select itself. See the Mozilla reference for HTMLSelectElement, which provides an example.
In the meantime, try replacing the code snippet you provided with this:
var x =document.getElementById("subComponentOSID");
var optn = document.createElement("OPTION");
optn.text="hhh"; //Added semi-colon
optn.value="val"; //Added semi-colon
x.add(optn); // Moved add to HTMLSelectElement

Related

Option:selected in javascript

I am able to do the following in javascript:
document.querySelector('select[name="plan_type"] option')
However, how would I get the selected option? For example:
document.querySelector('select[name="plan_type"] option:selected')
(the equivalent in jquery would be: $('select[name="plan_type"] option:selected').
We can obtain a reference to this type of element using its name:
oSelectOne = oForm.elements["select_one_element_name"];
To get the index of the selected option in the JavaScript options array of the select element, we can use the selectedIndex property of the select element object
var e =document.querySelector('select[name="plan_type"]');
var strUser = e.options[e.selectedIndex];
We can now use this index to determine the value of the selected option:
var strUser_value = e.options[index].value;
If we needed to get the text corresponding to the selected option, we would need to use the text property of the option element, instead of the value property:
var strUser_text = e.options[index].text;
QuerySelector is meant to use css selectors on the DOM, similar to jQuery, but they don't support the pseudo selectors, read on MDN
What you can do is to take a two step approach, get the element and then get the value from that element.
Like this:
var myElement = document.querySelector('select[name="plan_type"]);
var myValue = myElement.querySelector('[selected]').value;
Other general way to do this without query selector (needs id for the element), (name would do too)
var e = document.getElementById("{id_goes_here}");
var selectedValue = e.options[e.selectedIndex].value;
The options collection returns a collection of all elements in a drop-down list. Using the property selectedIndex to get the selected option.
let options = document.querySelector('select').options;
let text = options[options.selectedIndex].text;

Get selected checkbox(dynamically created) value in javascript

I'm using the following code snippet for create a dynamic checkbox.
This code snippet is inside of the for loop.based on the for loop the check boxes will create.The main function is called in the html onload.
This functionality is working fine.But if I choose the check box I need to get the value of the check box.I use the addEventListener its not working fine.
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = teamIds;
checkbox.id = i;
checkbox.addEventListener("click",setTeamIdsinTextBox(teamNamesToShow),false);
body.appendChild(checkbox);
Now I need, if I select the two checkboxes and I want to pass the both values to the setTeamIdsinTextBox function with comma separate string.
How can I do this? I need to achieve this with the javascript alone.
so I need to frame the selected checkbox values like
var teamNamesToShow ="firstselectedcheckboxvalue,secondselectedcheckboxvalue"
Thanks in Advance.
The click listener needs to iterate over the checkboxes and collect the ids of those that are checked. You can use a selector to get just the checked ones, or filter the checked ones later which allows for a less complex selector.
The following uses the more complex selector but simpler map callback:
window.onload = function(){
var form = document.forms['form0'];
for (var i=0; i<10; i++) {
var checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.name = 'name' + i;
checkbox.value = 'value' + i;
checkbox.id = 'cb' + i;
checkbox.addEventListener("click",
setTeamIdsinTextBox,
false);
form.appendChild(checkbox); // add checkboxes to form, not body
}
}
function setTeamIdsinTextBox() {
var form = this.form;
var cbs = Array.from(form.querySelectorAll('input[type="checkbox"]:checked'));
var ids = cbs.map(function(cb) {return cb.id});
form.ta0.value = ids.join(', ');
}
<form id="form0">
<textarea id="ta0" name="ta0"></textarea>
</form>
The body of the function could be:
this.form.ta0.value = Array.from(this.form.querySelectorAll('input[type="checkbox"]:checked')).map(function(cb) {return cb.id}).join(', ');
but I think splitting it over a couple of lines is more sensible.
Edit
Array.from was introduced in ECMAScript 2015 so may not be available in all implementations in use. There's a polyfill at MDN that can be included to provide support where lacking. Also, it can be replaced with Array.prototype.slice, which has ubiquitous support.
Instead of:
Array.from(form.querySelectorAll('input[type="checkbox"]:checked'));
use:
[].slice.call(form.querySelectorAll('input[type="checkbox"]:checked'));
however that may fail in IE 8 as (from memory) it doesn't allow calling built–in methods with a host object as this. In that case, go directly to map and provide a polyfill for IE 8:
[].map.call(form.querySelectorAll('input[type="checkbox"]:checked'), function(cb) {return cb.id});
That will work in IE 8 as the polyfill for map means that it's a native function, not built–in so using a NodeList as this is OK. Versions of IE with map are OK with the host object thing.
In the for loop which you are iterating maintain an int variable which gives you the exact no. of checkboxes which you are going to create.And then using that again iterate through a for loop for that int variable and check for each checkbox whether it is checked or not.
int countCheckBox=0;
var listOfCheckBoxVal='';
function setTeamIdsinTextBox(){
for(int i =1; i<=countCheckBox;i++){
if(document.getElementById(i).checked==true){
listOfCheckBoxVal += document.getElementById(i).value+",";
}
}
Now this listOfCheckBoxVal variable will have the list of values of checked checkboxes seperated by a comma.

Value of selected list

I have a select list with dynamic content such
Honorar, 120.00
Porti, 7.50
Spesen, 12.00
This values are stored x_ko_leistungsart. I am selecting only one option (no multi selection) and would like to have the values after comma such 120.00 for Honorar and 7.50 if the the option porti is selected.
I am using the following function to get these values. unfortunately it does not work. I get only the value 10 assiged...
Could you please have a look to the code where the mistake can be?
Regards
thanks
mpol_ch
function SelectAnsatz() {
document.fkostenedit.x_ko_ansatz.value = '10';
var Ansatz=0;
var splitted;
var elements = document.getElementsByName("x_ko_leistungsart[]");
splitted = elements.nextSibling.nodeValue.split(",");
Ansatz = parseFloat(splitted[1]);
document.fkostenedit.x_ko_ansatz.value = Ansatz.toFixed(2);
}
Take a look at document.getElementsByName("x_ko_leistungsart[]");
I'll give you a hint: The "value" you're getting from that is not what you're expecting. You can reduce at least two lines of code by expanding on the getElementByName function.
You can find more information here: http://www.w3schools.com/dom/dom_nodes_get.asp
I solves my problem with an onchange even on x_ko_leistungsart. Here is the function:
Thanks
mpol_ch
function SelectAnsatz(){
var x=document.getElementById("x_ko_leistungsart");Ansatz=x.options[x.selectedIndex].text.split(",");
document.fkostenedit.x_ko_ansatz.value = Ansatz[1];
}

Javascript reference element created from appendchild?

I am creating tables with the appendchild method. They contain checkboxes. I would like to be able to have the user to click a checkbox and have it run a function. I need the function to access the other checkbox and see if its checked or not. Currently I can' seem to reference the table or checkboxes at all.
My code for creating the table is:
function makeTable() {
var ItemA = Item.ItemName.options[Item.ItemName.options.selectedIndex].text;
var myParagraph=document.getElementById("myLine");
myForm = document.createElement("FORM");
mytable = document.createElement("TABLE");
mytablebody = document.createElement("TBODY");
var CB_Format = document.createElement('input');
CB_Format.type = 'checkbox';
CB_Format.name= "CB_Test";
CB_Format.value= 1;
CB_Format.setAttribute("name", "CBTest2");
CB_Format.onclick = changeColor;
theCell.appendChild(CB_Format);
var CB_Delete = document.createElement('input');
CB_Delete.type = "checkbox";
CB_Delete.name = "CB_Test";
CB_Delete.setAttribute("name", "CBTest2");
CB_Delete.value = 2;
CB_Delete.onclick = answer;
theCell.appendChild(CB_Delete);
My understanding is that my solution should be as simple as alert(document.form.checkbox.checked) but no matter what combination of possible names I try I get the error that it is null or not an object in both ie8 and firefox.
Thank you for your help
> function makeTable() {
> var ItemA = Item.ItemName.options[Item.ItemName.options.selectedIndex].text;
> var myParagraph=document.getElementById("myLine");
> myForm = document.createElement("FORM");
> mytable = document.createElement("TABLE");
> mytablebody = document.createElement("TBODY");
If you don't declare variables with var, they become global variables when first evaluated. Always declare variables.
> var CB_Format = document.createElement('input');
> CB_Format.type = 'checkbox';
> CB_Format.name= "CB_Test";
> CB_Format.value= 1;
> CB_Format.setAttribute("name", "CBTest2");
The above line changes the name property from the value assigned a couple of lines earlier, why do both? Just assign the correct value to the name property once:
CB_Format.name = "CBTest2";
The same goes for the use of setAttribute later. Note that setting the value of a property doesn't always change the associated attribute in some browsers, so always use properties unless there is a specific reason to use setAttribute,
[...]
My understanding is that my solution should be as simple as
alert(document.form.checkbox.checked) but no matter what combination
of possible names I try I get the error that it is null or not an
object in both ie8 and firefox. Thank you for your help
Form controls are made available as named properties of the form element. If there is more than one control with the same name, they are in a collecion. Assigning different values to the name property and attribute is asking for trouble. It should be that the second assignment overwrites the first, but no doubt there is a browser somewhere that will keep both values (one for the attribute and the other for the property).
The simple solution is to always use properties and only assign one value. If you want the name to be CBTest2 (since that is the second one assigned), then when the input is added to the form and the form to the document it will be available as:
document.forms['formName'].elements['CBTest2']
If the names are valid identifiers, then shorthand dot notation can be used:
document.formName.CBTest2
Since you have two elements with that name, the returned value will be a collection (a little like an array), so to get the first one, use:
document.formName.CBTest2[0]
You could use some code similar to...
var checkboxes = document.querySelectorAll('#some-form input[type="checkbox"]');
Array.forEach(checkboxes, function(checkbox) {
checkbox.addEventListener(function() {
var hasOtherCheckedCheckbox = Array.every(checkboxes, function(checkbox) {
return checkbox.checked;
});
});
});
Of course, for complete browser support, you'll need to modify this code a bit.

JavaScript: add extra attribute after new Option()

I have a piece of code that dynamically adds options to a select field depending on some other criteria. It looks somewhat like this:
if (chosen == "a_value") {
selbox.options[selbox.options.length] = new Option('text_1','value_1');
selbox.options[selbox.options.length] = new Option('text_2','value_2');
selbox.options[selbox.options.length] = new Option('text_3','value_3');
}
What I need is to add an extra attribute to that new option that contains a specific value. In this case the attribute will be called "discount" and the value will be an integer. Later on I'll read the attribute values and process them based on the value in the Option field.
So an option will look like this, once the script is ready;
<option value="value_1" discount="integer">text_1</option>
Makes sense?
Now how can I do this without the use of JS frameworks. It's just this small part of code that I need, so a framework would be overkill for this project.
Cheers! :-)
you can do something like
var o1 = new Option("key","value");
selbox.options[selbox.options.length] = o1;
o1.setAttribute("key","value");
I know this is old but I came across this question when I forgot it's add and not push today.
The correct way is to use select.options.add.
var opt = document.createElement('option');
opt.value = 'hello';
opt.text = 'world';
opt.setAttribute('data-discount', 'integer');
selbox.options.add(opt);
You can combine this into one line of code:
(selbox.options[selbox.options.length] = new Option("key","value")).setAttribute("key","value");
Note that this will only work if you have just one attribute to add, otherwise you will need a temporary variable.

Categories

Resources