Checkbox validation not working - javascript

I have some javascript that is supposed to validate a checkbox (making it mandatory) but my form regardless of whether it is checked or not just submits, here is my code :
<script>
function validateCheckBoxes(theForm) {
if (!theForm.declare.checked) {
alert ('You must tick the checkbox to confirm the declaration');
return false;
} else {
return true;
}
}
</script>
<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">
<input type="checkbox" name="declare" id="declare">
<input type="submit" name="submit" id="submit" value="submit">
</form>
Any ideas on why it isnt working?

<script type="text/javascript">
function validateCheckBoxes(theForm)
{
if (!theForm.declare.checked)
{
alert ('You must tick the checkbox to confirm the declaration');
return false;
} else {
return true;
}
}
</script>
<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">
<input type="checkbox" name="declare" id="declare">
</form>
As #shin mentioned, you need to specify the object of the form during the function call.
theForm.declare.checked returns true or false there is no need to check the value with == operator. Just use it directly (User ! depending on need - to negate the result)

change your function call like
return validateCheckBoxes(this);
Eg:
<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">
Because theForm should refer an object

<script>
function validateCheckBoxes()
{
if (document.getElementById('declare').checked == false)
{
alert ('You must tick the checkbox to confirm the declaration');
return false;
} else {
return true;
}
}
</script>
<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes();">
<input type="checkbox" name="declare" id="declare" />
<input type="submit" name="submit" value="submit" />
</form>

Here is a what I tried and worked for me
<script type='text/javascript'>
function validateCheckBoxes()
{
if (document.forms[0].declare.checked == false)
{
alert ('You must tick the checkbox to confirm the declaration');
return false;
} else {
return true;
}
}
</script>
<form name="form" method="POST" action="yourURL/search" id="eoi" onsubmit="return validateCheckBoxes();">
<input type="checkbox" name="declare" id="declare"/>
</form>
I don't think you need to pass the reference of the form object to the function.

Related

How to avoid onsubmit="return validateForm()" to submit the form when the validateForm() have a bug?

How to avoid onsubmit="return validateForm()" to submit the form, when the validateForm() have a bug?
<form action="index.php" method="post" name="eform" onsubmit="return validateForm();">
<input type="text" name="text" Maxlength="10000" />
<input name="" type="submit" value="submit"/>
</form>
<script>
function validateForm() {
if (dosomething) {
return true;
} else {
return false;
}
}
</script>
But when function validateForm() have some code error, such as...
function validateForm() {
ifffffffffffff(dosomerthing) { // Creates an error
return true;
} else {
return false;
}
}
The form is submitted automatically...
It displays 1 sec in Chrome console, how can I avoid this???
Thank you very much!
Update:
var from = document.getElementById('form');
form.addEventListener('submit', validateForm);
function validateForm(event) {
try {
error
} catch(err) {
console.log(err);
event.preventDefault();
}
}
<form action="index.php" method="post" name="eform" id="form">
<input type="text" name="text" Maxlength="10000" />
<input name="" type="submit" value="submit"/>
</form>
If I understand your question correctly you want to execute or stop executing the form method with an condition?
if so take a look, it may help you to get going.
function validateForm() {
var val ="errrrr"; // place your error here.
if(val == "err")
{
alert("submit form");
}
else
{
alert("don't submit the form"); //do what you want to do.
}
}
<form action="index.php" method="post" name="eform" onsubmit="return validateForm();">
<input type="text" name="text" Maxlength="10000" />
<input name="" type="submit" value="submit"/>
</form>

JS setCustomValidity not work at first time

I want to make a custom validity message to my form, and there are some problem.
The validity message will show after click two times.
and if I don't input correct word "text" first time, then it will not submit anymore.
what's the problem in my code.
JS:
function a(){
jQuery("#text")[0].setCustomValidity("");
if (jQuery("#text").val() == "text"){
return confirm('sure?');
}
jQuery("#text")[0].setCustomValidity("Incorrect");
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/" method="post" onsubmit="return a();">
<input type='text' id="text"/>
<input type="submit" value="submit"/>
</form>
Please try to check below solution:
$(document).on('click',"#submit_btn", function()
{
if($("#text").val() === "text")
return confirm('sure?');
else
$("#text")[0].setCustomValidity("Incorrect");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/" method="post">
<input type='text' id="text"/>
<input type="submit" value="submit" id="submit_btn"/>
</form>

onclick="validateForm();return false"?

I came across some code involving a submit button, whose onclick attribute is: onclick="validateForm();return false". For example:
<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
}
else
document.myForm.submit();
}
</script>
</head>
<body>
<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" method="post" target="_blank">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit" onclick="validateForm();return false">
</form>
</body>
</html>
I don't see any difference even if I remove return false in the above example. The return false does not stop the form from submitting as long as the text field is entered. So, what's the purpose of using "return false" immediately after the form is submitted by document.myForm.submit()?
It’s for when the form isn’t submitted by document.myForm.submit(), i.e. in the error case. A better way to write it would probably be to have validateForm control the return value:
function validateForm() {
var name = document.forms["myForm"]["fname"].value;
if (name.trim() == "") {
document.getElementById("demo").innerHTML = "Name must be filled out!";
// Error; cancel the form submission
return false;
}
// Just let the browser continue submitting; no need to .submit()
return true;
}
and
<form name="myForm" action="formHandler.jsp" method="post" target="_blank"
onsubmit="return validateForm()">
Name: <input type="text" name="fname"> <br>
<input type="submit" value="Submit">
</form>
Check Working example :
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

how to validate array input field using javascript

How to validate array input field?Please help me to solve this issue.
<form action="" method="post" name="frmPayPal1" id="frmPayPal1" onsubmit="return validateForm()"/>
<input type='text' name='txt_jobid[]' id='txt_jobid' >
<input type="submit" value="submit"/>
</form>
<script>
function validate(job)
{
if(job.elements['txt_jobid[]'].length == 0)
{
alert(" Please Enter Value!");
return false;
}
}
</script>
Maybe this...
<form action="" method="post" name="frmPayPal1" id="frmPayPal1">
<input type="text" name="txt_jobid[]" id="txt_jobid">
<input type="submit" value="submit">
</form>
<script>
$(document).ready(function(){
$('#frmPayPal1').on('submit', function(){
var lngtxt=($(this).find('input[name="txt_jobid[]"]').val()).length;
console.log(lngtxt);
if (lngtxt==0){
alert('please enter value');
return false;
}else{
//submit
}
});
});
</script>
You need to pass this
onsubmit="return validateForm(this)"
Also, return true if validation succeeds
function validate(job)
{
if(job.elements['txt_jobid[]'].length == 0)
{
alert(" Please Enter Value!");
return false;
}
return true;
}
function validateForm(){
if((document.getElementById("txt_jobid").value).length == 0){
alert(" Please Enter Value!");
return false;
}
}
<form action="" method="post" name="frmPayPal1" id="frmPayPal1" onsubmit="return validateForm()">
<input type='text' name='txt_jobid[]' id='txt_jobid'>
<input type="submit" value="submit"/>
</form>
Please let me know if you have any query.
here the solution of input type array. I have already post the solution on stackoverflow . please the below link.
https://stackoverflow.com/a/48092147/8189107
here the js fiddle link. you can see it's working here
https://jsfiddle.net/q0d76aqx/42/

Validate on submit button got issue

Here is my code example
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submitForm();">
Below is my function
<script type="text/javascript">
function submitForm()
{
var name = document.getElementById("name").value;
return false;
}
</script>
On press, the form still submit, but if i change
onsubmit="return false;"
then the form won't submit, how do I use the function to return false as i need do some if else validation
<script type="text/javascript">
function submitForm() {
return false;
}
</script>
<form
action="next2.php"
method="post"
name="next2"
id="next2"
onsubmit="return submitForm();"
>
submit is already a function for the form, you should call your JavaScript function something different, for instance submitForm as in the above.
just remove the semicolon in your function and place a alert in your function to make sure whether the function is called first.and then try to add validation
I like to make an invisible button for the actual submit which is only triggered after form validation:
function validate() {
var valid = true;
$.each($('input'), function(){
valid = valid && $(this).val().length > 0;
})
if (valid) {
$('#realSubmit').click();
} else {
alert('Please fill out all fields!');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="next2.php" method="post" name="next2" id="next2" onsubmit="return submit();">
<input type="text" placeholder="Enter Name" />
<input type="password" placeholder="Enter Password" />
<button type="button" onclick="validate()">Submit</button>
<button type="submit" id="realSubmit" style="display:none"></button>
</form>

Categories