Detecting if form has changed, script not working - javascript

I am trying to use the following script to detect if any fields in my form have changed (edit: detect if the values of my form fields have changed), and alert the user if so. Otherwise, another js box is displayed.
It's not detecting any changes though, and the confirm box is never shown. What am I doing wrong?
$('#eventMedia').click(function() {
var form_changed = false;
$('#tribe-events > form').on('keyup change', 'input, select, textarea', function(){
form_changed = true;
});
if (form_changed == true) {
confirm('You have unsaved changes! Click Cancel to save your changes before continuing.');
} else {
$('#eventMediaBox').show();
$('#blackFade').show();
}
});

You're starting to register keyup and change events only once the #eventMedia button is clicked which is probably not the desired order of things.
instead:
// Set the boolean flag variable first
var form_changed = false;
// On `input change` events - set flag to truthy
$('#tribe-events > form').on('input change', 'input, select, textarea', function(){
form_changed = true;
});
// Showtime!
$('#eventMedia').click(function() {
if (form_changed) {
alert('You have unsaved changes! Save your changes before continuing.');
} else {
$('#eventMediaBox, #blackFade').show();
}
});
Notice that the "input" event (in .on('input change') will also cover the cases where the user pastes content using mouse etc...
Also, don't forget to reset sometimes your form_changed back to false in your code...
Now thinking back to your UI... I have a question. "Why?". Yes, why show a "SAVE" or whatever #eventMedia does if the user did not changed anything in the form? I mean if a user did any changes than there's no reason to do anything - right?
This should suffice I think:
> button is disabled="true"
> (User makes changes?) on `input change` make enabled.

Related

Reading an HTML input field entered without a final Return

I have an input element in this jsfiddle: http://jsfiddle.net/stevea/DLe3a/9. If I enter Return after putting something in the field I trigger the change handler and pick up and display the value fine:
$(function() {
$('input#fname').change(function(e) {
$('div#firstName').append(this.value);
});
But what if the user forgets to hit return and closes down the page? I want to come back, in that case, when I sense the page shutting down, and pull out what was entered into the Input field without a Return.
Can I do that? In the jsfiddle I have a button and its handler. Assuming the button click is shutting down the page, how would I respond to the button click to get the value sitting in the input field?
Thanks
Try this sir
$(function() {
$("#fname").change(function(e) {
$("#firstName").append(this.value)
});
$("#getInput").click(function (e) {
});
});
To detect if the page is closing, use the .unload() event
$(window).unload(function() {
var input = $('#fname').val();
});
I believe that you want to do some code when the window is pre-closed.
Here is some sample code: jsDiddle
$('#fname').change(function () {
$('#firstName').append(this.value);
});
window.onbeforeunload = function (e) {
var e = e || window.event;
// get input #fname
$('#firstName').append($('#fname').val());
// do something you want before the window closes
// show confirm message (optional) - if you don't want show message, return '';
//IE & Firefox
if (e) {
e.returnValue = 'You have some unfilled inputs!';
}
// For Safari
return 'You have some unfilled inputs!';
};
The problem isn't detecting a page closing down. The problem is to capture an Input field's content when something external happens before the user enters Return. But after playing around with it more, at this jsfiddle - http://jsfiddle.net/stevea/bT54M/3/ - it turns out that there really is no problem. If you're in the middle of entering text into an Input field and you do something external, like hitting the Get Input button in the jsfiddle above, the change event for the Input is triggered automatically and this.value is what you've entered so far. So the bottom line is that you don't need to hit Return when you're done. Just about anything you do outside of the Input (probably anything that blurs the Input focus) triggers the Input change event.
$(function() {
$('input#fname').change(function(e) {
debugger;
$('div#firstName').append(this.value);
});
$('#getInput').click(function() {
debugger;
$('div#firstName').append(this.value);
});
});

Checking if an ASP page is dirty before asking user if they want to leave

I have a ASP.NET form and it has a bunch of user inputs, text boxes, checkboxes, etc. I need to be able to check if the user has made an edit on the form without saving and if so prompt then beforeunload.
I have a dirty flag that set once the user edits one of the text boxes. If they save the data on the form then I reset the flag. Therefore the flag should only ever be set when the user edits but has not saved.
I then use this flag to decide whether or not to prompt the user “Are you sure you want to leave this page?”
Code snippet:
var _isDirty = false;
$(function () {
try {
$("#MainContent_txtSometextBox").change(function () {
_isDirty = true;
});
} catch (e) { }
});
The problem is I don’t want to have to set this on every control. Is it possible to set it at a page level? I don’t think it will be that easy as we also have custom user controls on the page.
You could pass a different selector
$("input, select, textarea").change(function () {
_isDirty = true;
});
you may extend this as needed.
If you need to restrict it, wrap it in a div, then find.
$("#myForm").find("input, select, textarea").change(function () {
_isDirty = true;
});
You can use jquery's input selector to target all input, textarea, select and button elements. For button you would need an on click event and for textboxes and areas, the dirty flag is triggered on loss of focus.
Demo
$('#body :input'​​​​​​​​).change(function () {
_isDirty = true;
});

jQuery bind to keyup only, not focus

This seems like a simple thing but google hasn't turned up anything for me:
How can I bind to a text / value change event only, excluding an input gaining focus? Ie, given the following:
$(function(){
$('input#target').on('keyup', function(){
alert('Typed something in the input.');
});
});
...the alert would be triggered when the user tabs in and out of an element, whether they actually input text or not. How can you allow a user to keyboard navigate through the form without triggering the event unless they input/change the text in the text field?
Note: I'm showing a simplified version of a script, the reason for not using the change event is that in my real code I have a delay timer so that the event happens after the user stops typing for a second, without them having to change focus to trigger the event.
Store the value, and on any key event check if it's changed, like so:
$(function(){
$('input#target').on('keyup', function(){
if ($(this).data('val')!=this.value) {
alert('Typed something in the input.');
}
$(this).data('val', this.value);
});
});​
FIDDLE
Simply use the .change event.
Update: If you want live change notifications then do you have to go through the keyup event, which means that you need to program your handler to ignore those keys that will not result in the value being modified.
You can implement this with a whitelist of key codes that are ignored, but it could get ugly: pressing Del results in the value being changed, unless the cursor is positioned at the end of the input in which case it does not, unless there happens to be a selected range in the input in which case it does.
Another way which I personally find more sane if not as "pure" is to program your handler to remember the old value of the element and only react if it has changed.
$(function() {
// for each input element we are interested in
$("input").each(function () {
// set a property on the element to remember the old value,
// which is initially unknown
this.oldValue = null;
}).focus(function() {
// this condition is true just once, at the time we
// initialize oldValue to start tracking changes
if (this.oldValue === null) {
this.oldValue = this.value;
}
}).keyup(function() {
// if no change, nothing to do
if (this.oldValue == this.value) {
return;
}
// update the cached old value and do your stuff
this.oldValue = this.value;
alert("value changed on " + this.className);
});
});​
If you do not want to set properties directly on the DOM element (really, there's nothing wrong with it) then you could substitute $(this).data("oldValue") for this.oldValue whenever it appears. This will technically have the drawback of making the code slower, but I don't believe anyone will notice.
See it in action.
This will do it, set a custom attribute and check against that:
$('input').focus(function(){
$(this).attr('originalvalue',$(this).val());
});
$('input').on('keyup',function(){
if($(this).val()===$(this).attr('originalvalue')) return;
alert('he must\'ve typed something.');
});
Be wary of events firing multiple times.
Here is another version that plainly tests if the input field is empty.
If the input is empty then the action is not performed.
$(function(){
$(selector).on('keyup', function(){
if ($(this).val()!='') {
alert('char was entered');
}
})
});

How to disable tab key globally except for all forms in a page with JavaScript?

I'm making a single page app that is launching next week, for a pretty huge client, and going live for a pretty big event and well, there's still a ton to finish before then.
There's 100+ 'pages' which are all loaded within a single 700px x 600px window, and I had learned not long ago you could tab through the page/sections, which in-turn would break the app because it would bring focus to hidden off-screen elements, so for this reason, I disabled the tab key for the entire app.
But now there are a couple places where we have a form with a handful of input fields which you are not able to tab through as you fill in the form. It's a pain in the ass.
I need to make it so you can tab through the form fields, but only the form fields. I have the tabindex attribute set for the form, and have tried to make inputs tab enabled but was not able to make it work without causing the app to jump to hidden sections.
Here's the function I need to change so it will disable tab key except from input to input fields in a form.
window.onkeydown = function(e) {
if (e.keyCode === tab) {
return false;
}
}
I tried to do this, which obv didnt work lol
$('input').keydown(function(e) {
if (e.keyCode === tab) {
return true;
}
});
Thanks :)
I made some fixes to what #Joseph posted for an answer to this that handle being able to shift + tab through inputs of a form so you can reverse direction. It was a very annoying thing for me before when I first had to find a way to do this, and didn't have time to waste anymore trying to find a complete solution for this until now. Here it is.
$(function() {
// gather all inputs of selected types
var inputs = $('input, textarea, select, button'), inputTo;
// bind on keydown
inputs.on('keydown', function(e) {
// if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
// prevent default tab action
e.preventDefault();
if (e.shiftKey) {
// get previous input based on the current input
inputTo = inputs.get(inputs.index(this) - 1);
} else {
// get next input based on the current input
inputTo = inputs.get(inputs.index(this) + 1);
}
// move focus to inputTo, otherwise focus first input
if (inputTo) {
inputTo.focus();
} else {
inputs[0].focus();
}
}
});
});
Demo of it working http://jsfiddle.net/jaredwilli/JdJPs/
Have you tried setting tabIndex="-1" on all elements that you don't want to be able to tab to? I think that's a much better solution.
Otherwise, within your key handler function test event.target (or event.srcElement in IE) to see if the event originated with a form element. You seem to be using jQuery, so you could assign an "allowTab" class just to the fields in your form and then do this:
$(document).keydown(function(e) {
if (!$(e.target).hasClass("allowTab"))
return false;
});
Or
if (e.target.tagName !== "input")
// etc
what we do is to determine what input is next in line and skip to it!:
http://jsfiddle.net/qXDvd/
$(document).ready(function() {
//gather all inputs of selected types
var inputs = $('input, textarea, select, button');
//bind on keydown
inputs.on('keydown', function(e) {
//if we pressed the tab
if (e.keyCode == 9 || e.which == 9) {
//prevent default tab action
e.preventDefault();
//get next input based on the current input we left off
var nextInput = inputs.get(inputs.index(this) + 1);
//if we have a next input, go to it. or go back
if (nextInput) {
nextInput.focus();
}
else{
inputs[0].focus();
}
}
});
});​
may need some optimization but it works. this was originally meant to skip non-form elements. you can add selectors not to skip if you like. additionally, you can add logic for the Shift+Tab behavior (maybe before the tab logic)
obviously, it will still go through some elements according to how they appear in the source. however, why not just remove those hidden elements from the DOM but still keep track of them using the methods found in this question. that way, you won't have the pain of having to cycle back and forth through off-screen elements.

Detecting form changes using jQuery when the form changes themselves were triggered by JS

I have a list of radio buttons that I can toggle "yes" or "no" to using Javascript.
$(document).ready(function(){
$('#select-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', true);
$('input[type="radio"]', this).eq(1).attr('checked', false);
});
});
$('#deselect-all').click(function(){
$('#notifications .notif-radio').each(function(){
$('input[type="radio"]', this).eq(0).attr('checked', false);
$('input[type="radio"]', this).eq(1).attr('checked', true);
});
});
});
this works just fine. Now I have a separate piece of code that detects when a user has changed something, and asks them if they want to leave the page.
var stay_on_page;
window.onbeforeunload = confirm_exit;
$('.container form input[TYPE="SUBMIT"]').click(function(){
stay_on_page = false;
});
$('#wrapper #content .container.edit-user form').change(function(){
stay_on_page = true;
});
function confirm_exit()
{
if(stay_on_page){ return "Are you sure you want to navigate away without saving changes?"; }
}
The problem is that if the user uses the first piece of functionality to toggle all radio buttons one way or another. The JS detecting form changes doesn't see that the form was changed. I have tried using .live, but to no avail. Anyone have any ideas?
I do something similar to this by adding change() (or whatever's appropriate, click() in your case I suppose) event handlers which set either a visible or hidden field value, then check that value as part of your onbeforeunload function.
So, my on before unload looks like:
window.onbeforeunload = function () {
if ($('#dirtymark').length) {
return "You have unsaved changes.";
}
};
And, or course, dirtymark is added to the page (a red asterisk near the Save button), when the page becomes dirty.

Categories