jQuery Option De-Select Event? - javascript

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!");
}
});

Related

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>

Select option won't fire jquery event

I'm having some problems with what should be a simple jQuery show/hide based on a select's value. The select is hidden by default based on other selects, which might be why it's not working?
Unfortunately I can't change the source code in any manner, I can only add a function like this.
$(document).ready(function() {
$('#question-select-1271443').change(function() {
var selection = $(this).val();
if (selection == 'CIIC') {
$('#question-select-1082380').show();
} else {
$('#question-select-1082380').hide();
}
});
});
function val() extract the value of the attribute value of the option selected. Maybe you are trying to extract the content of the option. Example:
<select id="sas">
<option value="hi">Hello</option>
</select>
$("#sas").change(function(){
$(this).val(); // This return hi
$("option:selected", this).text() // This return Hello
});

how to prevent onclick event to trigger in select option

I have a select that triggers an event when it is clicked. But I want to prevent it to trigger again when I click in the respective option.
Is there a way to do that?
How about you try using onchange. So if there is not change in what is selected. Nothing is triggered.
Just use onchange event. Here is an example: https://jsfiddle.net/rafb0vyw/2/
$('#sel').on('change', function() {
alert('change');
})
You could check the event.target property, which will have a different value. Like this:
var select = document.querySelector('select');
var span = document.querySelector('span');
select.onclick = function(e) {
// show e.target in snippet (you would remove this line in your code):
span.textContent = 'You clicked on ' + e.target.tagName + '.' +
' Current selected value is ' + select.value;
if(e.target.tagName !== 'SELECT') return; // ignore
// The rest of your event handling comes here...
// This will only be executed when you click the SELECT and not the OPTION.
};
<select>
<option value = 'A'>Option A</option>
<option value = 'B'>Option B</option>
</select>
<span></span>
Make sure to have the event parameter (named e in the above example) defined in your event handler function.

Intercept value changes within .blur() event

I'm using .blur() function to execute some code every time a text field loses focus (also when its value doesn't change).
Now I need to add some logic that must be executed only when text field value changes. Is there a way to combine .change() event with .blur()? Or, better, is there a way to know if the value in my text field is changed just using .blur()?
Not directly, but you can store the value on focus event..
something like
$('input')
.on('focus',function(){
// store the value on focus
$(this).data('originalValue', this.value);
})
.on('blur',function(){
// retrieve the original value
var original = $(this).data('originalValue');
// and compare to the current one
if (original !== this.value){
// do what you want
}
});
Of course you could just bind different handlers for each event..
$('input')
.on('change', function(){/*your change code*/})
.on('blur', function(){/*your blur code*/});
The event change is trigger every time that the field lose the focus and the content has change. I think what you need is to use change() instead of blur(). Take a look at this jsfiddle
$('#in').change(function(){
alert('change!');
});
If what you need is to execute the same code when the input loses the focus and when the value changes, you can combine both events
$('in').on('change blur', function(){
//code
});
you can use closure to store the previous value and compare them later
var createOnBlurFunc = function(){
var prevVal = '';
return function(e){
if(prevVal === $(this).val()){
//same value
} else {
prevVal = $(this).val();
// do something
}
}
};
$('input').blur(createOnBlurFunc());
I think this is a more generalized way, for those that are created on the fly:
var $bodyEl = $('body'), inputOldValue;
$bodyEl.on('focus', 'input, textarea, select', function () {
inputOldValue = $(this).val();
});
$bodyEl.on('blur', 'input, textarea, select', function () {
if (inputOldValue != $(this).val()) {
$(this).trigger('changeBlur');
}
});
input, textarea, select is faster than :input as a selector.

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