changing the value of a select box by only having the xpath - javascript

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;

Related

Adding "values" to a texfield in jquery/js

When writing a new email, I've got a modal(pop-up window in boostrap) that shows a list of contacts. When I select (through checkboxes) a couple of contacts, the selected ones are written into a checkbox. Problem is I'm just writing the lastone I select instead of all of the selected ones.
If you need further explanation please ask. (Sorry for my english)
$("#tblContacto").on("click", ".ck", function(event){
if($(".ck").is(':checked')) {
selected_index = parseInt($(this).attr("alt").replace("Check", ""));
var contacto = JSON.parse(tbContactos[selected_index]);
$("#txtDestinatarios").val(contacto.Email);
} else {
$("#txtDestinatarios").val("");
}
});
Assuming that you want to add all E-Mails into a textfield with id txtDestinatariosthe cause of your Problem is the usage of the $("#txtDestinatarios").val(); function.
Calling val() with an argument sets (and thus overwrites) the value within the textfield. (See demo at http://api.jquery.com/val/#val2)
You would have to first retrieve the value of the textfield using code like var currentValue = $("#txtDestinatarios").val() and then add/remove the E-Mail from/to the string before setting the resulting string back as the value.
If you want to set all selected items in the checkboxes into Textfiled you can use the following line of code :-
$("#txtDestinatarios").val( $("#txtDestinatarios").val()+ ","+contacto.Email);

How can I update the background color of a dynamic input control?

I'm successfully creating some dynamic input textboxes using the following javascript:
var type = "Textbox";
var foo = document.getElementById("fooBar");
for (i = 1; i <= totalQty; i = i + 1) {
var textbox = document.createElement("input");
//Assign different attributes to the element.
textbox.setAttribute("type", type + i);
//textbox.setAttribute("value", type + i);
textbox.setAttribute("name", type + i);
textbox.setAttribute("id", type + i);
textbox.setAttribute("style", "width:300px");
textbox.setAttribute("width", "300px");
//Append the element in page (in span).
var newline = document.createElement("br");
foo.appendChild(newline);
foo.appendChild(textbox);
}
Everything works fine with that. Once the user keys in data and clicks submit however, I need to go back and set the background-color of any textboxes with an error to red. I found some code to do the actual coloring:
textbox.style.backgroundColor = "#fa6767";
...and I know the exact name of the textbox with the error (i.e. "Textbox1", "Textbox2", "Textbox3", etc) but I'm not sure how to programatically assign this background color code to the specific textbox. I can't use something like this, since all code is dynamically generated:
errorTextbox = $("#Textbox1");
Any suggestions?
It looks like you're building a form validation script. Here's an easier way to do this:
1) Create an entry in your stlyesheet for your error class. Adding and removing a class requires fewer steps than assigning properties individually.
.error {
background-color: #ff0000;
}
2) Give all the textboxes you wish to validate a unique class name "valMe", for example.
3) Then loop through them during the validation step:
$('.valMe').each(function() {
$(this).removeClass('error');
if($(this).text=='') {
$(this).addClass('error');
}
})
By using "this" you refer to the current element, so you don't even need to know the ID of the element.
If you already know the name (in this case identical to the id) of the element, you can use jQuery to select the element by forming the selector using string concatenation. Assuming you have a variable that stores the name/id of the text box that has the error, then it's a relatively simple process:
var errorTextboxName = 'Textbox1';
$('#' + errorTextboxName).css('background-color', 'red');
I ended up going with the following:
document.getElementById('Textbox1'.style.backgroundColor = "#fa6767";
I originally didn't think I would be able to capture my "Textbox1" control in this fashion since when I viewed the html source code, there was no "Textbox1" due to the fact I dynamically created it.
Thanks.

Getting value from search box in javascript

How do I get a value from search box in javascript?
I'd like to redirect users to particular pages based on what they select in the search box.
For example, if the user selected "New York" and then clicked on Yes, he'll be redirected to page /about/New York
This work for static pages, but for some reasons I can't get the value from the search box.
In Ruby I woud get it with params[:query_name]
I am using hidden_value and tag 'search'
var val = getElementsByTagName('search').value;
if (r) {
location.href = "/about/" + val";
}
You may also need to specify this == document and use double quotes in case 'search' is a reference to an object, to make sure it is properly interpolated
var val = document.getElementById("search").value;
or with jQuery:
var val = $("#search").val();
Did you mean (since I dont think there is an html tag named search):
var val = getElementById('search').value;
if (r) {
window.location.href = "/about/" + val;
}
So above code assumes your element has id set like id="search"
By the way, to select an specific element using getElementsByTagName, you also need to specify index since it returns Node list:
getElementsByTagName('tagName')[indexHERE].value
getElementsByTagName returns an array of many objects based on the tag name, e.g. input,div,a etc. If this is what your search bar looks like:
<input id="search" />
Then do:
getElementById('search').value;

How to get the value of the selected check-box value in XUl JavaScript

This is my check-box and it's created dynamically by getting the value of the XUL tree.
var yyahoo = tree.view.getCellText(i, tree.columns.getNamedColumn("yahoo"));
var existing = document.getElementById('box');
var checkbox = document.createElement('checkbox');
capt.appendChild(checkbox);
checkbox.setAttribute('label', yyahoo);
checkbox.setAttribute("checked", "false")
checkbox.setAttribute('style', 'color: green;');
Like this I have dynamically created many check-boxes in my XUL file.
When I checked Mozilla website, it is explained that, i have to use hasAttribute() to get the value of the selected check-box, which is confusing to me.
Please help me to get the value of the selected check-box.
This is the button to get the values on-click.
<row><button label="get" oncommand="get();"/></row>
This is function: This function is not working 'cause something is missing in my function.
function get()
{
// check that the attribute exists before setting a value
var d = document.getElementById("box");
if (d.hasAttribute("checkbox")) {
alert(d);
}
}
Thanks for your support.
The checkbox is a child of the element with ID box, not an attribute. Try something like this:
function get() {
// check that the attribute exists before setting a value
var table = document.getElementById("box");
var cells = table.getElementsByTagName("checkbox");
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if(cell.checked) {
alert(cell.getAttribute("label"));
// or cell.label
}
}
}
The checked property tells you whether the checkbox is currently selected or not. hasAttribute('checked') tells you whether the attribute was set or not. Maybe you have to use both, I don't know.
Apparently, the checkbox [MDN] element has no attribute value, so I don't know which value you are talking about.

How do we change the name of a html select element using javascript and only the tags' name to reference to?

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.

Categories

Resources