how to prevent onclick event to trigger in select option - javascript

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.

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>

Cancelling propagation of the onchange event of a select control

I have a select control nested inside a table cell. The Table row that contains the table cell has an onclick event. When I click on the select control to change the value the onclick event of the row is fired.
I've tried using the stoppropagation method on the onchange event but it doesn't seem to work.
Below is my code
xxxxxxx.Helper.DDGoto = function (o, e) {
e.stopPropagation();
var path = $(o).val();
if (path != null) {
this.Goto(path);
}
}
<tr onclick="somemethod()">
<td>some text</td>
<td>
<select onchange="xxxxxxx.Helper.DDGoto(this, event)">some options</select>
</td>
</tr>
The event triggered with the onchange event on your select is not firing the onclick event on your tr, they are not of the same type. They are two different events. That's also why stopping propagation of the onchange event does not stop the onclick event to be triggered.
You should instead in your onclick handler check if the select element was clicked or not:
somemethod = function (event) {
if (event.target.nodeName === 'SELECT') {
// The select was clicked, stopping...
return;
}
// The select was not clicked, go ahead...
}
To get the event in your handler, you need to change your declaration to:
<tr onclick="somemethod(event)">
I used the nodeName property for the example, but you could also use the type property of the target or any other method to detect if the select was clicked or not.
You can check this fiddle for an example.
When you click on select tag, both onChange and onClick event is fired!
I solved this by creating a onClick handler along side onChange handle and then calling e.stopPropogation() function.
Worked for me!
<select (click)="StopPropogation($event)" (change)="textureChanged($event,i)" class="form-control" id="sel1">
<option selected="isTextureSolid(nodule.texture)">solid</option>
<option selected="isTexturePartSolid(nodule.texture)">part-solid</option>
<option selected="isTextureNonSolid(nodule.texture)">non-solid</option>
</select>
Javascript code:
StopPropogation(e: Event) {
e.stopPropagation();
console.log('Click event stopped from propogating');
}
textureChanged(e: Event, i: number) {
e.stopPropagation();
console.log('textTure Changed');
let btnId = 'save' + i.toString();
document.getElementById(btnId).style.display = 'block';
document.getElementById(btnId).style.visibility = 'visible';
}

Select (trigger change) the dynamically added option of a select dropdown in Javascript/jQuery

I have a select dropdown in my webpage created dynamically as
<select id="mainDropDown" class="Field">
<option data-id="-1">Select your option</option>
</select>
I have it dynamically populated, when another event (button click) occurs
$('body').on("click", "#addOption", function () {
createOption();
$('#mainDropDown').val($("#newOption").val()).trigger('change');
$("#newOption").val("")
});
function createOption()
{
for (var k in OptionList) { // OptionList has the list of options already added to the dropdown
tempSelectedState = "";
if ($("#newOption").val() == OptionList[k].name) {
tempSelectedState = "selected";
}
$("#mainDropDown").append("<option data-id='" + OptionList[k].ID + "' " + tempSelectedState + ">" + OptionList[k].name + "</option>");
//$('body #mainDropDown').val().trigger('change');
}
}
Here the problem, is the select change event is not getting called.
$('#mainDropDown').change(function () {
//.................
}
I am trying to call it explicitly at
$('#mainDropDown').val($("#newOption").val()).trigger('change');
But when this is called, The dynamically added option to the mainDropDown is not populated yet, and hence not accessible.
The actual functionality needed is when a new option is added, it must be selected by default, also the value change event must be triggered successfully.
The addition of the new option created is a callback so, the select is populated only after change event triggered.
So remove the callback and trigger change only after populating the option.
This example is working as expected

How to fill a select element which is not embedded in a form with CasperJS?

My html code is:
<div class="setting-control">
<select class="on-off" id="custom-cache-pref">
<option value="">Default</option>
<option value="byc">Bypass cache</option>
<option value="basic">Basic caching</option>
<option value="iqs">Ignore query string</option>
<option value="agg">Aggressive caching</option>
<option value="all">Cache everything</option>
</select>
</div>
Usually with casperjs I would use
this.fillSelectors('form[name="formName"]', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
to select option "byc" but this time the "select" element is not embedded in a form!
How can I choose its value in this case?
Adapted from my answer here, you can create your own function that selects an option by value. This changes the selected index which might not trigger the select onChange event.
casper.selectOptionByValue = function(selector, valueToMatch){
this.evaluate(function(selector, valueToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.value.indexOf(valueToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
// dispatch change event in case there is some kind of validation
var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
evt.initUIEvent("change", true, true);
select.dispatchEvent(evt);
}, selector, valueToMatch);
};
casper.start(url, function() {
this.selectOptionByValue('select#custom-cache-pref', "byc");
}).run();
Alternative 1
Judging by the code of __utils__.fill() and casper.fillForm(), the selector of the form doesn't necessarily have to be a form. It may be a div:
this.fillSelectors('div.setting-control', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
Alternative 2
If this still doesn't work, you might need to resort on focusing on the select element in the page context and sending up and down key events to change the value using PhantomJS' page.sendEvent():
this.evaluate(function(){
document.querySelector('select[id="custom-cache-pref"]').focus();
});
this.page.sendEvent('keypress', this.page.event.key.Down);

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

Categories