jquery select2 .on("change", function(e) reset option - javascript

i am using select2.
Usage : if a value is "COUNTRY", i want to add a onchange event to the select2, else i want to remove the onchange event as shown below :
var reportLevel = getReportLevel();
if (reportLevel != "COUNTRY") {
$("#selected_countries").on("change", function(e) {
prepareGlidModel(e);
});
} else {
$("#selected_countries").on("change", function(e) {
});
}
Issue : Not being able to remove the onchange event, even if the else block is called.
Events are called based upon the reportLevel value selected in a dropdown.

try following:
var reportLevel = getReportLevel(),
// by default unbind/off change event
$select = $("#selected_countries").off("change");
// and if country then bind it
if (reportLevel == "COUNTRY") {
$select.on("change", function(e) {
alert("you selected :" + $(this).val());
});
}
Working example here: http://jsfiddle.net/JB89B/1/

i think on else case you want to reset the value to default for this you have to use
$("#selected_countries").val('default value')
and if u just want to prevent the default action of onchange event than on else you can write
e.preventDefault()
this will help

You can use off to deatach event handlers from your elements as shown below:
$("#selected_countries").off('change');

Related

Kendo toolbar button not firing click event after being enabled

This is my logic, here I am trying to disable the save changes button and prevent click event on it if the user enters a duplicate value and enable it again if the user changes the values but after enabling it the update / save event does not occur am I doing something wrong? This is my code
function OnChange(data) {
//data.preventDefault();
$(".k-grid-save-changes")
.attr("role", "button")
.removeClass("k-state-disabled")
//.addClass("k-grid-save-changes")
.click(function () {
return true;
});
//console.log("data", data.items["0"].ProviderTypeName);
var name = data.items["0"].ProviderTypeName;
var Id = data.items["0"].Id;
var grid = $("#grid").data("kendoGrid");
//console.log("Grid ", grid);
grid.tbody.find('>tr').each(
function () {
$(this).css('background', 'white');
var dataItem = grid.dataItem(this);
//console.log(dataItem.ProviderTypeName)
if (dataItem.ProviderTypeName == name && dataItem.Id != Id) {
$(this).css('background', 'red');
$(".k-grid-save-changes")
//.removeClass("k-grid-save-changes")
.addClass("k-state-disabled")
//.removeAttr("role")
.click(function () {
return false;
});
}
});
}
This is where is call the on change event
.Events(events => events.RequestStart("OnRequestStart").Change("OnChange").RequestEnd("OnRequestEnd").Error("onError"))
If I remove the "return false;" it is working as expected but this allows duplicated values to be saved. So I have used this.
If I understand correctly in your code you do exactly what you mention as a problem. At every change you disable the save functionality with the return false. You don't enable it again at any point.
If you add an event handler to the button then you have to undo it at a later point. Since though I don't believe that the validation should occur at the change event but at the button click I would suggest to use the grid Save event where you could iterate dataSource.data() of your grid (much better) do your check and if anything happens return false.
One other way to go since you probably want the css effect with the background is to keep your code and discard the click event. Just set a flag that you could use in the save event. Something like this:
if(// your control){
$(this).css('background', 'red');
duplicatedValue = true;
}else{
.removeClass("k-grid-save-changes");
duplicatedValue = false;
}
And in the save event
function onSave(){
if(duplicatedValue){
return false;
}
}

Selectize.js: onItemAdd event triggered when silently adding an item

Using Selectize.js, I'm trying to initialize the dynamically pre-select one of the item of the list without triggering the onItemAdd event. In the following code, the event is triggered even if the silent parameter is truthy:
$(function () {
$('select').selectize({
onItemAdd: function () {
alert("Add item");
}
});
// this triggers an the event
$('select')[0].selectize.addItem('2', true);
});
JSFiddle: http://jsfiddle.net/zuzat0dc/1/
According to the documentation:
addItem(value, silent): "Selects" an item. Adds it to the list at the current caret position. If "silent" is truthy, no change event will be fired on the original input.
Any idea how to avoid triggering the onItemAdd event? Is the silent parameter b0rked or should I use the change event instead?
A quick fix that worked for me was to keep a state flag and refer to it in the event handler...
$(function () {
var initialising = true;
$('select').selectize({
onItemAdd: function () {
if(!initialising) {
alert("Add item");
}
}
});
// this triggers an the event
$('select')[0].selectize.addItem('2', true);
initialising = false;
});
The silent parameter in addItem(value, silent) affects only to the fact whether or not the change event. You can't avoid item_add event with silent = true.
The only thing that worked for me was to store item_add event locally, remove it from selectize instance and set it back after I added the item:
onItemAdd: function(val) {
var e = this._events['item_add'];
delete this._events['item_add'];
this.addItem(123);
this._events['item_add'] = e;
}

Keeping the submit button disabled until a change is made

In my VB.NET project, I have a UI with some text input fields and a save/submit button. I want the save button to be in a disabled state on page load, and remain that way until a change is made to one of the inputs. And the save button should get disabled again if the values entered by the user are the same as they were at page load. So basically, the save button should be enabled only when there is an actual change.
How can I do this using jquery?
$(':input').change(
function(){
$("#submitButtonId").prop("disabled",false);
}
);
since you said it is dynamic, use on.
$(document).on("change", ":input",
function(){
$("#submitButtonId").prop("disabled",false);
}
);
You can handle that in the change event
$('input[type="text"]').on('change', function() {
// Change event fired..
$('input[type="submit"]').prop('disabled', false);
});
//This will bind all existing and dynamically added selects onChange to the handler
$(document).on('change', function(e) {
onChangeHandler();
}
// handle the event
function onChangeHandler() {
if (checkValues()) {
$('#yourButtonId').prop("disabled", false);
}
else {
$('#yourButtonId').prop("disabled", true);
}
}
// check all values against originals - data-* attributes are a good way to store data on
// an element. So have you can have:
<select id="id1" data-originalvalue="myValue"></select>
// compare the current value to the original value - if any one of them differ, return
// true
function checkValues() {
$.each($('select[data-originalvalue]'), function() {
if ($(this).val() !== $(this).attr(data-originalvalue){
return true;
}
return false;
});
}

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Do not fire one event if already fired another

I have a code like this:
$('#foo').on('click', function(e) {
//do something
});
$('form input').on('change', function(e) {
//do some other things
));
First and second events do actually the same things with the same input field, but in different way. The problem is, that when I click the #foo element - form change element fires as well. I need form change to fire always when the content of input is changing, but not when #foo element is clicked.
That's the question )). How to do this?
Here is the code on jsfiddle: http://jsfiddle.net/QhXyj/1/
What happens is that onChange fires when the focus leaves the #input. In your case, this coincides with clicking on the button. Try pressing Tab, THEN clicking on the button.
To handle this particular case, one solution is to delay the call to the change event enough check if the button got clicked in the meantime. In practice 100 milisecond worked. Here's the code:
$().ready(function() {
var stopTheChangeBecauseTheButtonWasClicked = false;
$('#button').on('click', function(e) {
stopTheChangeBecauseTheButtonWasClicked = true;
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
var self = this;
setTimeout(function doTheChange() {
if (!stopTheChangeBecauseTheButtonWasClicked) {
$(self).val($(self).val() + ' - changed!');
} else {
stopTheChangeBecauseTheButtonWasClicked = false;
}
}, 100);
});
});
And the fiddle - http://jsfiddle.net/dandv/QhXyj/11/
It's only natural that a change event on a blurred element fires before the clicked element is focused. If you don't want to use a timeout ("do something X ms after the input was changed unless in between a button was clicked", as proposed by Dan) - and timeouts are ugly - you only could go doing those actions twice. After the input is changed, save its state and do something. If then - somewhen later - the button is clicked, retrieve the saved state and do the something similar. I guess this is what you actually wanted for your UI behaviour, not all users are that fast. If one leaves the input (e.g. by pressing Tab), and then later activates the button "independently", do you really want to execute both actions?
var inputval = null, changedval = null;
$('form input').on('change', function(e) {
inputval = this.value;
// do some things with it and save them to
changedval = …
// you might use the value property of the input itself
));
$('#foo').on('click', function(e) {
// do something with inputval
});
$('form …').on('any other action') {
// you might want to invalidate the cache:
inputval = changedval;
// so that from now on a click operates with the new value
});
$(function() {
$('#button').on('click', function() {
//use text() not html() here
$('#wtf').text("I don't need to change #input in this case");
});
//fire on blur, that is when user types and presses tab
$('#input').on('blur', function() {
alert("clicked"); //this doesn't fire when you click button
$(this).val($(this).val()+' - changed!');
});
});​
Here's the Fiddle
$('form input').on('change', function(e) {
// don't do the thing if the input is #foo
if ( $(this).attrib('id') == 'foo' ) return;
//do some other things
));
UPDATE
How about this:
$().ready(function() {
$('#button').on('click', function(e) {
$('#wtf').html("I don't need to change #input in this case");
});
$('#input').on('change', function(e) {
// determine id #input is in focus
if ( ! $(this).is(":focus") ) return;
$(this).val($(this).val()+' - changed!');
});
});

Categories

Resources