On submit of a form which submit button was clicked - javascript

A validation() function needs to be called whenever a form is submitted which validates the input and based on that returns true or false. But based on two submit buttons there are two validation() functions. Here is an example
<form name="abc" id="abc" method="post" onsubmit="return validate()">
<button type="submit" id="save">Save</button>
<button type="submit" id="edit">Edit</button>
</form>
<script type = "text/javascript">
document.getElementById("save").onclick = function() {
validateSave();
}
document.getElementById("edit").onclick = function() {
validateEdit();
}
function validateSave(){
//do validation
}
function validateEdit(){
//do validation
}
function validate(){
//return true or false based on the validation
}
</script>
So basically I want to use onsubmit="return validate() weather to navigate to next page or remain in the same page. So how to use the onsubmit="return validate() alongwith the respective validation on basis of the button clicked.
Any leads/hint would be appreciated.
Thanks

Do something like this :
HTML :
<form name="abc" id="abc" method="post">
<button type="submit" id="save" onclick="validate(event)">Save</button>
<button type="submit" id="edit" onclick="validate(event)">Edit</button>
</form>
JS :
function validateSave(){
console.log("save");
return false;
}
function validateEdit(){
console.log("edit");
return false;
}
function validate(event){
event.preventDefault();
event.stopPropagation();
var callerId = event.target.id;
var formElement = document.getElementById("abc");
if (callerId === "Save") {
formElement.onsubmit = validateSave(); // Or other value/function
}
else {
formElement.onsubmit = validateEdit(); // Or other value/function
}
formElement.submit();
}

I found a way by declaring a flag variable inside the javascript section
<form name="abc" id="abc" method="post" onsubmit="return validate()">
<button type="submit" id="save">Save</button>
<button type="submit" id="edit">Edit</button>
</form>
<script type = "text/javascript">
var flag="";
document.getElementById("save").onclick = function() {
flag="Save";
}
document.getElementById("edit").onclick = function() {
flag="Edit";
}
function validateSave(){
//do validation
}
function validateEdit(){
//do validation
}
function validate(){
if(flag == "Save"){
if(validateSave()){
return true;
}
else{
return false;
}
}
if(flag == "Edit"){
if(validateEdit()){
return true;
}
else{
return false;
}
}
}
</script>

Related

How can i submit a fom when their is multiple functions are created , which function to call on evnets like onclick and onsubmit?

<html>
<body>
<form onsubmit="return myFunction()">
<input type="text" id="txt">
<input type="text" id="txt1">
<input type="button" value="click" id="btn">
</form>
</body>
<script>
var a = document.getElementById("txt");
var b = document.getElementById("txt1");
var save = document.getElementById("btn");
//save.addEventListener("click" , myFun);
save.onclick = function(){myFunction()};
//save.addEventListener("click" , myFunction);
function myFunction(){
if((a.value=="") || (b.value=="")){
alert("fill something");
return false;
}else{
alert("all ok");
location.href="sec.html";
return true;
}
//a.addEventListener("keyup" , myFun);
//b.addEventListener("keyup" , myFun);
}
a.addEventListener("keyup" , myKeyFun);
b.addEventListener("keyup" , myKeyFun);
function myKeyFun()
{
if(a.value!==b.value){
alert("mismatched");
return false;
}else{
return true;
}
}
</script>
</html>
i have created many function for different - different validation so now i want to submit the form and redirect to another page when all the cinditons are true.
but here form is getting submitted even when the conditions are not true, i have wrote this code just to understand.
the actual code is quite big so i have wrote this to understand how i would have to call the main function to submit the form when there is multilpe function
Don't mess by making different functions. Do it with conditions as below.
var a = document.getElementById("txt");
var b = document.getElementById("txt1");
var save = document.getElementById("btn");
function myFunction() {
if(a.value == ""){
alert("Please fill Text 1");
}else if(b.value == ""){
alert("Please fill Text 2");
}else if (a.value != b.value){
alert("Text 1 and Text 2 must be same");
}
else{
alert("Successfully submitted");
//redirect to another page code;
}
}
function textTwoFun(){
if(a.value != b.value){
alert('Value missmatched! Text 1 and Text 2 must be same');
}
}
<form>
<input type="text" id="txt" placeholder="Text 1">
<input type="text" id="txt1" onkeyup="textTwoFun()" placeholder="Text 2">
<input type="button" onclick="myFunction()" value="click" id="btn">
</form>

return false not working on form submit in jquery

function SaleProduct() {
var CusId=$('#CusId').val();
$.get('customer-id.php?CusId='+CusId, function(data) {
if(data==0){
alert("Customer Id not valid.")
return false;
}
});
}
<form action="sales-edit-insert.php" method="post" onSubmit="return SaleProduct()">
<input type="text" name="CusId" id="CusId"/>
<!--Some input field here-->
<input type="submit" value="Submit"/>
</form>
return false; or e.preventDefault(); not working on above function when I submit the form. Form is submitted after showing an alert.
Your SaleProduct returns nothing(actually undefined).
You can stop immediate form sending with return false; inside of onsubmit attribute:
<form action="sales-edit-insert.php" method="post" onSubmit="SaleProduct(); return false;">
And later you can submit your form manually:
function SaleProduct() {
var form = ...;
var CusId=$('#CusId').val();
$.get('customer-id.php?CusId='+CusId, function(data) {
if(data==0){
alert("Customer Id not valid.")
return;
}
form.submit();
});
return false; // you can also move this statement to here from attribute
}
Most simple way to get form element is provide it into onsubmit:
<form action="sales-edit-insert.php" method="post" onSubmit="return checkCustomer(this)">
And js:
function checkCustomer(form) {
//code from above
return false;
}
You're using jQuery already so why bother with the onsubmit attribute. Try
<form action="sales-edit-insert.php" method="post" id="sale-product-form">
and
jQuery(function($) {
$('#sale-product-form').on('submit', function(e) {
e.preventDefault()
var form = this;
$.get('customer-id.php', $(form).serialize(), function(data) {
if (data == 0) {
alert('Customer Id not valid.')
} else {
form.submit() // submit normally
}
})
})
})

Javascript: How to disable submit button until all fields are validated?

I have several validation functions that work fine and I want to write an additional validation in simple javascript (no jQuery, etc) for the entire form that disables/enables the Submit button depending on whether the other validation functions return true or false. How do I go about that?
For example, for my main HTML I have:
<form id="form" method="POST">
<label class="form">Field 1</label><input type="text" name="input1" onkeyup="validateInput1(); return false">
<label class="form">Field 2</label><input type="text" name="input2" onkeyup="validateInput2(); return false">
...
<button id="submit" type="submit" value="submit">Submit</button>
</form>
For my script I have:
function validateInput1(){
...
}
function validateInput2(){
...
}
Now I want to write a function with something like:
function validateForm(){
var submitButton = document.getElementById('submit');
submitButton.disabled = true;
/*If all other validation functions like validateInput1() returns true then submitButton.disabled = false*/
}
How do I do this?
Start the button off as disabled. Hook to the onchange event for each of the form inputs, and then have it check the validateForm() function to see if all the forms are valid. After that, if they're all valid, set the submit button to enabled, otherwise set it to disabled.
var inputs = document.querySelectorAll('#form input');
var validateInput1 = function()
{
return document.getElementById('input1').value != '';
}
var validateInput2 = function()
{
return document.getElementById('input2').value != '';
}
var validateForm = function() {
if ( !validateInput1() ) {
return false;
}
if ( !validateInput2() ) {
return false;
}
return true;
}
for ( var i = 0, len = inputs.length; i < len; i++ )
{
var checkValid = function() {
document.getElementById('submit').disabled = !validateForm();
//Is the same as:
/*if ( !validateForm() )
{
document.getElementById('submitButton').disabled = true;
}
else
{
document.getElementById('submitButton').disabled = false;
}*/
}
inputs[i].addEventListener('change', checkValid);
inputs[i].addEventListener('keyup', checkValid);
}
<form id="form" method="POST" onsubmit="alert('Submitted!'); return false">
<label class="form">Field 1</label><input type="text" name="input1" id="input1">
<label class="form">Field 2</label><input type="text" name="input2" id="input2">
<button id="submit" type="submit" value="submit" disabled="disabled">Submit</button>
</form>

How to validiate form onsubmit when form is submitted via a link instead of a button

I've got the following simple test to validate the input on the form when it is submitted by clicking the "submit" link. Unfortunately, it doesn't validate the form.
<form id="testform" action = "?blah" onsubmit="return validateForm()">
<input type="text" name="testinput" >
Submit
</form>
<script>
function validateForm() {
var x = document.forms["testform"]["testinput"].value;
if (x == null || x == "") {
alert("Field must be filled out");
return false;
}
}
</script>
If I replace submitting with a button instead of a link then it validates the form properly. But how can I ensure it validates when I am using a link to submit as in the above example?
Try creating a function that triggers the validation when clicking on the link.
Example:
<form id="testform" action = "?blah" onsubmit="return validateForm()">
<input type="text" name="testinput" >
Submit
</form>
<script>
function validateForm() {
var x = document.forms["testform"]["testinput"].value;
if (x == null || x == "") {
alert("Field must be filled out");
return false;
}
}
function submitForm() {
if (validateForm()) {
document.getElementById('testform').submit();
}
}
</script>
Note: I would highly recommend decoupling your JavaScript from your HTML, but that's outside the scope of your question.
Here comes a jQuery style way of doing it.
<form id="testform" action = "?blah" onsubmit="return validateForm()">
<input type="text" name="testinput" />
Submit
</form>
<script type="text/javascript">
function validateForm() {
if ($.trim($("[name=testinput]").val()) == "") {
alert("Field must be filled out");
return false;
}
}
</script>
This works for me. It takes advantage of a variable and of an assigned method to testform:
<form id="testform" action = "?blah" onsubmit="return formValid">
<input type="text" name="testinput" >
Submit
</form>
<script>
var formValid = false;
document.getElementById('testform').onsubmit = function(){
console.log('submit');
formValid = validateForm();
};
function validateForm() {
var x = document.forms["testform"]["testinput"].value;
if (x == null || x == "") {
alert("Field must be filled out");
return false;
}
}
</script>

Textbox value compare before submitting

I want to let my two textboxes be checked before those get submitted.
like
if textbox1 >= textbox2 submit
else show errorlabel and dont submit.
How can i do this?
Provide your onclick handler's implementation to extract the value of the two text boxes, then parse them as an int.
function submitForm() {
var first = parseInt(document.getElementById("first"), 0);
var second = parseInt(document.getElementById("second"), 0);
if(first >= second) {
// ...
return true;
} else {
var hiddenTextBox = document.getElementById("error");
hiddenTextBox.style.visibility = "visible";
return false;
}
}
This assumes you have two elements with id="first" and id="second" respectively, and a hidden element with id="error"
Try it like,
$('#submitId').on('click',function(){
if $('#textbox1').val() < $('#textbox2').val()){
$('#erroLabel').show(); // showing error label
return false; // to prevent submitting form
}
});
You can make function in javascript,
<script type="text/javascript">
function checkValues()
{
var searchtext1 = document.getElementById("textbox1").value;
if(searchtext1=='')
{
alert('Enter any character');
return false;
}
var searchtext2 = document.getElementById("textbox2").value;
if(searchtext2=='')
{
alert('Enter any character');
return false;
}
}
</script>
and then in html form
<form method='GET' onSubmit="return checkValues();">
<input type="text" id= "textbox1" name="textbox1" class='textbox' >
<input type="text" id= "textbox2" name="textbox2" class='textbox' >
<input type="submit" id='submit' value="Search" class ='button' >
</form>

Categories

Resources