click event on HTML select element - javascript

I would like to listen a click event in the event. The change event is only fired when I select other items, but I need an event to be triggered even I click the selected one.
For example, when I select Apple, change event triggered. Then I select Apple again, I need an event to be triggered as well.
$("#fruit").on('click', function() {
console.log("click event");
});
$("#fruit").on('change', function() {
console.log("change event");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="fruit">
<option>Apple</option>
<option>Pear</option>
</select>

I solve that problem wrapping the select element with a div element and using the onclick over the div, after that the function javascript call the select element using the id, like this:
HTML:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div onclick="ReadSelected()">
<select id="fruit">
<option value="Apple">Apple</option>
<option value="Pear">Pear</option>
</select>
</div>
Javascript:
function ReadSelected(){
var selectedValues = $("#fruit").val();
console.log(selectedValues); //if you select apple will be ['Apple']
}

According to the jQuery docs:
The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
As there is no change when you click on 'Apple' when 'Apple' is already selected, it looks like the 'click' event is your best option. Why exactly do you need the change event to fire when you click the same option? Maybe there is a better solution than firing the change event in this case?

You may check condition on click like below to achieve what you want .
var flag = false;
$('#fruit').on('click', function() {
if (flag) {
console.log($(this).val());
flag = false;
} else {
flag = true;
}
}).on('blur', function() {
flag = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="fruit">
<option>Apple</option>
<option>Pear</option>
</select>

Related

how to make a javascript event occur only if another event to the same element is first triggered?

I have attached a mouseleave event to the select tag. But I want this event should only occur if a user first clicks the select tag and then removes the mouse from.
function loseFocus() {
var dateSelect=document.querySelector('[name="dayCount"]');
dateSelect.blur();
console.log('mouse leave event triggered')
}
<select name="dayCount" onmouseleave="loseFocus()">
<option >op1</option>
<option >op2</option>
<option>op3</option>
</select>
You can define a variable as false and run a click event on your drop down, then in your call back for the click event set that variable to true. Then in your blur event call back a conditional to check if the variable is true.
You may want to do a mouseout event if you don't want to have to click off the drop down menu after a selection has been made.
let dateSelect = document.querySelector('[name="dayCount"]');
let clicked = false;
function changeClick(){
clicked = true;
}
function checkFocus(){
clicked === true ? console.log('BLUR FIRED -> select has lost focus') : null;
}
function mouseOut(){
clicked === true ? console.log('MOUSEOUT FIRED -> Your mouse is not over the select element') : null;
}
dateSelect.addEventListener('click', changeClick);
dateSelect.addEventListener('blur', checkFocus);
dateSelect.addEventListener('mouseout', mouseOut);
<select name="dayCount">
<option >op1</option>
<option >op2</option>
<option>op3</option>
</select>

Select onchange with keyboard - do not trigger onchange event until focusout?

I have a select that is bound to a change event so that it will take the user to a new page when a selection is made. It's fine with the mouse, but when I try to make a selection using my keyboard's arrow keys, the change event fires as soon as I press the arrow rather than waiting for me to tab out, so I can only ever select the first option with my keyboard.
$selectLocation.on('change', function() {
location.href = '/data#' + $(this).val().toUpperCase();
});
How can I differentiate between a click and a keypress on my change function, or otherwise make the change function not fire on keypress?
Consider the following snippet:
// Sets the redirect based on user activity on #test.
$('#test').on('change', function(e) {
if ($(this).data('clicked')) {
// A click was used to change the select box, redirect.
console.log('clicked redirect');
}
});
// Sets data-keypressed on #test when the down or up arrow key is pressed.
$('#test').on('keydown', function(e) {
var code = e.keyCode || e.which;
if (code === 38 || code === 40) {
// Reset data-clicked.
$(this).data('clicked', false);
// Bind focusout to the redirect.
$('#test').unbind('focusout').bind('focusout', function(e) {
if ($(this).val !== '') {
// An option is selected.
console.log('keyboard focusout redirect');
}
});
}
});
// Sets data-clicked on #test.
$('#test').on('click', function(e) {
// Unbind the focusout event added in the change handler.
$(this).unbind('focusout');
// Set data-clicked to be used in the change handler.
$(this).data('clicked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test" data-clicked="false">
<option value="">-- Select an Option --</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
This snippet uses the HTML data attribute to set whether or not the select box was changed with a click, and sets the focusout event on the select box when the select box was changed on keypress. The redirect will occur immediately on click selection, but when using the keyboard will only occur when the select box is focused out and a value is selected.
As selection causes (in your case) navigation, the simplest solution is to avoid change event. Instead save initial value and compare against current when clicked or blured.
var defaultValue = $('#select').val();
$('#select').focus();
$('#select').on('click blur', function(event) {
if (defaultValue === $(this).val()) {
return
}
// no need to save with location.href
defaultValue = $(this).val()
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="option" id="select">
<option value="1">1</option>
<option value="2">2</option>
</select>

Behave differently when selecting a dropdown select by click or arrow keys

<select id="s">
<option value="1">selected1</option>
<option value="2">selected2</option>
<option value="3">selected3</option>
<option value="4">selected4</option>
</select>
<div id="se">
</div>
$('body').on('change', '#s', function() {
$('#se').text($('#s :selected').text()+" / unfortunatly it also triggers when Im moving with the UP and DOWN keys, not just with select");
});
https://jsfiddle.net/8kLke2je/
I want this event triggered if I pick an item from the dropbox with mouseclick and not with UP and DOWN arrows.
Just use the "click" event on the select:
$('#s').click(function(){
var sv = $('#s').val();
$('#se').html("That\'s it: "+sv);
});
Here there is a fiddle for it: https://jsfiddle.net/nemoneminis/rwza9xzt/1/
.on passes the event into the callback function. You can utilize that to detect whether it was a click or keypress.
If you bind separately to click and keyup, you can detect which one by checking the event type:
$(document).on('click keyup', '#s', function(e) {
if ('click' == e.type) {
$('#se').text($('#s :selected').text());
}
});

jQuery Option De-Select Event?

I would like to detect the event where an option is de-selected from a select element. So for instance, if my HTML is:
<select id="select_box">
<option value="1">Hot</option>
<option value="2">Cold</option>
<option value="3">Just Right</option>
</select>
And the second option is selected (value="2"), and then the user de-selects it by clicking on another option (such as value="3") or clicking the same option again, how do I detect that event using jQuery? My goal is to fire off a function when it happens.
I tried the following:
$("#select_box option:selected").change(function() {
console.log($(this).val());
});
But it didn't work.
The change event should go on the select element itself:
$("#select_box").change(function() {
console.log($(this).val());
});
This event fires when the value of the select is changed and will match the behaviour you require.
I want the value of the option that was de-selected.
In that case you would need to store the previous value when it's selected, something like this:
$("#select_box").change(function() {
var $select = $(this),
currentValue = $select.val(),
oldValue = $select.data('previous-value');
// do stuff...
$select.data('previous-value', currentValue);
});
Well, this is how I would handle this with with a change Event listener.
$("#select_box").on('change', function(e){
var $t = $(this), data = $t.data('last') || {optText:'none', val:'none'};
$t.next().text('last was ['+data.optText+'] and its value is "'+data.val+'"').end()
.data('last', {optText:$t.children('[value="'+$t.val()+'"]').text(), val:$t.val()});
});
Fiddle HERE
I would enable the element when the option is selected using the one() event binding method
change event will fired only when value is changed which is required by you
$("#select_box").change(function() {
console.log(this.value);
});
You can do it manually some thing like below code i given,
var xSelectedOption = 0;
$("#select_box").change(function() {
if(xSelectedOption != $(this).val())
{
xSelectedOption = $(this).val();
console.log("Option was changed!");
}
});

Select box option value on right-click: without using option:selected

My question is different than just "how do I get the selected option from a select box".
In select box, no option element is 'selected' prior to right-clicking on it.
On right-clicking an option, I want to get the value of that option element.
Therefore, option:selected won't work.
<select name='mySel' id='mySel' multiple>
<option value='val1'>myOption1</option>
<option value='val2'>myOption2</option>
</select>
I have bound rightclick event to the context menu:
// bind right click event to context menu
(function( $ ) {
$.fn.rightClick = function(method) {
$(this).bind('contextmenu rightclick', function(e){
e.preventDefault();
method();
return false;
})
};
})( jQuery );
The event handler code below will only work if an option is selected prior to right clicking:
$('#mySel').rightClick(function(e){
alert($('#mySel option:selected').text());
});
Without using option:selected, how do I get the value of right-clicked option?
The target property of the event parameter will refer to the element which triggered the event, in your case the option element that was right-clicked:
$('#txBase').rightClick(function(e){
alert(e.target.value); // val1 or val2
});
DEMO
A few notes about your code:
no need to return false and to e.preventDefault, both statement have the same result so just use one or the other
you might wanna check if method is not undefined and is a function before calling it, otherwise it will break
when you call method, pass the parameter e to it otherwise you won't be able to use inside your callback
Here's the modified code:
$(this).bind('contextmenu rightclick', function(e) {
e.preventDefault();
if (method && $.isFunction(method)) {
method(e); // pass the event parameter to your callback
}
})
<select name='mySel' id='mySel' multiple>
<option value='val1' oncontextmenu="getValue(this);return false">myOption1</option>
<option value='val2' oncontextmenu="getValue(this);return false">myOption2</option>
</select>
<div id="status"></div>
<script>
function getValue(t){
document.getElementById('status').innerHTML=t.value;
}
</script>
What about this?

Categories