Multiple Checkbox validation at javascript - javascript

i have multiple checkbox, and all of it must be checked.
i write down the code but it doesnt work.
this is the code
html sample::
<form name="pembres" id="pembres" method="POST" onSubmit="return validateform()" style="margin:0;">
<input type="checkbox" name="lanjut[]" value="setuju2" />
<input type="checkbox" name="lanjut[]" value="setuju3" />
<input type="checkbox" name="lanjut[]" value="setuju4" />
<input type="checkbox" name="lanjut[]" value="setuju5" />
<input type="submit" value="Next Step" name="next" />
</form>
1st script at head tag
<script type="text/javascript">
function validateform(){
var success = false;
for (i = 0; i < document.pembres.elements['lanjut[]'].length; i++){
if (document.pembres.elements['lanjut[]'][i].checked){
success = true;
}
}
return success;
}
</script>
2nd script before /body
<script type="text/javascript">
var form = document.getElementById('pembres');
form.onsubmit = validateForm;
function validateForm() {
var isValid = false,
form = this,
els = form.elements['lanjut[]'];
i;
for (i = 0; i < els.length; i += 1) {
if (els[i].checked) {
isValid = true;
}
}
return isValid;
}
</script>

You are setting isValid to true if any checkbox is checked, what you should do is return false if any checkbox is not checked.
function validateForm() {
var form = this,
els = form.elements['lanjut[]'], i;
for (i = 0; i < els.length; i += 1) {
if (!els[i].checked) {
return false;
}
}
return true;
}

Related

validation using js is not updating to span

I wrote this code to validate user input by js but it seems not entering the script I think the problem is that the "onkeyup" is not working with me
<script language="JavaScript">
var flag = false ;
function checkCat(value)
{
var validate = /^[a-z]{3,15}$/i ;
if( value.length ==0 )
{
re = '';
flag = false ;
}
else if(!validate.test(value))
{
flag = false ;
re = 'Invalid';
col = 'red' ;
}
else
{
flag = true ;
re = 'Valid';
col = 'green' ;
}
document.getElementById('print').style.color = col ;
document.getElementById('print').innerHTML = re ;
}
function checkForm ()
{
document.catForm.JSEnabled.value="TRUE";
return flag ;
}
</script>
the above code in the head part and the below in the body part
<form method = 'post' name = 'catForm' onsubmit="return checkForm();" >
<input type="text" name = 'cat' placeholder="Category name" onkeyup='checkCat(this.value)'> <span id='print'></span> <br/>
<input type='hidden' name='JSEnabled' value='FALSE' />
<input id="submit" type="submit" name = 'sb' value="Add A New Category" >
I even tested it with HTA extension and everything is ok !
<!DOCTYPE html>
<html>
<title>validation using js is not updating to span</title>
<head>
<script language="JavaScript">
var flag = false ;
function checkCat(value)
{
var validate = /^[a-z]{3,15}$/i ;
if( value.length ==0 )
{
re = '';
flag = false ;
}
else if(!validate.test(value))
{
flag = false ;
re = 'Invalid';
col = 'red' ;
}
else
{
flag = true ;
re = 'Valid';
col = 'green' ;
}
document.getElementById('print').style.color = col ;
document.getElementById('print').innerHTML = re ;
}
function checkForm ()
{
document.catForm.JSEnabled.value="TRUE";
return flag ;
}
</script>
</head>
<body>
<form method = 'post' name = 'catForm' onsubmit="return checkForm();" >
<input type="text" name = 'cat' placeholder="Category name" onkeyup='checkCat(this.value)'> <span id='print'></span> <br/>
<input type='hidden' name='JSEnabled' value='FALSE' />
<input id="submit" type="submit" name = 'sb' value="Add A New Category" >
</body>
</html>
Seems it is working as expected:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<form method='post' name='catForm' onsubmit="return checkForm();">
<input type="text" name='cat' placeholder="Category name" onkeyup='checkCat(this.value)'> <span id='print'></span> <br />
<input type='hidden' name='JSEnabled' value='FALSE' />
<input id="submit" type="submit" name='sb' value="Add A New Category">
</form>
<script>
var flag = false;
function checkCat(value) {
var validate = /^[a-z]{3,15}$/i;
if (value.length == 0) {
re = '';
flag = false;
}
else if (!validate.test(value)) {
flag = false;
re = 'Invalid';
col = 'red';
}
else {
flag = true;
re = 'Valid';
col = 'green';
}
document.getElementById('print').style.color = col;
document.getElementById('print').innerHTML = re;
}
function checkForm() {
document.catForm.JSEnabled.value = "TRUE";
return flag;
}
</script>
</body>
</html>
I tested it here:
`https://jsfiddle.net/v2b6sqcx/`
and it's working fine for me

Get the form data on load submit

I want the form data that was submitted on page load via POST method
Here is my code
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>
What I want is to get the form data when ever this page is loaded
What I tried
document.getElementsByTagName('form')[0].onsubmit = function () {
var status, date;var str = '';
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
else if (date != null) {
str += date.value;
}
}//func close
Why are you submitting the form while user has not even filled the form body onload !
If you are allowed to use Jquery it will do your task easy
document.getElementsByTagName('form')[0].onsubmit = function () {
$(this).serializeArray();
}//func close
Please have a look at this link for details
Here is a small demonstration
$(document).ready(
function() {
$("#Form1").on('submit', function() {
var data = $(this).serializeArray()
console.log(data);
for (var i = 0; i < data.length; i++) {
document.body.innerHTML += 'Key: '+data[i].name +' and Value: '+ data[i].value + '</br>';
}
return false;
});
$("#Form1").submit();
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
You need to write your code inside window.onload evnet.
Try this
window.onload = function() {
var str = '';
var status, date;
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name.toLowerCase() === 'status') {
status= inputs[i];
}
else if (inputs[i].name.toLowerCase() === 'date') {
date= inputs[i];
}
}//for close
if (status != null) {
str += status.value;
}
if (date != null) {
str += date.value;
}
alert(str);
};
<<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<body onload="document.forms["Form1"].submit()">
<form id="Form1" method="POST" action="page2.aspx">
<input type="hidden" name="Status" value="success">
<input type="hidden" name="Date" value="05/05/2016">
</form>
</body>

How to do proper validation for this and set focus and then form has to submitted

Here I am facing problem in if condition it validates for subject and unable to set focus and not validate for medium field. Here checkbox is coming from mysql. But it gives source like this only. can any figure out what is the problem in my code?what I have to do here.I hope everyone understand the question.I need to proper code to validate these two fields. At least in subject column any one should be selected likewise in regional field also any should be selected. I tried has much what I can do. But I could not completed the work.
what I needed is:
Atleast any one should be selected in subject field.if its null alert +focus
like wise for medium field also.
<script type="text/javascript">
function check() {
var a1 = false;
b1 = false;
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var reg1 = reg.length;
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
a1 = true;
}
}
}
if (!chk[i].checked) {
chk[i].focus();
}
if (len) {
for (i = 0; i < len; i++) {
if (reg1[i].checked) {
return true;
} else {
alert('please select the medium');
b1 = true;
}
}
}
if (a1 == true && b1 == true) {
return true;
}
}
</script>
Myform is:
<form name="f1" action="s.php" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
Like this
Instead of onclick use onsubmit and assign the function onload
window.onload=function() {
document.getElementsByName("f1")[0].onsubmit=function() {
var chk = document.getElementsByName('subject[]'),chkOk=false;
for (var i = 0, n=chk.length; i < n; i++) {
if (chk[i].checked) {
chkOk = true;
break;
}
}
console.log(chkOk)
if (!chkOk) {
alert('please select the subject');
chk[0].focus(); // focus the first
return false;
}
var reg = document.getElementsByName('regional[]'),regOk=false;
for (var i = 0, n=reg.length; i < n; i++) {
if (reg[i].checked) {
regOk = true;
break;
}
}
if (!regOk) {
alert('please select the medium');
reg[0].focus(); // focus the first
return false;
}
return true; // allow submit
}
}
<form name="f1" action="s.php" method="post" onsubmit="return check()">
Subject
<input type='checkbox' name='subject[]' value='science'>science
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT">
</form>

Disable/Enable Submit Button until all forms have been filled

I want my form submit button to be disabled/enabled depending on if the form is completely filled.
When the inputs are filled, the disabled button changes to enabled. That works great.
But I would like it to disable the button when an input gets emtied.
This is my script:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
Just use
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.
Just add an else then:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
Put it inside a table and then do on her:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
Here is the code
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
I think this will be much simpler for beginners in JavaScript
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input");
We create another variable to store the button element
var btn = document.getElementById("btn");
We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) {
// Code
}
Finally, We use the checkValidity() method to check if the input elements
(with a required attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
You can enable and disable the submit button based on the javascript validation below is the validation code.
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>

Validating a single radio button is not working in available javascript validation script Part-2

I am available with the solution given by #Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined
[Break On This Error] var rdo = (frm.creatorusers.length >...rm.creatorusers : frm.creatorusers;
I used the code for validating radio button as:
function valDistribution(frm) {
var mycreator = -1;
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers;
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
mycreator = 1;
//return true;
}
}
if(mycreator == -1){
alert("You must select a Creator User!");
return false;
}
}
Here is how to use the code you were given by #Tomalak but did not copy correctly
function valDistribution(frm) { // frm needs to be passed here
var myCreator=false;
// create an array if not already an array
var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : [frm.creatorusers];
for (var i=0; i<rdo.length; i++) {
if (rdo[i].checked) {
myCreator=true;
break; // no need to stay here
}
if (!myCreator){
alert("You must select a Creator User!");
return false;
}
return true; // allow submission
}
assuming the onsubmit looking EXACTLY like this:
<form onsubmit="return valDistribution(this)">
and the radio NAMED like this:
<input type="radio" name="creatorusers" ...>
You can try this script:
<html>
<script language="javascript">
function valbutton(thisform) {
myOption = -1;
alert(thisform.creatorusers.length);
if(thisform.creatorusers.length ==undefined) {
alert("not an array");
//thisform.creatorusers.checked = true;
if(thisform.creatorusers.checked) {
alert("now checked");
myOption=1;
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers.value);
}
}
else {
for (i=thisform.creatorusers.length-1; i > -1; i--) {
if (thisform.creatorusers[i].checked) {
myOption = i; i = -1;
}
}
if (myOption == -1) {
alert("You must select a radio button");
return false;
}
alert("You selected button number " + myOption
+ " which has a value of "
+ thisform.creatorusers[myOption].value);
}
}
</script>
<body>
<form name="myform">
<input type="radio" value="1st value" name="creatorusers" />1st<br />
<!--<input type="radio" value="2nd value" name="creatorusers" />2nd<br />-->
<input type="button" name="submitit" onclick="valbutton(myform);return false;" value="Validate" />
<input type="reset" name="reset" value="Clear" />
</form>
</body>
</html>

Categories