Onchange - switching from prototype to jquery? - javascript

is there anyway of getting the onchange to work with jquery? Right now i'm using prototype.js. What the onchange does is when either US, CA or GB is selected it shows the state dropdown box for it. basically a show / hide
<SELECT id='country' onchange="HandleStateApearence(this.selectedIndex,
null, $('state_'), $('state_3'), $('state_2'),
null, 1, 2, false)" name=add[country]>
<OPTION value="" selected>-- Select Country --</OPTION>
<OPTION value=US>United States</OPTION>
<OPTION value=CA>Canada</OPTION>
<OPTION value=GB>United Kingdom</OPTION>
</SELECT>
<span id='state_' style="display:none; font-weight:bold;">State:</span>
<SELECT id=state_2 style="DISPLAY: none" name="c_state">
<OPTION value="" selected>-- Select Province --</OPTION>
<OPTION value=AB>Alberta</OPTION>
<OPTION value="BC">British Columbia</OPTION>
</SELECT>
<SELECT id=state_3 style="DISPLAY: none" name="u_state">
<OPTION value="" selected>-- Select State --</OPTION>
<OPTION value=AL>Alabama</OPTION>
<OPTION value=AK>Alaska</OPTION>
<OPTION value=AZ>Arizona</OPTION>
</SELECT>

You haven't shown the definition of HandleStateAppearence(), so I'm not sure what its parameters' expected types are, but in jQuery the $('someselectorhere') function returns a jQuery object that you can treat as if it is an array elements that matched the selector (potentially an empty array, though it won't be in your case). Also, to select an element by ID you use "#", e.g., $('#state_') - jQuery selectors (mostly) follow the syntax of CSS selectors.
So putting those two points together, if your function is expecting direct references to the select elements you need to say $('#state_')[0]:
<SELECT id='country' onchange="HandleStateApearence(this.selectedIndex, null,
$('#state_')[0], $('#state_3')[0], $('#state_2')[0], null, 1, 2, false)"
name=add[country]>
EDIT: Here's a complete jQuery-based method to handle the show/hide of applicable state select elements.
<script>
$(document).ready(function() {
$("#country").change(function() {
$(".state").hide();
var stateSelect = $("#state_" + $(this).val());
if (stateSelect.length === 0)
$("#state_label").hide();
else {
$("#state_label").show();
stateSelect.show();
}
});
});
</script>
<SELECT id='country' name=add[country]>
<OPTION value="" selected>-- Select Country --</OPTION>
<OPTION value=US>United States</OPTION>
<OPTION value=CA>Canada</OPTION>
<OPTION value=GB>United Kingdom</OPTION>
</SELECT>
<span id='state_label' style="display:none; font-weight:bold;">State:</span>
<SELECT id="state_CA" class="state" style="DISPLAY: none" name="c_state">
<OPTION value="" selected>-- Select Province --</OPTION>
<OPTION value=AB>Alberta</OPTION>
<OPTION value="BC">British Columbia</OPTION>
</SELECT>
<SELECT id="state_US" class="state" style="DISPLAY: none" name="u_state">
<OPTION value="" selected>-- Select State --</OPTION>
<OPTION value=AL>Alabama</OPTION>
<OPTION value=AK>Alaska</OPTION>
<OPTION value=AZ>Arizona</OPTION>
</SELECT>
I've removed the inline onchange handler and instead assigned the change handler via jQuery, done inside the document.ready handler so that we can be sure the country element has already been parsed. This is the standard way to assign event handlers.
In your html, I've given each state select element a class of "state" so that we can easily select them all at once to hide them with a single statement.
I've also changed the ID attribute of the select elements to be "state_{countrycode}", e.g., "state_CA", where the codes match exactly with the corresponding values in the country option elements. That way we can reference them in JavaScript by concatenating the currently selected country code to the end of "state_" and if you later add more countries to the list with their own corresponding state drop-down you won't need to change the JavaScript at all. The most important line of code is probably this one:
var stateSelect = $("#state_" + $(this).val());
Which declares a variable stateSelect that will be assigned to a jQuery object containing all elements that match a selector that is an element ID of "state_{currentcountrycode}". Depending on which country option is selected that stateSelect jQuery object will contain exactly 0 or 1 elements, so I then test the length of the object and if it is 0 I hide the state label (I changed its ID too, to be more descriptive), or if the length is 1 I show the state label and the select element.

I'm not well versed with prototype.js, but what it looks like you're doing is passing in elements to your change handler function.
In jQuery, if you're going to be selecting using IDs, you have to prepend the id value with a #.
HandleStateApearence(
this.selectedIndex, null,
$('#state_'), $('#state_3'), $('#state_2'),
null, 1, 2, false
)

Related

Change span text with selected option

I am on beginning of the coding life. I am trying to change text in span with selected option, but it gives me values not texts. For example, when I select the bus option, I want it to shows me the "bus" text. I do not want value number. Thanks in advance.
<select id="vehicles" onchange="showChange()">
<option value="1">Bus</option>
<option value="2">Car</option>
<option value="3">Plane</option>
</select>
<span id="vehicle"></span>
<script>
function showChange(){
var selected_vehicle = document.getElementById("vehicles").value;
document.getElementById("vehicle").innerText = selected_vehicle;
}
</script>
You can first pass this keyword to the function then get the text using selectedIndex of option.
<select id="vehicles" onchange="showChange(this)">
<option value="1">Bus</option>
<option value="2">Car</option>
<option value="3">Plane</option>
</select>
<span id="vehicle"></span>
<script>
function showChange(el){
var selected_vehicle = el.options[el.selectedIndex].text;
document.getElementById("vehicle").innerText = selected_vehicle;
}
</script>
If you keep the inline declarations from your HTML ( generally the preferred approach ) you can assign your event handlers in a separate file. Also, as a point of note - if you submit the form data in the traditional manner ( rather than with AJAX etc ) then the select element needs a name - an ID will NOT appear in the REQUEST array!
document.querySelector('select[name="vehicles"]').addEventListener('change',e=>{
e.target.nextElementSibling.textContent=[ e.target.value, e.target.options[e.target.options.selectedIndex].text].join(' ')
})
<select name='vehicles'>
<option selected hidden disabled>Select mode of transport
<option value='1'>Bus
<option value='2'>Car
<option value='3'>Plane
</select>
<span id='vehicle'></span>

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

How to set the value of multiple dropdown selectors based on the value of another dropdown selector on change?

EDIT: post the question and magically it starts working :/ Maybe because I removed the alert?
So I have a dropdown selector that is supposed to represent the default for a set of dropdown selectors that make up a country list.
Here is one of the many code permutations I tried:
$("#edit-ip-ban-setdefault").change(function () {
var selected = this.selectedIndex
$(".form-type-select").each(function() {
$('.form-select').attr('selectedIndex', selected);
$(".form-select").val(selected).change();
});
});
Here is the relevant HTML for the default dropdown:
<select class="form-select valid" name="ip_ban_setdefault" id="edit-ip-ban-setdefault" selectedindex="1">
<option value="0"></option>
<option value="1"> Read Only </option>
<option selected="selected" value="2"> Complete Ban </option>
</select>
And here is the HTML for one of the many dropdowns I wish to have updated on change:
<div class="form-item form-type-select form-item-ip-ban-AF">
<select class="form-select valid" id="edit-ip-ban-af" name="ip_ban_AF">
<option selected="selected" value="0"></option>
<option value="1">Read Only</option>
<option value="2">Complete Ban</option>
</select>
</div>
I'm using jQuery 1.7, but ideally the solution would work for 1.5 to 1.10.

Select box not returning expected value

I have a form that will display different options depending on the first select box.
If option 1 is selected then a second dropdown will be shown with an option pre selected. If option 2 is selected then a different dropdown with two options will be shown.
The two new dropdowns will have the same ID and name for passing the option through to the backend but it keeps returning wrong values. Here is a
jsbin
<p class="input_title">I will use:</p>
<select name="js-rp-use" class="signup-select js-rp-use" id="rp-use" class="signup-select">
<option value="">Select Plan</option>
<option value="SOLO">Manage my own items</option>
<option value="OTHER">Manage others items</option>
</select>
<div class="js-rentpro-plan-solo">
<p class="input_title">System Plan:</p>
<select name="plan_id" id="plan_id" class="signup-select">
<option value="-1">Select plan</option>
<option value="1" selected>Plan Solo</option>
</select>
</div>
<div class="js-rentpro-plan-other">
<p class="input_title">System Plan:</p>
<select name="plan_id" id="plan_id" class="signup-select">
<option value="-1">Select plan</option>
<option value="2">Plan Business</option>
<option value="3">Plan Max</option>
</select>
</div>
<br><br><br>
<button type="button" id="submit">Submit</button>
// jquery
$("div[class^='js-rentpro-plan-']").hide();
$('.js-rp-use').change(function(){
$('#js-rp-plan-text, .js-rentpro-plan-solo, .js-rentpro-plan-other').hide();
if( $(this).val() == 'SOLO' ){
$('.js-rentpro-plan-solo').show();
} else if( $(this).val() == 'OTHER' ){
$('.js-rentpro-plan-other').show();
} else {
$('#js-rp-plan-text').show();
}
});
$('#submit').click(function(){
console.log( 'plan id is: ' + $('#plan_id').val() );
});
ID's must be unique. Instead of using the same id, use class.
The reason for you getting the wrong value is you're using $('#plan_id').val() It will return the value for the first match it finds.
EDIT:
To get the correct value with the current structure you can use:
var vl = $(this).siblings('div:visible').find('select').val()
console.log('plan id is: ' + vl );
But I suggest you modify the structure, wrap them in a form, give your select containers same class, so you'll have access to them more easily.
jsfiddle DEMO
your selector will always use the first match, regardless of you using element, class or id. Or using the class you can:
$('.signup-select:visible').val()

How to select an option with CasperJS

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+"]".

Categories

Resources