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;
Related
I am currently using robotium to record a load of actions in an android web view. There is a known bug in robotium that doesnt let you change the value of a select box. in order to combat this when the test is running i am creating another javascript injection to change it. It works with name and Id but it needs to be able to use xpath as well in case a name or id arent available.
At the moment I can do this using the name and Id of the select box using:
selectBox = document.getElementById(identifyingValue);
or
selectBox = document.getElementByName(identifyingValue);
After this I can create a method to change the value of the select box the value that I want. The issue is that sometimes i cannot get the id or name of the select box and there isn't a similar method to do this via an Xpath ie:
selectBox = document.getElementByXpath(identifyingValue);
My code currently looks like this:
var selectBox;
var identifyingAttribute = ('$identifyingAttribute');
var identifyingValue = ('$identifyingValue');
var selectedIndex = '$selectedIndex';
if (identifyingAttribute === 'id') {
selectBox = document.getElementById(identifyingValue);
} else if (identifyingAttribute === 'name') {
selectBox = document.getElementByName(identifyingValue);
} else if (identifyingAttribute === 'xpath') {
selectBox = document.getElementByXpath(identifyingValue);
}
selectBox.selectedIndex = selectedIndex;
if (selectBox.onchange) {
selectBox.onchange();
}
So far you can see that I am trying to use the id and name first and the xpath as a last resort.
Is they a away that I can select an element by its Xpath and then change its value or perform a similar action. Any help or input would be greatly appreciated.
you can use document.querySelector() and select the property with a css selector.
documentation can be found here: https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
I have found a solution to the problem using document.evaluate()
The statement works for me:
selectBox = document.evaluate(identifyingValue, document, null , 9, null).singleNodeValue;
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
I am populating country dropdownlist from a database. I need to select a value from dropdown list and assign it to textbox by using Javascript.
Code:
var textboxId = document.getElementById("txtCountry");
var dropdownListId =document.getElementById("ddlLocation");
var e = document.getElementById("ddlLocation");
var strUser = e.options[e.selectedIndex].value;
document.getElementById(textboxId).value = strUser;
document.getElementById(textboxId).focus();
by doing this I am getting error. Any solutions?
Your code is wrong, Look at where I've made the changes to the same code:
var textboxId = document.getElementById("txtCountry");
var e = document.getElementById("ddlLocation");
var strUser = e.options[e.selectedIndex].value;
textboxId.value = strUser;
textboxId.focus();
What you did, is you selected your textbox and JS returned you a DOM element of that text box and you wanted to populate it by passing the DOM of the textBox inside the getElementById() function.
Here is where it broke:
document.getElementById(textboxId).value = strUser;
To use getElementById() method, you pass a string value of the id of an element.
Hope this helps.
Try with:
document.getElementById('<%=txtCountry.ClientID%>').value
or
var textBox = document.getElementById('<%=txtCountry.ClientID%>');
textBox.value = strUser;
That's because the ids of the html elements in the generated documents doesn't match with the id that you have assigned in your code. To get the id assigned to your control in the html, you can use the ClientID property of your dropdown.
Another problem is that you assign yourhtml element to variable and then use getElementById function which is not valid call.
This is changed in ASP.NET 4, that is about to be released.
Hope that helps!
These two lines:
document.getElementById(textboxId).value = strUser;
document.getElementById(textboxId).focus();
are wrong too. If your previous line actually worked:
var textboxId = document.getElementById("txtCountry");
then what you have called textboxId will actually be the textbox control, so you will be doing a getElementById using the control instead of a string identifier.
To follow upon what #anthares said; try this:
var textboxId = '<%=txtCountry.ClientID%>';
alert('My textbox id is: ' + textboxId);
and make sure that you are getting the correct ID for the textbox (remember that it will be munged by ASP.Net, at least make sure you are not getting nothing). Then when you do a document.getElementById you need to check the result before using:
var myTextBox = document.getElementById(textboxId);
if (myTextBox !== null) {
...now i can access the properties...
}
If you don't want to use
document.getElementById()
try it:
var VarName = $('#<%=YouDropDownId.ClientId %>').val();
How can I get the id of the selected node in a jsTree?
function createNewNode() {
alert('test');
var tree = $.tree.reference("#basic_html");
selectedNodeId = xxxxxxxxx; //insert instruction to get id here
tree.create({ data : "New Node Name" }, selectedNodeId);
}
Unable to get harpo's solution to work, and unwilling to use Olivier's solution as it uses internal jsTree functions, I came up with a different approach.
$('#tree').jstree('get_selected').attr('id')
It's that simple. The get_selected function returns an array of selected list items. If you do .attr on that array, jQuery will look at the first item in the list. If you need IDs of multiple selections, then treat it as an array instead.
Nodes in jsTree are essentially wrapped list items. This will get you a reference to the first one.
var n = $.tree.focused().get_node('li:eq(0)')
You can replace $.tree.focused() if you have a reference to the tree.
To get the id, take the first matched element
if (n.length)
id = n[0].id
or you can use the jQuery attr function, which works on the first element in the set
id = n.attr('id');
In jstree version 3.1.1, you can get it directly from get_selected:
$("#<your tree container's id>").jstree("get_selected")
In the most recent version of jsTree (checked at 3.3.3), you can do this to get an array of IDs:
var ids = $('#tree').jstree('get_selected');
This will return, for example, ["selected_id1", "selected_id2", "selected_id3"]. If you want to get the selected nodes (not IDs), you can do this:
var nodes = $('#tree').jstree('get_selected', true);
The current docs contain more information.
$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});
I was having problems getting the selected ids from a tree with MULTIPLE selections. This is the way I got them:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});
In my case, the data call doesnt work.
I succeed in accessing my node data by using attr function.
$("#tree").jstree("get_selected").attr("my-data-name");
to get all selected ids use the below code
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
now you have all the selected id's in the "selectedData" variable
<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>
Just use
var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;
where #FaqTreeView is the id of your div that contains the jstree.
In some cases and/or jstree versions this solution doesn't work.
$('#tree').jstree('get_selected').attr('id');
Instead of defined "id" I get nothing.
What did the trick for me is:
$("#tree").jstree("get_selected").toString();
These are all old answers for old versions. As of version 3.3.3 this will work to get all attributes of the selected node.
$('#jstree').jstree().get_selected(true)[0]
If you then want the id then add .id at the end. You can look at all the other attributes in web developer tools if you copy the above code.
You can use the following code
var nodes = $("#jstree_demo_div").jstree(true).get_selected("full", true);//List of selected node
nodes[0].id//Which will give id of 1st object from array
With the latest version of jsTree, you can do it as follows:
var checked_ids = [];
$('#your-tree-id').jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));
HI! I have a problem with changing the name of a select element. I have about 28 select elements generated on the page. Each of these select elements has been given the name "dropdown". I use this name to calculate the total based on the option selected.
But when i pass this information to a php page, it shows only the last select element. To overcome this i need to have all the select tags labelled as "dropdown[]" onsubmit. This is because i need "dropdown" for javascript to read it and i need "dropdown[]" for php to process it.
<select name="dropdown">
<option>
<option>
<option>
</select>
should be changed to :
<select name="dropdown[]">
<option>
<option>
<option>
</select>
while validating the form in the end. How do i go about it? I dont use ids along with the name, because I think it might make it complex.
I would recommend you to stay with the 'dropdown[]' name, then you can use the getElementsByName function, which will return you an array that you can iterate, of elements with the given name in the document:
var dropdownArray = document.getElementsByName('dropdown[]'),
i, element, n = dropdownArray.length;
for (i = 0; i < n; i++) {
element = dropdownArray[i];
// you can check the value of each element here...
}
Edit: Modifying your code:
function addup(){
var tot = 0, i, // i declaration was missing
dropdowns = document.payment.elements['dropdown[]'];
for(i = 0;i<dropdowns.length;i++) {
//alert(i);
var find = dropdowns[i];
var check = find.options[find.selectedIndex].value;
//alert(check);
if(check.substring(0,3)=='pay') {
// not using eval anymore
var tot1 = document.payment.elements[check.substring(4)+'_amount'].value;
//alert(tot1);
tot += +tot1; // unary plus operator to convert to number
}
document.payment.total_amount.value=tot;
calcTotal();
}
}
I think you're approaching this problem wrong. You should probably use "id" to uniquely identify elements. Then you can use one of the many libraries available for free (jQuery, dojo query, ....) to provide you a nicer way to select elements from the page. Either by giving your specific "<select>" elements class names, or just by finding all the "select" elements on the page.
I'm completely in the dark as to why "[]" at the end of the name would make a difference for you. But I'm not familiar with php.
Using this box because i could display the code.
If i named the element as "dropdown[]" I would be getting an error like in this case:-
function addup(){
var tot=0;
for(i=0;i<(document.payment.dropdown.length);i++)
{
//alert(i);
var find=document.payment.dropdown[][i];
var check=find.options[find.selectedIndex].value;
//alert(check);
if(check.substring(0,3)=='pay')
{
var other="document.payment."+check.substring(4)+"_amount.value";
var tot1=eval(other);
//alert(tot1);
tot+=parseInt(tot1);
}
document.payment.total_amount.value=tot;
calcTotal();
}
}
Pardon the shabby code, but this doesnt seem to work if i name it as "dropdown[]". So i need the name to be "dropdown" in the beginning and then it should change to "dropdown[]" onsubmit.
I've just found your question.
Why to just add a id (example 'itsID') tag to your select and then point it to change its name with:
var ref = document.getElementById('itsID');
ref.name = "dropdown[]";
It works for me with ref.