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?
Related
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>
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>
I try to call a function when a value from the select box is chosen. I would also have a default value selected and a button appear for that value on the page.
This is my select box:
<select id="messagingMode" class="bootstrap-select" >
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
This is the js:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
And the function just prints the selected value for the moment:
function showCorrespondingAuthorizationBtn(select) {
console.log(select.val());
}
Nothing is printed in the console, why doesn't this work?
Try with direct call function name not with function() .Default bind with this in change function
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn() {
console.log($(this).val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="messagingMode" class="bootstrap-select">
<option value="1" selected="selected">Webhooks messaging</option>
<option value="2">Real time messaging</option>
</select>
You are invoking the function, not passing it as reference. Also this is not what you think it is in that context.
Try:
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn);
function showCorrespondingAuthorizationBtn(event) {
console.log($(this).val());
// or
console.log(this.value);
}
Use the jQuery event delegation:
$('#messagingMode').on('change',function(){
console.log($(this).val());
});
Here is a working fiddle.
$('#messagingMode').change(function () {
showCorrespondingAuthorizationBtn($(this).val());
});
It is not triggering because your are invoking the method on your event attachment logic.
// calling the invocation operator () triggers the method
$('#messagingMode').on('change',showCorrespondingAuthorizationBtn(this));
In order to solve this, try the following code.
function onDropdownChanged() {
var sender = $(this);
console.log(sender.val());
}
$(document).ready(function() {
$('#messagingMode').on("change", onDropdownChanged);
})
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!");
}
});
I have a form that needs to display specific select options ("locations") based on the user's ZIP, which is in a number field above. In this example, I need the option "Out of Range" to hide and the "In Range" to show when the user enters "12345" in the input.
This is my HTML:
<!--Zip-->
<div class="zip-field">
<label for="zip">Zip Code</label>
<input type="number" id="zip" name="zip" />
</div>
<!--Location-->
<div class="location-field">
<label for="location">Location</label>
<select id="location" name="location">
<option value="In Range">In Range</option>
<option value="Out of Range">Out of Range</option>
</select>
</div>
This is my jQuery:
$('#zip').on('change',function(){
if ( $(this).val() == "12345" ) {
$("#location option[value='In Range']").show();
$("#location option[value='Out of Range']").hide();
}
});
Should be pretty straightforward, but no cigar.
There are two things you need to change here:
You need to set an event handler to the zip input element. $('#zip').val( ... ); only sets the value once when that line is executed.
You need to select the option better. $("#location option[value='In Range']").show(); will not show the option you want. You have to set the value of the selector input to a value that matches the option you want.
Change your javascript to this:
$("#zip").on('blur', function(){
if ( $(this).val() == "12345" ) {
$("#location").val("In Range");
}else{
$("#location").val("Out of Range");
}
});
Notice that I'm using $('#zip').on('blur', ...); to register an event handler, setting it to the blur event and passing in a function to be executed when that event fires.
Then I set the value of the location selector input to the correct value of the option you want to select.
DEMO
Hiding an option won't work across browsers, it is same as binding event to option elements you can do only very limited thing with them. instead remove them and cache them for later use.
$(function(){
var $location = $('#location');
$location.data('options', $location.find('option')); //cache the options first up when DOM loads
$('#zip').on('change', function () { //on change event
$location.html($location.data('options')); //populate the options
if ($(this).val() == "12345") { //check for condition
$location.find("option[value='Out of Range']").remove(); //remove unwanted option
}
});
});
Fiddle
You should monitor the the value as it changes using the method below:
$('#zip').on('keyup',function(){
$("#location").val('Out Of Range');
if ( $(this).val() == "12345" ) {
$("#location").val('In Range');
}
});
The on function binds an event listen to that Element. The keyup event listens for when the key is released inside the your field. You can then compare the value to what ever and show / hide as needed.