Reputation: 5954
I have an html form which has a couple of text boxes and a submit button. I would like to check if the textbox has changed value -- if so, submit it to database, else just redirect to different page.
I was trying the following code. I keep getting the text changed alert even when the text is not changed. I am not sure what is wrong here?
Here is the code that I have tried:
http://jsfiddle.net/6bSX6/828/
And my html form.
<form action="" method="POST" name="myform" id="container">
<input type="text" id="name1" name="name1" value=""
onkeypress='validate1(event)'
onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
onblur="if (this.value == '') {this.className = 'hint'; this.value = '';}"
size="25" maxlength="30"/>
<input type="text" id="number1" name="number1" value=""
onkeypress='validate(event)'
onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
onblur="if (this.value == '') {this.className = 'hint'; this.value = '';}"
size="20" maxlength="10"/>
<input type="submit" value="Submit" name="submit" id="submit" class="button1" />
</form>
<script>
function validate(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate1(evt){
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[a-zA-Z]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
Upvotes: 0
Views: 3261
Reputation: 3888
I think what you want to do is keep track of if any of the textboxes have changed. You can do this using $elem.data
. Of course, if you have only one form element, you could just use a variable, since we're only storing one thing anyway.
Code:
// We keep track of the form to check if it changes
// Initially, none of the forms have changed
$("form").data("changed", false);
// When it changes, set "changed" to true
$("form").on("change", function() {
$(this).data("changed", true);
});
$('form').on('submit', function () {
if ($(this).data("changed")) {
alert("Something changed!");
// Reset variable
$(this).data("changed", false);
} else {
alert("Nothing changed!");
}
// Do whatever you want here
// You don't have to prevent submission
return false;
});
Side note: JSFiddle has a "scripts" panel dedicated to JavaScript. Don't put your script in the HTML panel. Updated fiddle: http://jsfiddle.net/prankol57/xxf08dbz/
Upvotes: 1