Check if fields are edited or not? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have 7 textfields put inside a table. These textfields data i get from server when user presses submit. After filling textfield with fetched data, user submits that data to the server from a new button submit.
If the user submits the data as it is, I need to show an error message that 'at least one field must be edited'. If it edits at least one field and then submits I will update data on the server.
How can I check whether user has changed a field or not?
Problem is I will need to store data fetched for comparison, which I will have to do it in global variable in my JavaScript (which is not a good practice).

You can create an hidden input (like say #lastr2d2) named haschange like
<input type="hidden" name="haschange" id="haschange" value="0" />
and add an jquery or javascript function witch change the value of haschange from 0 to 1
when happens an event onChange on each textfields. for example you can create a function like bellow:
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
$("#haschange").val(1);
});
});
Finally when you click the button of finally submit then you can check if haschange value is 0 or 1
--- Edit ---
If you want check for original changing (see #antindexer comments) then you can use below code
$(document).ready(function(){
//Check this link
$("#textfields1").change(function(){
var defaultValue = document.getElementById('textfields1').defaultValue;
var currentValue = document.getElementById('textfields1').value;
if( currentValue != currentValue ) {
$("#haschange").val(1);
}
});
});

You could do something like this:
Add data attributes to your input fields. Replace "<%= serverValue %>" with whatever syntax your server code uses.
<form id="form">
<table>
<tr>
<td><input type="text" value="<%= serverValue %>" data-original-value="<%= serverValue %>" /></td>
</tr>
</table>
<input type="submit" value="submit" />
</form>
And then place a script tag on the page with something like this (assuming you're using jQuery):
<script>
$(function () {
var $form = $('#form');
$form.on('submit', function (e) {
$(form).find('[data-original-value]').each(function (index, el) {
var $el = $(el);
if ($el.val() === $el.attr('data-original-value]')) {
e.preventDefault();
console.log('please edit at least one value');
}
});
});
});
</script>
Here is a JSFiddle - http://jsfiddle.net/X4S4y/1/

You can use attr data-value ( or any name you want ) to keep your original value
Example: ( Assume you use PHP )
<input type="text" value="<?php echo $value_1?>" data-value="<?php echo $value_1?>" class="input_text">
<input type="text" value="<?php echo $value_2?>" data-value="<?php echo $value_2?>" class="input_text">
<input type="text" value="<?php echo $value_3?>" data-value="<?php echo $value_3?>" class="input_text">
<input type="text" value="<?php echo $value_4?>" data-value="<?php echo $value_4?>" class="input_text">
In Jquery you can check if there are any change in input text then submit form
Example:
$(document).ready(function(){
$("form").submit(function(){
var is_changed = false;
$(".input_text").each(function(){
if ( $(this).val() == $(this).attr("data-value") {
return false;
} else {
is_changed = true;
}
});
if( is_change == true ) {
alert("Please change at least one input");
return false;
}
});
})

Related

Validate forms by function

I have strange problem. I'm trying validate my form by function in JavaScript in this way:
<input type="submit" onclick="return validate();" name="valideButton" value="Something" />
And the validate function:
function validate() {
alert("Some alert!");
var someValidateInputName = document.forms["formName"]["someValidateInputName"].value;
alert(someValidateInputName);
if (someValidateInputName == "0") {
alert("Wrong value: " + document.forms["formName"]["someValidateInputName"].value);
return false;
}
return true;
}
When I use alert(document.forms["formName"]["someValidateInputName"].value) inside my form there's everything allright, but when I'm calling function validate(); I have an alert with Some alert, but I don't have alert with someValidateInputName. It seems like a function return true when I try to check someValidateInputName and I don't know why...
The script with function is in the same file above the html code.
I validate form on the other my pages in the same way and there was no problem.
alert("Some alert!); should be alert("Some alert!"); the way it is now it tries to alert everything untill the next " meaning it tries to alert half your function.
Ok, I solve the problem.
It was a stupid mistake... and I think that nobody could not help me without more information.
I skip this, because I forget that this can be so important.
My form was closed in foreach loop and many input has name="someValidateInputName", so my outside function doesn't know which input I want to validate. I don't look at the problem in this way, because for me it was strange that function always return true when only I try read the input value.
If somebody forget about this like me, here is the solve:
We need to adding an indexes to name of form and name of input like this:
<input type="submit" onclick="return validate();" name="valideButton <?php echo $j; ?>" value="Something" />
In the same way we have to add index to name of form.
And I send my Index to read the right value via $_POST. I increment $j too.
<input type="hidden" value="<?php echo $j++; ?>" name="Index" />
At the end my validation() look like this:
function validate(index) {
alert("Some alert!");
var someValidateInputName = document.forms["formName"+index]["someValidateInputName"+index].value;
alert(someValidateInputName);
if (someValidateInputName == "0") {
alert("Wrong value: " + document.forms["formName"+index]["someValidateInputName"+index].value);
return false;
}
return true;
}
If you could place the form out of the foreach you don't be need to an index to form.
Thanks for the trying help!
Cheers

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

Html5 required validation checkbox

I made a input checkbox that contains array values. so it generates plenty of rows in a table.
But it needs for me to check it all to submit.
It doesn't allow me to check only few not all.
<form>
<table>
<td>
<input required="required" type="checkbox" name="id[]" id="id" value="<?php echo $result2["id"]; ?>"/>
</td>
<input type="submit" name="submit" value="submit"/>
</table>
</form>
How can i make the required field able to check atleast one and able to submit even if not all are checked?
I dont know if I understand you,
but maybee you need something like this:
Online demo
Main part with notes:
$('#frm').bind('submit', function(e) { // set this function for submit for your formular
validForm = true; // default value is that form is correct, you can chcange it as you wish
var n = $( "input:checked" ).length; // count of checked inputs detected by jQuery
if (n != 1) { validForm=false; } // only if you checked 1 checkbox, form is evaluated as valid
if (!validForm) { // if result of validation is: invalid
e.preventDefault(); // stop processing form and disable submitting
}
else {
$('#echo').html("OK, submited"); // ok, submit form
}
});
You can use any number of comboboxes under any tag and get count of selected by jQuery, then use any rule for validate form.

jQuery (or just JS) choosing from multiple form submit buttons in onSubmit function

I've got a form that has multiple submit buttons. One for changing data in a database, one for adding, and one for deleting. It looks like this:
<form action="addform.php" method="post" id="addform" onSubmit="return validate(this)">
<select name="listings" id="listings" size="1" onChange="javascript:updateForm()">
<!-- Here I have a php code that produces the listing menu based on a database query-->
</select>
<br />
Price: <input type="text" name="price" id="price" value="0"/><br />
Remarks: <textarea name="remarks" wrap="soft" id="remarks"></textarea><br />
<input type="submit" value="Update Database Listing" name="upbtn" id="upbtn" disabled="disabled"/>
<input type="submit" value="Delete Database Listing" name="delbtn" id="delbtn" disabled="disabled"/>
<br />
<input type="submit" value="Add Listing to Database" name="dbbtn" id="dbbtn"/>
<input type="button" value="Update Craigslist Output" name="clbtn" id="clbtn" onClick="javascript:updatePreview();"/>
</form>
There are actually more elements in the form, but that doesn't matter. What I want to know is, for my validation method, how can I check which submit button has been clicked?
I want it to do the following:
function validate(form){
if (the 'add new listing' or 'update listing' button was clicked'){
var valid = "Are you sure the following information is correct?" + '\\n';
valid += "\\nPrice: $";
valid += form.price.value;
valid += "\\nRemarks: ";
valid += form.remarks.value;
return confirm(valid);}
else {
return confirm("are you sure you want to delete that listing");
}
}
I assume there must be some way to do this relatively easily?
Why don't you set a global variable specifying which button was last clicked? Then you can check this variable in your validate method. Something like:
var clicked;
$("#upbtn").click(function() {clicked = 'update'});
// $("#delbtn").click(function() {clicked = 'delete'});
// ...
function validate(form) {
switch(clicked) {
case 'update':
break;
// more cases here ...
}
}
You can, for example, attach a click event to every submit button that will save a pointer to it in a variable or mark it with a specific attribute / class (it that case you will have to remove that marker from all other submit buttons in the event handler) and then in the submit callback you will know which one was clicked
I think it's easier to just use a click event on each button and handle it individually.
$(function() {
$('input[name=someName]').click(someFunc);
});
function someFunc() {
// Your validation code here
// return false if you want to stop the form submission
}
You could have a hidden field on a form and set the value of that field on clicking the button and then pick it up in your validation routine. You can use jquery to achieve this, let me know if you require an example.
You can use ajax submission with jQuery, you can try something like this:
$('form#addform input[type="submit"]').on('click',function(e){
e.preventDefault();
var current = $(this); //You got here the current clicked button
var form = current.parents('form');
$.ajax({
url:form.attr('action'),
type:form.attr('method'),
data:form.serialize(),
success:function(resp){
//Do crazy stuff here
}
});
});

jQuery/Javascript function to clear all the fields of a form [duplicate]

This question already has answers here:
Resetting a multi-stage form with jQuery
(31 answers)
Closed 9 years ago.
I am looking for a jQuery function that will clear all the fields of a form after having submitted the form.
I do not have any HTML code to show, I need something generic.
Can you help?
Thanks!
Note: this answer is relevant to resetting form fields, not clearing fields - see update.
You can use JavaScript's native reset() method to reset the entire form to its default state.
Example provided by Ryan:
$('#myForm')[0].reset();
Note: This may not reset certain fields, such as type="hidden".
UPDATE
As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger():
$('#myForm').trigger("reset");
UPDATE
If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.
To reset form (but not clear the form) just trigger reset event:
$('#form').trigger("reset");
To clear a form see other answers.
Something similar to $("#formId").reset() will not clear form items that have had their defaults set to something other than "". One way this can happen is a previous form submission: once a form has been submitted reset() would "reset" form values to those previously submitted which will likely not be "".
One option to clear all forms on the page, is to call a function such as the following, executing it simply as clearForms():
function clearForms()
{
$(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(':checkbox, :radio').prop('checked', false);
}
If you want to reset a specific form, then modify the function as follows, and call it as clearForm($("#formId")):
function clearForm($form)
{
$form.find(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$form.find(':checkbox, :radio').prop('checked', false);
}
When I originally came to this page I needed a solution that takes into account form defaults being changed and is still able to clear all input items.
Note that this will not clear placeholder text.
Set the val to ""
function clear_form_elements(ele) {
$(ele).find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
<input onclick="clear_form_elements(this.form)" type="button" value="Clear All" />
<input onclick="clear_form_elements('#example_1')" type="button" value="Clear Section 1" />
<input onclick="clear_form_elements('#example_2')" type="button" value="Clear Section 2" />
<input onclick="clear_form_elements('#example_3')" type="button" value="Clear Section 3" />
You could also try something like this:
function clearForm(form) {
// iterate over all of the inputs for the form
// element that was passed in
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
More info here and here
<form id="form" method="post" action="action.php">
<input type="text" class="removeLater" name="name" /> Username<br/>
<input type="text" class="removeLater" name="pass" /> Password<br/>
<input type="text" class="removeLater" name="pass2" /> Password again<br/>
</form>
<script>
$(function(){
$("form").submit(function(e){
//do anything you want
//& remove values
$(".removeLater").val('');
}
});
</script>
You can simply use the reset button type.
<input type="text" />
<input type="reset" />
jsfiddle
Edit: Remember that, the reset button, reset the form for the original values, so, if the field has some value set on the field <input type="text" value="Name" /> after press reset the field will reset the value inserted by user and come back with the word "name" in this example.
Reference: http://api.jquery.com/reset-selector/
I use following solution:
1) Setup Jquery Validation Plugin
2) Then:
$('your form's selector').resetForm();
function reset_form() {
$('#ID_OF_FORM').each (function(){
this.reset();
});
}
the trigger idea was smart, however I wanted to do it the jQuery way, so here is a small function which will allow you to keep chaining.
$.fn.resetForm = function() {
return this.each(function(){
this.reset();
});
}
Then just call it something like this
$('#divwithformin form').resetForm();
or
$('form').resetForm();
and of course you can still use it in the chain
$('form.register').resetForm().find('input[type="submit"]').attr('disabled','disabled')
Would something like work?
JQuery Clear Form on close
HTML
<form id="contactform"></form>
JavaScript
var $contactform = $('#contactform')
$($contactform).find("input[type=text] , textarea ").each(function(){
$(this).val('');
});
Simple and short function to clear all fields

Categories