How to disable the "Save Changes" button until changes are made? - javascript

I'm using an editing mechanism similar to the example Grid Batch Editing, but my buttons look at lot different.
Because of this difference it would make a lot of sense to have the save changes and cancel button disabled changes are made and then when you press the save or cancel button they should disable again. How do I achieve this?

Managed to answer my own question here.
Function for changing the buttons state:
function changeSaveAndCancelButtonState(enable) {
$(".k-grid-save-changes").kendoButton({ enable: false })
.data("kendoButton").enable(enable);
$(".k-grid-cancel-changes").kendoButton({ enable: false })
.data("kendoButton").enable(enable);
}
To enable buttons when you edit data (regular cell):
#(Html.Kendo().Grid<DeuarTestValue>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(c => c.Sample).Editable("enabledRegularEdit");
})
// Insert code for data source etc etc
);
function enabledRegularEdit() {
changeSaveAndCancelButtonState(true);
// return true to indicate that this the cell can be edited
return true;
}
To disable the buttons by default and on click:
function disableSaveAndCancelButtonState() {
changeSaveAndCancelButtonState(false);
}
// Disable themselves on-click
var but = $(".k-grid-save-changes").kendoButton({ click: disableSaveAndCancelButtonState });
var but = $(".k-grid-cancel-changes").kendoButton({ click: disableSaveAndCancelButtonState });
// And Disable them by default.
changeSaveAndCancelButtonState(false);
Note: This doesn't take into consideration whether the cell was actually edited, simply that the cell was taken into edit mode. If anybody knows how to make it work only when edits are properly made?
Since the picture in the post has check boxes, they need to be handled a little bit differently because they aren't edited via the standard Editable function.
To enable buttons when you edit data (checkbox's):
columns.Bound(c => c.Approved)
.ClientTemplate("<input type='checkbox' #= Approved ? checked='checked' : '' # class='Approvedchkbx'/>")
.Editable("disableEdit");
function disableEdit() {
return false;
}
$("#grid .k-grid-content").on("change", ".Approvedchkbx", function (e) {
var grid = $("#grid").data("kendoGrid"),
dataItem = grid.dataItem($(e.target).closest("tr"));
changeSaveAndCancelButtonState(true);
dataItem.set("Approved", this.checked);
});

You can disable the button right after its click and make sure they get enabled back on when your job is done.
$('#your-button').on('click', function (e) {
e.preventDefault();
$(this).prop('disabled', true);
//Do your work
//Once everything is done
$(this).prop('disabled', false);
})

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;
}
}

Run code that decides if checkbox/radio will be checked before actually checking anything (javascript)

I'm building a cart app in Javascript and jQuery that needs to run some logic whenever a product is clicked. The clicked elements are radio buttons and checkboxes and the code will check if the right conditions are met for adding the product to the cart.
My initial way of trying to do this was to run preventDefault() at the start of my function, run some logic that decides if it's ok to add the item, and if so, add it to the cart and check the input element.
Looks sort of like this:
$(document).on("click","[data-item]", function(event) {
cart.updateCart(this, event);
});
cart.updateCart = function(target, event) {
if (event) {
event.preventDefault();
}
// pseudo code...
if (conditionIsMet === true) {
cart.addItem(target);
}
}
cart.addItem = function(item) {
products.push(item);
var element = $('[value=' + item.key + ']');
element.prop('checked', true);
};
My problem is that it seems that I can't use element.prop('checked', true); in my addItem function, since preventDefault stops that.
Can I get around this someway or what route should I go to get my wanted functionality? I really wan't to stop the form elements from getting checked at all and only check or uncheck through my app instead.
It seems that it's not possible to set the checked property of a checkbox right after preventDefault was called on it. Try wrapping your prop call with setTimeout, which will make sure that the update of the checked property occurs in another turn of the event loop:
$("#cb").on("click", function(event) {
updateCart(this, event);
});
const updateCart = function(target, event) {
if (event) {
event.preventDefault();
}
// pseudo code...
if (true === true) {
addItem(target);
}
}
const addItem = function(item) {
setTimeout(function() {
$('#cb').prop('checked', true);
})
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb">

How to prevent multiple code execution on checkbox click in jQuery?

On my page I have a checkboxes like this:
<input id="check0" type="checkbox">
Each time user check or uncheck it I want to execute some jQuery code. Here's sample of this code:
$("input[type=checkbox]").click(function () {
if ($(this).is(':checked')) {
// Calculate something here
}
else {
// Or calculate something here
}
});
Here's the problem: if user will click on checkbox multiple time really quick, some of the code will be executed multiple times, because it will trigger click function every time, but browser will not change 'check' status that quick!
How to prevent this?
I thought to put something like:
$("input[type=checkbox]").click(function () {
if ($(this).is(':checked')) {
// Disable checkbox
$(this).disabled = true;
// Calculate something here
// Enable it back
$(this).disabled = false;
}
else {
// Or calculate something here
}
});
How can I make my code to execute exact in this sequence? Disable > then execute code > then enable back?
Thanks
You should use on change, not on click. Then check the prop checked. If checked, run code. If you want to disable, use attr.
Try this...
$("#check0").on("change", function () {
if($(this).prop("checked") == true){
alert("hey now");
$(this).attr("disabled","disabled");
} else {
//nothing
}
});
http://jsfiddle.net/Eddieflux/z3xfcmgk/

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

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

Categories

Resources