Detecting when the user chooses an option from a dropdown - javascript

I have a classic HTML select box:
Show:
<select name="show" id="showThreads">
<option value="all" selected="selected">All</option>
<option value="new">Only unread</option>
</select>
Now, I need JavaScript to make an Ajax request when the user changes the selection in the box (without jQuery).
I have tried:
Listening for clicks on the <option> tags, but it won't work for users using a keyboard or a touch device
on an interval, looping though the <option> tags and checking if the selected one changes, but it seemed to trigger even when I simply hovered over the second option.
Is there a way of doing this that will work on all browsers/devices?
Thanks!

Try the "change" event.
document.getElementById("showThreads").onchange = function() {
};

Listen for onChange on the <select> tag.

function yourAjaxCall(something) {
}
<select name="choice1" size="1" onchange="yourAjaxCall(this);">
<option value="one">first</option>
<option value="two">second</option>
<option value="three">third</option>
</select>

Related

does normal jquery id #selector work on html of an Ajax json response?

with on click event i returned the below drop down element as ajax json response, without page refresh:
<select class='custom-select col-md-4' id='family'>
<option value''> Select family</option>
<option value='1'>familyName</option>
</select>
then I want to execute a function when changed the option using:
$('#family').on('change', function(){
alert("Yeey");
});
but doesn't seem to be working.
Your code seems to be working.
Just add one more option in select
For now, you have only one option which is by default selected so no change event applied.
your script is good.
example:
<select class='custom-select col-md-4' id='family'>
<option value=''>select family</option>
<option value='1'>familyName</option>
</select>
Needs more than 1 option.
By default, the first option is selected.
So there's no on change event triggering.

HTML make <option> invalid

I have the following piece of code in a contact form for a site I am designing:
<select id="Category" name="Category">
<option value="0" selected="selected" disabled>Category</option>
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</select>
I would like set the menu such that the user cannot leave category as the selected option. Is there any way to do this with HTML? If not, how would I do it with JavaScript?
Thank you
According to the HTML5 spec,
Constraint validation: If the element has its required attribute specified, and either none of the option elements in
the select element's list of options have their
selectedness set to true, or the only option element in
the select element's list of options with its
selectedness set to true is the placeholder label option,
then the element is suffering from being missing.
If a select element has a required attribute
specified, does not have a multiple attribute specified, and
has a display size of 1; and if the value of the first
option element in the select element's list of
options (if any) is the empty string, and that option
element's parent node is the select element (and not an
optgroup element), then that option is the select
element's placeholder label option.
Therefore, you can use
<select id="Category" name="Category" required>
<option value="" selected disabled>Category</option>
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</select>
When the user click on any option, he can´t return the first one back. But he can submit form without change, then you need to validate via JS.
It's quite simple,
function validate() {
var select = document.getElementById('Category');
return !select.value == 0;
}
And the form in HTML:
<form onsubmit="return validate()">...</form>
Will disabling select work for you?
<select id="Category" name="Category" disabled>
<option value="0" selected="selected">Category</option>
...
</select>
Or maybe disabling all but selected option will work for you (as shown here: https://stackoverflow.com/a/23428851/882073)
Ideally, you would simply remove the selected attribute from disabled options on the server side when generating the HTML document to begin with.
Otherwise, if you are using JQuery, this can be done fairly easily with:
$('#Category').find('option:not([disabled])').first().prop('selected', true);
Add this to your ondomready event handler. This will force the first non-disabled option to be selected for this select element regardless of its options' selected attributes. The disadvantage of this method is that it will prevent the selected attribute from being able to be used at all with this select element.
On the other hand, if you are trying to create category headers within a select element, you should consider using an optgroup element instead, since that is the correct semantic markup for this:
<select id="Category" name="Category">
<optgroup label="Category">
<option value="1">General Info</option>
<option value="2">Booking</option>
<option value="3">Auditions</option>
</optgroup>
</select>

How to close dropdown on onchange event of selector In iOS6?

I am working on hybrid application with worklight.
When tapping on select control, a native dropdown pops out. Now I have bound onchange event on this select so when I choose any option the event gets fired but the dropdown doesn't fadeout until I tap on the done button.
I have used ('select').blur() to overcome and it is working fine for Android but not for iOS6.
I want to fadeout the dropdown with onchange.
Code:
<select id="myID" onchange="myFun()">;
function myFun(){
$('select').blur();
}
or
function myFun(){
$('#myID').blur();
}
What are the possible soultions for it? Thanks.
It seems that in iOS you cannot use .blur() on a select element, the event will be ignored.
Note: in iOS the user is expected to tap the Done button. Why confuse your end-user by introducing unexpected interaction and behavior (= not provided by the OS to begin with). For example, what if the user selected by mistake? Instead of being able to correct on the spot, s/he will be forced to tap again and select again... I recommend leaving it with the default behavior.
Updated example: instead of removing the select from the DOM and re-introducing it, I've found this.
The below works only in iOS6, though, per the question. It doesn't work in iOS7.
HTML
<div id="mySelectDiv">
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
Selected option: <input type="text" id="selectedOption"/>
JavaScript
function wlCommonInit(){
$("#mySelect").bind('change', changeValue);
}
function changeValue() {
var mySelectedIndex = $("#mySelect option:selected").index();
$("#selectedOption").val($("#mySelect option:selected").text());
if($("#mySelect").is("select")){
var fakeSelect = $("#mySelect").clone();
$("#mySelect").replaceWith(fakeSelect);
$("#mySelect").bind('change', changeValue);
$("#mySelect").prop('selectedIndex', mySelectedIndex);
}
}
While my previous answer will work, only in iOS6, the following works for me in both iOS6 and iOS7 using the iOS7-Select-Element-Auto-Close plug-in by lukewhyte.
Simply place the JS code provided in the plug-in in your project and include it in your index.html,
<script src="js/select.js"></script>
Then:
HTML
<div id="mySelectDiv">
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</div>
JavaScript
function wlCommonInit(){
$('#mySelect').iOSSelect();
$("#mySelect").bind('change', changeValue);
}
function changeValue() {
$("#selectedOption").val($("#mySelect option:selected").text());
}

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

I have the following markup:
<select onchange="jsFunction()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
When a user pulls down the combobox and selects the same option that was previously selected (or doesn't change the selection at all), JavaScript doesn't regard it as an onchange event. So, the jsFunction() is not called. But I want the jsFunction() called even in this case. How can I achieve this?
I'd do it like this:
<select onchange="jsFunction()">
<option value="" disabled selected style="display:none;">Label</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
If you want you could have the same label as the first option, which in this case is 1.
Even better: put a label in there for the choices in the box.
You have to add empty option to solve it,
I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.
<select onChange="jsFunction()" id="selectOpt">
<option value="1" onclick="jsFunction()">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
alert(myselect.options[myselect.selectedIndex].value);
}
Just set the selectIndex of the associated <select> tag to -1 as the last step of your processing event.
mySelect = document.getElementById("idlist");
mySelect.selectedIndex = -1;
It works every time, removing the highlight and allowing you to select the same (or different) element again .
Try this. Just add an empty option. This will solve your problem.
<select onchange="jsFunction()">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>​
For this problem, I have finally put a new <i> tag to refresh the select instead. Don't try to trigger an event if the selected option is the same that the one already selected.
If user click on the "refresh" button, I trigger the onchange event of my select with :
const refreshEquipeEl = document.getElementById("refreshEquipe1");
function onClickRefreshEquipe(event){
let event2 = new Event('change');
equipesSelectEl.dispatchEvent(event2);
}
refreshEquipeEl.onclick = onClickRefreshEquipe;
This way, I don't need to try select the same option in my select.
use the "onmouseup" property with each option element. it's verbose, but should work. also, depending on what your function is actually doing, you could arrange things a little differently, assuming the number is important in the handler:
<select>
<option onmouseup="handler()" value="1">1</option> //get selected element in handler
<option onmouseup="handler(2)" value="2">2</option> //explicitly send the value as argument
<option onmouseup="handler(this.value)" value="3">3</option> //same as above, but using the element's value property and allowing for dynamic option value. you could also send "this.innerHTML" or "this.textContent" to the handler, making option value unnecessary
</select>
JavaScript code:
on mousedown event: set selectedIndex property value to -1
on change event: handle event
The only drawback is that when the user clicks on the dropdown list, the currently selected item does not appear selected
It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change event.
You can handle the blur event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.

Javascript Event for Select element Selection

I'm looking to find the Javascript Event I need to put into jQuery's .bind function in order to have the function triggered when a selection is made from a <select> element.
At the moment I'm using .bind('change',function() { ...}) but I need the event to trigger when the selected option is chosen again.
Any suggestions?
I'm currently doing this successfully by clearing the dropdown box selection so that it can be re-selected. It will allow you to trigger the function again by adding this within your function before the end:
$('select option:selected').removeAttr('selected');
Change on select boxes is unreliable anyway. Read:
http://www.quirksmode.org/dom/events/change.html#t05
I'd probably go for something click (but be suspicious, somebody (--> IE) is going to make your life difficult). Or build something yourself without select.
This is possible, however it is not fully supported. Here is a sample:
html
<select id="selectId">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
jquery
$("#selectId>option").click(function(){
alert(this.value);
});
here is a mediocre approach to handle ie:
<div id="dropdownWrapper">
<select id="selectId">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</div>
js
var clickCount_guid324fF = 0;
$("#dropdownWrapper").click(function(){
if(++clickCount_guid324fF % 2 == 0){
alert($("#selectId").val());
clickCount_guid324fF = 0;
}
});
Wouldn't click work? .bind('click',function() { ...})
I once did this using mouseup, and checked where the event originated. If it was an option element, i handled the select. No listening on onchange at all:
<body>
<select id="select0">
<option value="0">option 0</option>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
<script type="text/javascript">
$('#select0').bind('mouseup', function (e) {
var src = e.target;
if (src.nodeName.toLowerCase()==='option') {
doMagicOnSelect(this);
}
});
function doMagicOnSelect(selectElem) {
console.log('current value:'+selectElem.value);
}
</script>
</body>
There is no reliable event fired when a selected option is re-chosen.
Whilst on some browsers you can catch events originating from an <option> (which you could use to trap click and keyboard events if you had the patience to try to reproduce a browser's select handling), this is unstandardised and doesn't work in IE (as it uses native Windows widgets to implement select boxes, which don't give that kind of granular access).
If you need to be able to re-fire an event when the same option is chosen again, what you have doesn't really sound like a select box to me; it could perhaps be better replaced with a scripted pop-up div full of buttons. (There are plenty of scripts that will substitute a select box for a scripted div to give you greater control on browsers where JavaScript is available.)
bind the change AND click event
$select.bind("change click", function (event) { // do something });

Categories

Resources