How to select an option with CasperJS - javascript

I try to set select option attribute to selected. But I try to avoid using nth-child in CasperJS because there are bugs in PhantomJS's nth-child.
So I try to use this as the subtitution of jQuery(css_path).
function setSelectedCountry(i){
window.__utils__.echo("i :"+i);
var query = "//*[#id='cboCountry']/optgroup[2]/option["+i+"]";
__utils__.getElementByXPath(query).setAttribute("selected","selected");
}
But, when I evaluate that code by this way
this.evaluate(setSelectedCountry, 5);
The select option is not changed.
Moreover, when I try to trigger onblur() using
document.getElementById("cboCountry").onblur();
inside setSelectedCountry() funtion, there were nothing happened.
Why this happened?
Also, when I try to call the function with XPath expression, and the other one is using CSS selector, I got undefined error returned from CasperJS.
I use this function :
function getCityName(i){
var query = "//*[#id='cboCity']/option["+i+"]";
return __utils__.getElementByXPath(query).innerText;
}
then I got the other one:
function setSelectedCountry(i){
var query = "#cboCountry > optgroup:nth-child(3) > option:nth-child("+i+")";
jQuery(query).attr("selected", "selected").blur();
}
When I try to run both of them, then this is what I've got
PAGE.ERROR: TypeError: 'undefined' is not an object (evaluating
'__utils__.getElementByXPath(query).innerText')
Can you give me suggestions?
[EDITED]
Here is my markup :
This one for cboCountry select option :
<select name="cboCountry" id="cboCountry" onkeypress="return selectItem();" onkeyup="event.cancelbubble=true;return false;" onkeydown="return handleKey();" onfocus="activeList=this;this.enteredText='';" onchange="//hs.DropCity();" onblur="hs.DropCity();"
class="txtBox">
<option value="">-- --Select-- --</option>
<optgroup label="Popular Destinations">
<option value="MA05110065">Indonesia</option>
<option value="MA05110067">Malaysia</option>
<option value="MA05110069">Singapore</option>
<option value="MA05110001">Thailand</option>
</optgroup>
<optgroup label="Other Destinations">
<option value="MA05110083">Afghanistan</option>
<option value="MA05110124">Albania</option>
<option value="MA05110133">Algeria</option>
<option value="MA05110186">American Samoa</option>
<option value="MA05110103">Andorra</option>
<option value="MA05110014">Angola</option>
<option value="MA05110135">Anguilla (UK)</option>
<option value="MA05110136">Antigua and Barbuda</option>
<option value="MA05110171">Argentina</option>
<option value="MA05110206">Armenia</option>
<option value="MA05110183">Venezuela</option>
<option value="MA05110070">Vietnam</option>
<option value="MA05110013">Western Sahara</option>
<option value="MA05110082">Yemen</option>
<option value="MA05110027">Zambia</option>
<option value="MA05110028">Zimbabwe</option>
</optgroup>
</select>
And this one for cboCity select option :
<select name="cboCity" id="cboCity" onkeypress="return selectItem();" onkeyup="event.cancelbubble=true;return false;" onkeydown="return handleKey();" onfocus="activeList=this;this.enteredText='';" onchange="//hs.DropLocation();" onblur="hs.DropLocation();"
class="txtBox">
<option value="">-- --Select-- --</option>
<option value="">-- Select --</option>
<option value="MA02022810">Ambarawa</option>
<option value="MA09090008">Ambon</option>
<option value="MA08090042">Anyer</option>
<option value="MA02022861">Wonosobo</option>
<option value="MA06060051">Yogyakarta</option>
</select>

The problem is the distinction between property and attribute. Browsers usually don't re-evaluate attributes when you change them in the DOM. In those cases, you would need to change the property behind that attribute on the DOM element.
In this case, you need to change the selected index. The select element has the selectedIndex property that you can change to the intended option which you can get through option.index:
function setSelectedCountry(i){
__utils__.echo("i :"+i);
var opt = "//*[#id='cboCountry']/optgroup[2]/option["+i+"]";
var select = document.getElementById('cboCountry');
select.selectedIndex = __utils__.getElementByXPath(opt).index;
select.onblur(); // or `onchange()`
}
See this answer for more information on the option index.
"//*[#id='cboCity']/option["+i+"]" cannot work, because this expression will match options that are direct children of a #cboCity element, but you have an optgroup inbetween. Either use "//*[#id='cboCity']//option["+i+"]" or "//*[#id='cboCity']/optgroup/option["+i+"]".

Related

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

Change "value" of combobox option JS

So, as the title says I want to change the value of a certain option using JS. I have already looked for it but every answer refers to changing the selected option not the value of a specifical option.
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
I want to change "Ver" option value from 0 to 1. I don´t know if it is possible but thanks in advance.
Have you tried assigning it an id and then changing it in your js file?
Something like this:
<option value='0' id='opt1' selected>Ver</option>
and in javascript:
document.getElementById("opt1").value = "1";
You can select the option with value 0 using
let opt = document.querySelector('select.form-control option[value="0"]')
You can then change the value by reassigning it
opt.setAttribute('value', '1')
If you have more than one select with class form-control this could be a problem, and you might want to give it/them a unique id — then the selector would be
let opt = document.querySelector('select#your-id option[value="0"]')
Here is a stack snippet doing this, where I've combined the select and the assignment into a single statement. I've also added a change event listener to show the value in the console, so if you switch to 20 then switch to Ver again it would print 20 and then 1 to the console, showing you that the value is indeed 1, not 0
document.querySelector('select.form-control')
.addEventListener('change', function(e) {
console.log(this.value);
});
document.querySelector('select.form-control option[value="0"]')
.setAttribute('value', '1');
select {
min-width: 10em;
}
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
Hello you can assign the value with the following instruction
$("#SelectID").val("value option");
document.getElementById("SelectID").value = "value option";
reference in this url Set value of combobox or select

set a html option selected in a dropdown containing optgroup tag using javascript

I'm working With Html(JSP) and Javascript. I have a dropdown box with id "examcenter" containing many optgroup as shown in the following code. in the function loadDrivingSchool() in javascript, I would like to set selected the value of the selected element. the loadDrivingSchool() function calls a controller in a server and when I return the view, the dropdown list does not have a selected value. I want to set this selected value to the value that the user choose before the reloading of the page. I have try the following Javascript code but it is not working:
document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;
<select id="examcenter" onchange="loadDrivingSchool();">
<optgroup label="ADAMAOUA">
<option value="1">TIBATI</option>
<option value="2">TIGNERE</option>
<option value="3">MEIGANGA</option>
<option value="4">BANYO</option>
<option value="5">NGAOUNDERE</option>
</optgroup>
<optgroup label="CENTRE">
<option value="6">YAOUNDE</option>
<option value="7">ESEKA</option>
<option value="8">AKONOLINGA</option>
<option value="9">NANGA EBOKO</option>
<option value="10">MONATELE</option>
<option value="11">MBALMAYO</option>
<option value="12">MFOU</option>
<option value="13">NGOUMOU</option>
<option value="14">BAFIA</option>
<option value="15">NTUI</option>
</optgroup>
<optgroup label="EXTREME NORD">
<option value="20">MAROUA</option>
<option value="21">KAELE</option>
<option value="22">KOUSSERI</option>
<option value="23">MORA</option>
<option value="24">YAGOUA</option>
<option value="25">MOKOLO</option>
</optgroup>
<optgroup label="EST">
<option value="16">YOKADOUMA</option>
<option value="17">ABONG-MBANG</option>
<option value="18">BATOURI</option>
<option value="19">BERTOUA</option>
<option value="62">NGUELEMENDOUKA</option>
</optgroup>
</select>
What I think you are trying to do is keep a track of what the user has selected, without submitting that selected option. That can only be achieved if you keep a record of that in some way, possibly using the session attribute.
You can probably store the value of the selected options in a session and then get it's value using AJAX.
But if I am wrong and you are trying to just simply get the value of the selected option without leaving that page, then you can try this to display the value of the selected option in your dropdown:
alert( document.getElementById("examcenter").value );
Also, I see a problem in your code. You are using
document.getElementById('examcenter').getElementsByTagName('option')[examCenter].selected = 'selected' ;
Instead, you should use:
document.getElementsByTagName('option').selected = true ;

Css jquery.each just one do

I'm a rookie when it comes to Javascript.
First thanks for all of your answers.
Please follow under codes.
I made like this.
This is crawler htmls one section.
<select data-js="career-select" data-group-id="stats">
<option value="0x02E00000FFFFFFFF" option-id="ALL HEROES">ALL HEROES</option>
<option value="0x02E0000000000002" option-id="Reaper">Reaper</option>
<option value="0x02E0000000000003" option-id="Tracer">Tracer</option>
<option value="0x02E0000000000004" option-id="Mercy">Mercy</option>
<option value="0x02E0000000000005" option-id="Hanzo">Hanzo</option>
<option value="0x02E0000000000006" option-id="Torbjörn">Torbjörn</option>
<option value="0x02E0000000000007" option-id="Reinhardt">Reinhardt</option>
<option value="0x02E0000000000008" option-id="Pharah">Pharah</option>
<option value="0x02E0000000000009" option-id="Winston">Winston</option>
<option value="0x02E000000000000A" option-id="Widowmaker">Widowmaker</option>
<option value="0x02E0000000000015" option-id="Bastion">Bastion</option>
<option value="0x02E0000000000016" option-id="Symmetra">Symmetra</option>
<option value="0x02E0000000000020" option-id="Zenyatta">Zenyatta</option>
<option value="0x02E0000000000029" option-id="Genji">Genji</option>
<option value="0x02E0000000000040" option-id="Roadhog">Roadhog</option>
<option value="0x02E0000000000042" option-id="McCree">McCree</option>
<option value="0x02E0000000000065" option-id="Junkrat">Junkrat</option>
<option value="0x02E0000000000068" option-id="Zarya">Zarya</option>
<option value="0x02E000000000006E" option-id="Soldier: 76">Soldier: 76</option>
<option value="0x02E0000000000079" option-id="Lúcio">Lúcio</option>
<option value="0x02E000000000007A" option-id="D.Va">D.Va</option>
<option value="0x02E00000000000DD" option-id="Mei">Mei</option>
<option value="0x02E000000000012E" option-id="Sombra">Sombra</option>
<option value="0x02E000000000013B" option-id="Ana">Ana</option>
</select>
This is server side jQuery part.
var quick_data = $(`#quickplay select[data-group-id="stats"]`);
quick_data.each(function() {
var test= $(this).find("option").attr('value');
console.log('test : ' + test);
})
I tried and got values(like '0x230000000fffffffffff') but if I use server side jQuery send like this
test : 0x02E00000FFFFFFFF
Just 1.. just one!!
Why this just works one?
Thank you for read my foolish code and English
Thank you and Regards
Why this just works one?
Because there's only one select, so your each callback is called only once, and it grabs the value of the first option within it (because that's how attr, val, prop, and such work when you use them as getters*).
If you want each value, you can loop through the options:
$(`#quickplay select[data-group-id="stats"] option`).each(function(){
console.log('test : ' + this.value);
});
Example:
$(`#quickplay select[data-group-id="stats"] option`).each(function() {
console.log('test : ' + this.value);
});
<div id="quickplay"><select data-js="career-select" data-group-id="stats">
<option value="0x02E00000FFFFFFFF" option-id="ALL HEROES">ALL HEROES</option>
<option value="0x02E0000000000002" option-id="Reaper">Reaper</option>
<option value="0x02E0000000000003" option-id="Tracer">Tracer</option>
<option value="0x02E0000000000004" option-id="Mercy">Mercy</option>
<option value="0x02E0000000000005" option-id="Hanzo">Hanzo</option>
<option value="0x02E0000000000006" option-id="Torbjörn">Torbjörn</option>
<option value="0x02E0000000000007" option-id="Reinhardt">Reinhardt</option>
<option value="0x02E0000000000008" option-id="Pharah">Pharah</option>
<option value="0x02E0000000000009" option-id="Winston">Winston</option>
<option value="0x02E000000000000A" option-id="Widowmaker">Widowmaker</option>
<option value="0x02E0000000000015" option-id="Bastion">Bastion</option>
<option value="0x02E0000000000016" option-id="Symmetra">Symmetra</option>
<option value="0x02E0000000000020" option-id="Zenyatta">Zenyatta</option>
<option value="0x02E0000000000029" option-id="Genji">Genji</option>
<option value="0x02E0000000000040" option-id="Roadhog">Roadhog</option>
<option value="0x02E0000000000042" option-id="McCree">McCree</option>
<option value="0x02E0000000000065" option-id="Junkrat">Junkrat</option>
<option value="0x02E0000000000068" option-id="Zarya">Zarya</option>
<option value="0x02E000000000006E" option-id="Soldier: 76">Soldier: 76</option>
<option value="0x02E0000000000079" option-id="Lúcio">Lúcio</option>
<option value="0x02E000000000007A" option-id="D.Va">D.Va</option>
<option value="0x02E00000000000DD" option-id="Mei">Mei</option>
<option value="0x02E000000000012E" option-id="Sombra">Sombra</option>
<option value="0x02E000000000013B" option-id="Ana">Ana</option>
</select></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
* jQuery is set-based. In your original code, $(this).find("option") returned a set of option elements (all of them), but when you use a getter on the set, it only gets from the first element in the set. (In contrast, jQuery's setters update all elements in the set; the API is assymmetrical.) There's one exception to this: text, when used as a getter, gets the text of all of the elements in the set. (I have no idea why it's different from all the others.)
it looks like your jQuery foreach has the wrong selector. You're doing foreach on the select, not the options with in the select. Try this
var quick_data = $(`#quickplay select[data-group-id="stats"] > option`);
$(`#quickplay select[data-group-id='stats'] option`)
This will grab all options under id quickplay where select has the attribute data-group-id stats.
vs.
$(`#quickplay select[data-group-id='stats']`)
This will grab all selects under #quickplay (with the data-group-id being stats).
Then you add:
.each(function() {
console.log($(this).find("option").attr("value"));
});
And, now, we're iterating through all of our selects and printing the first
option. When you use functions like .attr() on multiple elements,
it will take the value from only the first one. It does not return an array.
$(`#quickplay select[data-group-id='stats'] option`).each(function(){
var test= $(this).attr('value');
console.log('test : ' + test);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="quickplay">
<select data-js="career-select" data-group-id="stats">
<option value="0x02E00000FFFFFFFF" option-id="ALL HEROES">ALL HEROES</option>
<option value="0x02E0000000000002" option-id="Reaper">Reaper</option>
<option value="0x02E0000000000003" option-id="Tracer">Tracer</option>
<option value="0x02E0000000000004" option-id="Mercy">Mercy</option>
<option value="0x02E0000000000005" option-id="Hanzo">Hanzo</option>
<option value="0x02E0000000000006" option-id="Torbjörn">Torbjörn</option>
<option value="0x02E0000000000007" option-id="Reinhardt">Reinhardt</option>
<option value="0x02E0000000000008" option-id="Pharah">Pharah</option>
<option value="0x02E0000000000009" option-id="Winston">Winston</option>
<option value="0x02E000000000000A" option-id="Widowmaker">Widowmaker</option>
<option value="0x02E0000000000015" option-id="Bastion">Bastion</option>
<option value="0x02E0000000000016" option-id="Symmetra">Symmetra</option>
<option value="0x02E0000000000020" option-id="Zenyatta">Zenyatta</option>
<option value="0x02E0000000000029" option-id="Genji">Genji</option>
<option value="0x02E0000000000040" option-id="Roadhog">Roadhog</option>
<option value="0x02E0000000000042" option-id="McCree">McCree</option>
<option value="0x02E0000000000065" option-id="Junkrat">Junkrat</option>
<option value="0x02E0000000000068" option-id="Zarya">Zarya</option>
<option value="0x02E000000000006E" option-id="Soldier: 76">Soldier: 76</option>
<option value="0x02E0000000000079" option-id="Lúcio">Lúcio</option>
<option value="0x02E000000000007A" option-id="D.Va">D.Va</option>
<option value="0x02E00000000000DD" option-id="Mei">Mei</option>
<option value="0x02E000000000012E" option-id="Sombra">Sombra</option>
<option value="0x02E000000000013B" option-id="Ana">Ana</option>
</select>
</div>

Using JQuery "select option:first-child" just for an element with a given id?

This code looks at if dropdownlist with 'townid' has an option of Central and then puts Central after the first option at all dropdownlists.
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('select option:first-child');
}
My problem is that:
How can I add it just after dropdownlist that has id of townid? I mean something like:
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('#townid select option:first-child');
}
For example:
<select id=townid>
<option value="5000">AL</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5204">Central</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
After that process they should be seem like:
<select id=townid>
<option value="5000">AL</option>
<option value="5204">Central</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
How can I add it just after dropdownlist that has id of townid?
Okay, I’m gonna assume your HTML looks something like this:
<select id="townid">
<option>
…
</option>
</select>
In that case, you could use:
$('#townid option:contains("Central")').appendTo('#townid option');
If there are multiple option elements inside #townid and you only want to select the first, just change the selector:
$('#townid option:contains("Central")').appendTo('#townid option:first');
In your example, don’t use if (central), use if (central.length) instead.
You just messed up the selector, because #townid IS the select tag.
var central = $('#townid option:contains("Central")');
if(central.length === 1){
central.insertAfter('#townid option:first-child');
}

Categories

Resources