I have a page that loads with a dropdown in it with a select dropdown list with an id = "accounts". When the page loads it is already on the Account Orange page. I would like to use JQuery to find the select id element and then force it click on the 3 option which should be index 2.
<select id="accounts" onChange="changeAccount(this.form,this[this.selectedIndex].value)">
<OPTION value="">Select One...</OPTION>
<OPTION value="111">Account Red</OPTION>
<OPTION value="222">Account Yellow</OPTION>
<OPTION value="333">Account Blue</OPTION>
<OPTION value="444" selected>Account Orange</OPTION>
</select>
Something like this works:
jQuery('#accounts>option:eq(2)').prop('selected', true);
Currently when the page loads it does select the correct option despite the "selected" tag but it does not fire it to the OnChange function to select "Account Yellow" and then it would reload the page. That's what I would like it to do.
First, it's better to set the value of the SELECT by value instead of index. Because you might want to add extra OPTION's later (in your source code or dynamically) and then your index count is off.
Second, I find it better practice to change the value of the SELECT, instead of changing HTML attributes/properties which make it selected (e.g. not setting/changing the selected property of the OPTION, but changing the value of the SELECT). Otherwise, you might end up with more than one selected OPTION's which might work, but is not very clean coding.
Third, the suggested >option:eq(2) selector might not work if you're using OPTGROUP's, because then the OPTION is not a direct descendant of SELECT.
So, my suggestion is to use:
jQuery('#accounts').val('222').change();
It selects the right SELECT field, then sets the value to 333 and then fires the onchange event (you need to do that manually in this case).
$('#accounts>option:eq(2)').prop('selected', true).promise().then(function(){
changeAccount(this.form,this[this.selectedIndex].value)
});
Try the following:
jQuery('#accounts>option:eq(2)').prop('selected', true).closest('select').trigger('change');
Related
On a product page, a customer can select from different variants. In a "select" element, all the variants are stored. This element is hidden with display none. So, users can select variants using all fancy things like swatches and other fun stuff but under the hood its just a "select" element which keeps track of which variant is being used. Its value is variant id.
I am attaching an image to be more clear on what's going on.
Goal: Get the variant id on change of variant.
Problem: I am unable to detect the change event on this select element.
Limitations: I am not allowed to touch the HTML of this code. I can only append a javascript file at run time on this page in <head> tag and I need to detect the change event in that script.
$(document).ready(function(){
$('body').on('change', "select[name='id']", function(){
console.log('here');
});
});
I can get its value just fine with below code at any time I want.
console.log($("select[name='id']").val());
Any ideas that why change event won't be detected?
As per the jQuery documentation change() is not fired when val() is set programmatically
Note: Changing the value of an input element using JavaScript, using .val() for example, won't fire the event.
You need to do it manually when you set val()
$("select[name='id']").val(354).trigger('change');
Edit[0]: After your comments on what you were trying to do I took a quick look at the js.
I found that the template fires a custom event variantChange
$("#ProductSection--product-template").on("variantChange", function(evt){alert($("select[name='id']").val());});
Good Luck;
Since the goal was to get the current value of variant id, here is how I got to that.
Getting the value is not a problem, so when page loads, store the initial value in localStorage then listen to change event on form. Thankfully, change event is triggering on Form element.
$('body').on('change', 'form[action^="/cart/add"]', function () {
console.log($('select[name="id"]').val());
});
Compare the value with previous value and see if its changed. If yes, then do my thing. If not, wait for another change event on form. Yeah, I hope it will work for the long run.
Thank you all !!
I think that should know what triggers this, I mean if change when you change the select of the sizes then inside this you get the value that you need, for example:
$(document).on("change","#select1",function(){
var valuneed = $("#select2").val();
console.log(valuneed);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1">
<option value="11">size a</option>
<option value="21">size b</option>
</select>
<select id="select2">
<option value="21">value a</option>
<option value="22">value b</option>
</select>
And if the update of the second select takes a seconds (is the usual) then you just add a settimeout
If there is more than just on trigger, then you:
$(document).on("change","#select1, #selector2, #selector3",function(){
Let me know if this is what you need.
I have created a select element drop down list in HTML. The select tag has three options. An "onclick" JS event is attached to the select tag. In JavaScript, I have a matching function that alerts the user if and only if the first option has been selected. Here is a JSFiddle with my code.
https://jsfiddle.net/TempusF/rad11vgx/12/
The problem I am having is that, on Firefox for mac, this alert will only be displayed if you first select a different option. That is to say, if the page loads and "Zone 1" is displayed, clicking Zone 1 a second time will not trigger the alert. You must click to Zone 2 or Zone 3, and then click back to Zone 1 to get the alert.
However, on Firefox for Windows, any click on the Zone 1 option will display the alert.
This leads me to believe that I am incorrectly using the onclick event when a different event is more idiomatic. Perhaps the expectation is that I have a button below the select element that triggers the alert function, thus deferring execution. However, I would like to create an interface that reacts immediately when a select option has been chosen.
Here is the HTML:
<select id="zoneSelect" onclick="updateChar();">
<option value="zone1">Zone 1</option>
<option value="zone2">Zone 2</option>
<option value="zone3">Zone 3</option>
</select>
Here is the ecmascript.
function updateChar() {
var zone = document.getElementById("zoneSelect");
if (zone.value == "zone1"){
alert("You clicked Zone 1.");
}
}
You shouldn’t use onclick in modern html, but you might try the following:
onchange="updateChar();"
Better still, you should set the event handler in the startup code. In any case, it’s still the change event.
Also, I recommend that a drop-down menu begin with a harmless null value, so that you don’t default to the first value — unless, of course, that is the intention:
<option value="">Choose one …</option>
Edit
Apropos by comment that you shouldn’t use inline event handlers in modern JavaScript, here is how you would do it today:
In HTML:
<select id="zoneSelect">
<!-- options-->
</select>
In JavaScript:
document.addEventListener("DOMContentLoaded",init);
function init() {
document.querySelector('select#zoneSelect').addEventListener('click')=updateChar;
}
Better still, if the select element is part of a form, then it should have a name attribute, and you wouldn’t need an id attribute. In JavaScript, you can refer to it as:
document.querySelector('select[name="…"]')
and ditto for any CSS you might apply.
Here is a jsfiddle. http://jsfiddle.net/cuycbxxp/
I have a dropdown selection here for 2. names and numbers.
Select name and then select numbers. once a dropdown is selected for numbers, execute function get executed and a output is displayed at the console.
This might look like it is working fine. but open the console and click on the dropdown. execute function executes before we even select a dropdown option.
How to ensure that execute function should execute only when the user clicks on one of the option tags ?
Markup:
<div ng-controller="MyCtrl">
<div>
<label>Names:</label>
<select ng-model="params.name">
<option value="pa">Taeo</option>
<option value="ws">Wers</option>
<option value="pn">Petin</option>
</select>
<br>
<label>Numbers:</label>
<select ng-click="execute()">
<option value="22">22</option>
<option value="33">33</option>
</select>
</div>
</div>
ng-click will trigger when you click any element with that decorator, not the option. I think ng-change will probably be a better directive in your case.
Change <select ng-click="execute()"> to <select ng-change="execute()">
The ng-click gets executed whenever you click on the object (in this case, the dropdown). The ng-change gets executed when the form element is changed, which is whenever the user changes the dropdown item.
You need to use angular ng-change (ngChange).
Use
ng-change="execute()"
instead of
ng-click="execute()"
Doc Reference ng-change: https://docs.angularjs.org/api/ng/directive/ngChange
Doc Reference ng-click: https://docs.angularjs.org/api/ngTouch/directive/ngClick
Since you use ng-click, the click event fires at the time you click the select box. However if you use ng-change, the change event will fire when the select box's value change based on the option selection, thus execute() will fire.
I know this may be kind of a simple question, but cant seem to find an answer anywhere, I have a form in my site, with multiple form elements like combobox, text, radio buttons, checks etc, My requirement is to change the values of those form elements when a user from dropdown combobox is selected, I have successfully implemented that functionality with all the form elements except for the comboboxes, I cant seem to find any way to change the options of the combobox...
Since you included the jQuery tag,
select.val(value);
where select is the jQuery select element and value is the value.
JSFiddle
<select>
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
<script>
$('select').val('2');
</script>
New option can be added to the combobox as below
$('< option value=’Value’ > Sample Value < /option >').appendTo('#ComboId');
a dropdown value can be selected by
$('#ComboId').val('Value');
I have this code below. Everything will be disabled after a selection.
<select id="dropdown" name="dropdown" onchange="javascript:this.disabled = 'disabled';">
<option value="dropdown">Pls select one
<option value="apple">Apple
<option value="oragne">Orange
<option value="grapes">Grapes
</select>
But when I hit submit, the value for the "dropdown" is not being passed. Am I missing something here?
Disabled form controls don't get submitted. This is normal behaviour.
One work around is to copy the selected value to a hidden input that would get submitted.
(I really don't recommend disabling a select on change though - what if the user accidentally clicked the wrong thing? What if they were trying to select with the keyboard?)
(And as another aside, you don't need javascript: in inline event attributes.)
EDIT: How to implement the hidden input? Well, give the hidden input the name that your server-side code expects (and remove the name attribute from the select element):
<input type="hidden" name="dropdown" id="dropdown">
And then your onchange attribute would be something like:
<select onchange="document.getElementById('dropdown').value=this.value; this.disabled=true;">
The value of your selected option from your dropdown will not be passed its because you had your dropdown disabled. maybe thats the reason why. try not disabling it.
It seems disabled selection does not submit by default.
You can add another hidden selection element. And use script to make choice to submit.
It doesn't really make sense to disable a control, then submit its value. If you want the value submitted, don't disable it.
Anyhow, one option is to enable the control before submitting:
<form ... onsubmit="this.dropdown.disabled = false;">
Now you don't have to copy the value anywhere and the value will be submitted whether the control is disabled or not.