Alternative to onblur/onchange in select - javascript

I am trying to find a way to run a JavaScript function when a user selects an option in an HTML select box, regardless of whether this option was already selected. So onchange is out of the question.
The problem with using onblur is that (in Chrome and Safari, at least) the event is not triggered until the user clicks another element. This can also prove annoying if the user focuses on the select, then clicks away without choosing an option, in which case I do not want the event to be triggered.
I was able to get some success by giving each of the options an onmouseup handler, but this only works in Firefox, as far as I can tell. Any ideas?

Since nobody has bothered to answer this, I'll post a generic version of my code:
<select id="mySelect" onfocus="this.selectedIndex=0;" onchange="userDidSomething(event)">
<option>Choose one:</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
The JavaScript:
function userDidSomething(event) {
// Your Code Here.
}

Try using
var s = document.getElementById("mySelect");
s.attachEvent("onchange", function() {
// function here
});

Related

.focus() event behavior with Javascript

I have these three tabs:
When a user uses the mouse and clicks on one of the tabs, (Compliance Notes in this example), the proper element on the tabbed page gets focus and is highlighted appropriately.
However, if the user uses the keyboard and presses the Tab key to highlight the tab they want, and then presses the Enter key to select that tab, the tabbed page gets focus. Then, via JavaScript, I set focus to the proper element on that tabbed page (by using the .focus() method on that element), and the same asp:DropDownList in the example behaves like the user not only selected the element, but clicked on it:
If you then either hit Enter or Tab, manually, the dropdown list closes and the element looks like it did if the user clicked on the tab versus using the keyboard:
So, is there a "simple" way, after I use the .focus() method, to then simulate either an Enter or Tab keystroke so the element will have focus but not have the dropdown list triggered? Or is there another way, using the .focus() method or some other approach, to prevent the dropdown list from being triggered when using the keyboard to navigate the page?
The behavior you are mentioning seems to be related to the keydown event.
Here's an example - when you type in the text field it should set focus on the dropdown. When you press enter in the text field, notice that the first example (using keydown) behaves similarly to what you reported. The second example (using keypress) does not.
document.querySelector('#typeHere').addEventListener("keydown", (e) => {
document.querySelector('#focusMe').focus();
});
document.querySelector('#typeHere2').addEventListener("keypress", (e) => {
document.querySelector('#focusMe2').focus();
});
<select id='focusMe'>
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>
<input id='typeHere' >
<br><br>
<select id='focusMe2'>
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>
<input id='typeHere2'>

Detect change event on hidden select element

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.

Click event on select with single option (Firefox) doen't work

I made a search tag interface, so I need to put my found tags like option in select. Then I wait user click (bubble up) on option and add this tag to groups of tags which will send to server. Why doesn't it work in FF? I know workaround solution to use the mousedown event instead of the click event, but I want to understand the logic, maybe it's a bug and I need to report it to the FF developers. By the way, everything works well when I add a few options, I think it is somehow related to the fact that by default 1 option is always select = true.
Codepen sandbox
document.querySelector("#b").addEventListener("click", function() {
console.log(1);
});
<select name="a" id="b">
<option value="one">one</option>
</select>

Responding to Onclick in a <select> HTML Element

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.

Selecting an item in an HTML SELECT list using keyboard doesnt trigger the CLICK event

I have an HTML select list which, when an item is selected, must show different information beneath it. The onclick or JQuery change events are triggered when a select list item is selected by being clicked on (mouse), but not when the user uses key presses (keyboard).
Any idea what event to watch in order to determine when the selected list item has changed?
Here is a BASIC test example:
<select id="mylist" name="mylist">
<option value="">(none)</option>
<option value="1">Test 1</option>
<option value="2">Test 2</option>
<option value="3">Test 3</option>
</select>
<span id="myspan"></span>
<script type="text/javascript">
$("#mylist").change(function() {
$("#myspan").html($("#mylist").attr("selectedIndex"));
});
</script>
The code will run when the select box loses focus
(press tab or click anywhere outside of the select box)
The OnChange event is different from browser to browser when an item is changed with keyboard shortcuts.
For example, in IE, the event is fired the same way with the keyboard and the mouse, but in Firefox, to trigger the event with the keyboard, you need to press enter when the item selected is the good one. The event is also fired when the <select> loose focus (OnBlur - and only if OnChange has not already been fired) as Gaby pointed out.
It the way it's made...
It works if you change add attribute:
multiple="multiple"
if you want the dropbox, I'd bind a 'global' keyup event handler to the document.body
and do some magic there.

Categories

Resources