Checkbox checked input required , if checkbox is unchecked input not required - javascript

This is my html
<input type="checkbox" name="checked" id="check" onclick="unlocking()">
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display:none;">
<input type="text" name="Name" value="Name" id="inside" required>
<input type="text" name="email" value="email" id="inside" required>
<input type="text" name="Adress" value="Adress" id="inside" required>
</fieldset>
And this is my js with the function to hide and show the fieldset.
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
if(checkBox.checked) {
form.style.display="block";
}else {
form.style.display="none";
}
}
If the fieldset is show i want the input to be required and if not just to skip it.

You could loop through each child and set its required attribute to either true or false depending on if the checkbox is checked or not, like so:
for (child of form.children) {
child.required = true;
}
Please check the snippet below:
function unlocking() {
var checkBox = document.getElementById("check");
var form = document.getElementById("unlock");
if (checkBox.checked) {
form.style.display = "block";
for (child of form.children) {
child.required = true;
console.log(child);
}
} else {
form.style.display = "none";
for (child of form.children) {
child.required = false;
console.log(child);
}
}
}
<input type="checkbox" name="checked" id="check" onclick="unlocking()" />
<label for="checkbox">If checked</label>
<fieldset id="unlock" style="display: none;">
<input type="text" name="Name" value="Name" id="inside" />
<input type="text" name="email" value="email" id="inside" />
<input type="text" name="Adress" value="Adress" id="inside" />
</fieldset>

//element.setAttribute("required", ""); turns required on
//element.removeAttribute("required"); turns required off
function unlocking() {
var checkBox = document.getElementById("check")
var form = document.getElementById("unlock")
var inputs = document.querySelectorAll('input[type=text]')
if(checkBox.checked) {
form.style.display="block";
for(var i = 0; i < inputs.length; i++)
inputs[i].setAttribute("required", "");
}else {
form.style.display="none";
for(var i = 0; i < inputs.length; i++)
inputs[i].removeAttribute("required");
}
}

Related

enabling submit btn after filling form (all inputs) with javascript no jquery

I am trying to create a form that the submit btn is disabled untill all (except for one) of the fields are filled.
this is the html:
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>
this is the js:
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var filled = true;
for(var i = 0; i < txs.length; i++){
if(txs[i].value === "")
filled = false;
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value === "")
filled = false;
}
submitform.disabled = filled;
});
first, it takes a few seconds until the btn becomes disabled. secondly, after I fill any field the btn becomes enabled.
thank you!
Disregarding the comments and the radio buttons and focusing on the main issue, try changing the second half of the code to:
submitform.disabled = true;
contactForm.addEventListener('keyup', function() {
var ins = document.getElementsByTagName("INPUT");
filled = []
for (var j = 0; j < ins.length; j++) {
if (ins[j].value === "")
filled.push(false);
else {
filled.push(true)
}
}
if (filled.includes(false) === false) {
submitform.disabled = false
};
});
and see if it works.
The reason it becomes enabled when you input something is because you are setting
submitform.disabled = filled
At the start, filled is set to true which is why the button is disabled. However, once you type something in any input, you set filled to false which enables the button (submitform.disabled = false).
There's a lot of ways to go about this but here's one. It increments a counter when ever something is filled in. Then you check if that counter is the same as the amount of inputs and textareas.
Secondly, we set the button to be disabled at the very start so even if you remove text from an input, the button will be disabled again if it wasn't
const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');
const submitform = document.querySelector('#submitform');
const contactForm = document.querySelector('#contactForm');
submitform.disabled = true;
contactForm.addEventListener('keyup', function (){
var ins = document.getElementsByTagName("INPUT");
var txs = document.getElementsByTagName("TEXTAREA");
var amountFilled = 0
submitform.disabled = true
for(var i = 0; i < txs.length; i++){
if(txs[i].value !== "") {
amountFilled += 1
}
}
for(var j = 0; j < ins.length; j++){
if(ins[j].value !== "") {
amountFilled += 1
}
}
if (amountFilled === ins.length + txs.length) {
submitform.disabled = false
}
});
<section id="contacSection">
<form id="contactForm">
<fieldset id="contactSection">
<legend>Your contact information</legend>
<label for="FirstName">First Name</label>
<input type="text" id="FirstName" name="FirstName" placeholder="First Name" required>
<label for="LastName">Last Name</label>
<input type="text" id="LastName" name="LastName" placeholder="Last Name">
<label for="email">E-mail</label>
<input type="email" id="email" name="email" placeholder="example#gmail.com" required>
<label for="comments">Comment</label>
<textarea type="text" id="comments" name="comments" placeholder="Don't be shy, drop a comment here!" required></textarea>
</fieldset>
<fieldset>
<legend>Would you like to meet for?</legend>
<div class="radiobtn">
<input type="radio" id="meetingtype1" name=meetingtype value="coffee" checked> A coffee</input>
<input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</input>
<input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</input>
<input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</input>
</div>
</fieldset>
<button id="submitform" type="submit" >Submit</button>
</form>
</section>

Why the output from javascript just shown for a short period of time?

I am developing a Registration form for my assignment. All things are working but when I click on the submit button, the warning messages on the label are just shown for a very short period of time. I am using eclipse and apache tomacat. here is my code.
JSP Code:
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid"/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname"/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname"/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email"/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" onclick="validate()"/>
</form>
Javascript Code:
function validate()
{
var itemid=document.getElementById("itemid").value;
var itemname=document.getElementById("itemname").value;
var uname=document.getElementById("uname").value;
var email=document.getElementById("email").value;
var amount=document.getElementById("amount").value;
var autoincrement=document.getElementById("autoincrement");
var flag=true;
if(itemid.length==0){
flag=false;
document.getElementById("itemid_l").innerHTML="<b>Required field!</b> Item Id: ";
}
if(itemname.length==0){
flag=false;
document.getElementById("itemname_l").innerHTML="<b>Required field!</b> Item Name: ";
}
if(uname.length==0){
flag=false;
document.getElementById("uname_l").innerHTML="<b>Required field!</b> Your Name: ";
}
if(email.length==0){
flag=false;
document.getElementById("email_l").innerHTML="<b>Required field!</b> Your Email Address: ";
}
if(amount.length==0){
flag=false;
document.getElementById("amount_l").innerHTML="<b>Required field!</b> Amount Bid: ";
}
if(!autoincrement.checked){
flag=false;
document.getElementById("autoincrement_l").innerHTML="<b>Required field!</b> Auto-increment to match other bidders:: ";
}
if(flag==true){
alert('Good job!!');
return true;
}
else
{
document.getElementById("msg").innerHTML="Required data is missing. Please fill";
return false;
}
}
Any suggestion will help me a lot..
You can use onsubmit event so that whenever user click on submit button this gets call and if the function validate() return true form will get submitted else it will not submit form .
Demo code :
function validate() {
var itemid = document.getElementById("itemid").value;
var itemname = document.getElementById("itemname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var amount = document.getElementById("amount").value;
var autoincrement = document.getElementById("autoincrement");
var flag = true;
if (itemid.length == 0) {
flag = false;
document.getElementById("itemid_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemid_l").innerHTML = ""
}
if (itemname.length == 0) {
flag = false;
document.getElementById("itemname_l").innerHTML = "<b>Required field!</b> ";
} else {
//if fill remove error any
document.getElementById("itemname_l").innerHTML = "";
}
if (uname.length == 0) {
flag = false;
document.getElementById("uname_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("uname_l").innerHTML = "";
}
if (email.length == 0) {
flag = false;
document.getElementById("email_l").innerHTML = "<b>Required field!</b> ";
} else {
document.getElementById("email_l").innerHTML = "";
}
if (amount.length == 0) {
flag = false;
document.getElementById("amount_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("amount_l").innerHTML = "";
}
if (!autoincrement.checked) {
flag = false;
document.getElementById("autoincrement_l").innerHTML = "<b>Required field!</b>";
} else {
document.getElementById("autoincrement_l").innerHTML = "";
}
if (flag == true) {
document.getElementById("msg").innerHTML = "";
alert('Good job!!');
flag = true; //do true
} else {
document.getElementById("msg").innerHTML = "Required data is missing. Please fill";
flag = false; //do false
}
return flag; //return flag
}
<!--add onsubmit -->
<form method="post" id="forms" onsubmit="return validate()">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--give id to span instead of label-->
<label> <span id="itemid_l"></span>Item Id:</label> <input type="text" name="itemid" id="itemid" /><br/>
<label><span id="itemname_l"></span>Item Name:</label> <input type="text" name="itemname" id="itemname" /><br/>
<label><span id="uname_l"></span>Your Name:</label> <input type="text" name="uname" id="uname" /><br/>
<label><span id="email_l"></span>Your Email Address:</label> <input type="text" name="email" id="email" /><br/>
<label><span id="amount_l"></span>Amount Bid:</label> <input type="number" name="amount" id="amount" /><br/>
<label><span id="autoincrement_l"></span>Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement"><br/>
<input type="submit" value="Submit Bid" />
</form>
Also , if you just need to check for empty field you can just use required attribute on input tag like below :
<form method="post">
<h2>Welcome to AP Auctions. Please Enter Bid</h2>
<span id="msg" style="color:red;font-size:25px"></span><br/>
<!--added required attribute-->
<label id="itemid_l">Item Id:</label> <input type="text" name="itemid" id="itemid" required/><br/>
<label id="itemname_l">Item Name:</label> <input type="text" name="itemname" id="itemname" required/><br/>
<label id="uname_l">Your Name:</label> <input type="text" name="uname" id="uname" required/><br/>
<label id="email_l">Your Email Address:</label> <input type="text" name="email" id="email" required/><br/>
<label id="amount_l">Amount Bid:</label> <input type="number" name="amount" id="amount"required/><br/>
<label id="autoincrement_l">Auto-increment to match other bidders:</label><input type="checkbox" name="autoincrement" id="autoincrement" required><br/>
<input type="submit" value="Submit Bid"/>
</form>

check atleast 2 of 5 input fields were not empty

How to check of two out of five inputted fields and get the value? I'm using jQuery, and I'm not sure what is the proper positioning of this code. Maybe you guys can help me.
Here is my code:
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
}
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
The result that I get is that it only trigger the res variable if the execution reach into 2 above.
I want to submit the form only when there are at least two fields were inputted.
Thanks!
You're checking if any value other than the first two has value
The correct way to implement your check would be:
$(document).ready(function(){
$("#btnSubmit").on('click', function(){
var val = $(".validate");
var res = "";
var reqCount=0
for(var i = 0; i < val.length; i++){
if(val[i].value){
reqCount++;
}
if(reqCount >= 2){
res = "Code Execution here";
}
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
I don't know why there's a C# tag on this question, if you mean to do this on the server side, that'd be a whole different question
Change you logic to count number of filed having value in for loop
than base don count change alert message
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = ""; let count=0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
count++;
}
}
if (count >= 2) {
res = "Code Execution here";
}
alert(res);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
If all you want to do is make sure you have atleast 2 feilds filled before the user submits the form , you can do the below:
function isEmpty(validateElem) {
return (validateElem === "" || typeof validateElem === 'undefined') ? true : false;
}
$(function(){
var InputValidateCount = 0;
$('form').submit(function(){
$('input').each(function(e , i){
if(!isEmpty($(this).val())) {
InputValidateCount++;
}
});
if(InputValidateCount < 2) {
return false; // Stop from from submitting;
}
});
});
You should count the validated fields before submission.
Upvote if this answered you. :P
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var minimumNonEmptyFields = 2;
var validatedNonEmptyFieldsCount = 0;
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
validatedNonEmptyFieldsCount++;
}
}
if(validatedNonEmptyFieldsCount >= minimumNonEmptyFields) {
alert( validatedNonEmptyFieldsCount + " fields are non-empty");
} else {
alert("Please fill " + (minimumNonEmptyFields - validatedNonEmptyFieldsCount) + " more fields");
}
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<title>
Validate any 2 input
</title>
</head>
<body>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<input type="text" class="validate" id="req6" name="req6">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>
<script></script>
</body>
</html>
if atleast two input is not empty then return true else return false .
if return's true it submit's the form else it will not.
$(document).ready(function() {
$("#btnSubmit").on('click', function() {
var val = $(".validate");
var res = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value) {
if (i >= 2) {
res = "Code Execution here";
console.log("success");
return true;
}
}
}
console.log("fail");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="validate" id="req1" name="req1">
<input type="text" class="validate" id="req2" name="req2">
<input type="text" class="validate" id="req3" name="req3">
<input type="text" class="validate" id="req4" name="req4">
<input type="text" class="validate" id="req5" name="req5">
<button type="button" class="btn" id="btnSubmit" name="submit">Submit</button>

My Javascript is not working when tested in IE8

I am making a website and one of the requirements is it to be IE8 compatible. I have a simple form on my page and using a radio button I am changing what fieldsets of the form are visible. Basically I am giving user an option to either input his name or his number. I am using IE11 on W10 in IE8 compatibility mode in F12 menu and the switching is not working. It works everywhere else, even in IE9+. Do you know what could be the problem?
Both my radio buttons have an onclick function that set one fieldset at display:none and the other at display:block. The "header__form__fs_person" is hidden by default.
html:
<form class="header__form" name="form_name">
<fieldset class="header__form__label_choices">
<label class="header__form__label" for="person">Podle jména</label>
<input class="header__form__input_radio" type="radio" value="person_on" id="person" name="choice" onclick="hideIc(this)" checked>
<span class="header__form__divider">/</span>
<label class="header__form__label" for="ic">Podle IČ</label>
<input class="header__form__input_radio" type="radio" value="ic_on" id="ic" name="choice" onclick="hidePerson(this)">
</fieldset>
<fieldset class="header__form__fs_person">
<input class="header__form__input_text" type="text" id="name" placeholder="Jméno" required>
<input class="header__form__input_text" type="text" id="lastname" placeholder="Příjmení" required>
<input class="header__form__input_text" type="text" id="bday" placeholder="Narozen" onfocus="(this.type='date')" required>
</fieldset>
<fieldset class="header__form__fs_ic" disabled>
<input class="header__form__input_text" pattern=".{9,}" placeholder="123456789" required>
</fieldset>
<label class="header__form__terms" for="terms">Souhlasím s <a class="header__form__terms_a" href="">obchodnimi podmínkami</a></label>
<input class="header__form__input_checkbox" type="checkbox" id="terms" required>
<input class="header__form__input_btn" type="submit" value="Ověřit">
</form>
js:
<script>
function hideIc(radio_btn) {
if (radio_btn.checked) {
var ic = document.getElementsByClassName("header__form__fs_ic");
var person = document.getElementsByClassName("header__form__fs_person");
for (var i=0; i < ic.length; i++) {
ic[i].style.display = "none";
ic[i].disabled = true;
person[i].style.display = "block";
person[i].disabled = false;
}
}
}
function hidePerson(radio_btn) {
if (radio_btn.checked) {
var ic = document.getElementsByClassName("header__form__fs_ic");
var person = document.getElementsByClassName("header__form__fs_person");
for (var i=0; i < ic.length; i++) {
ic[i].style.display = "block";
ic[i].disabled = false;
person[i].style.display = "none";
person[i].disabled = true;
}
}
}
</script>
IE8 doesn't support getElementsByClassName().
See here: http://caniuse.com/#feat=getelementsbyclassname
There is a walk-around:
if(!document.getElementsByClassName) {
document.getElementsByClassName = function(className) {
return this.querySelectorAll("." + className);
};
Element.prototype.getElementsByClassName = document.getElementsByClassName;
}
The answer isn't mine... I found it here: javascript document.getElementsByClassName compatibility with IE

Check(validate) radio buttons with an if else if true no alert if not checked alert must be check

This is what I have on the HTML side of things. I have a form with the id of products, a name of myForm, an action tag a method of get, and onsubmit returns the function validateForm(); I have a full fledged order form
<form id="products"name="myForm"action="FormProcessor.html"method="get"
onsubmit="return validateForm();">
<label for="payment">Payment Method?</label>
<input id="visa" name="credit_card" type="radio" value="Visa" />
<label for="visa">Visa</label>
<input id="masterCard" name="credit_card" type="radio"value="MasterCard" />
<label for="mastercard">MasterCard</label>
<input id="ae"name="credit_card"type="radio"value="American Express" />
<label for="americanexpress">American Express</label><br>
This is what I have on the js side of things, I am also trying to write it in vanilla js. I have not learned jQuery yet i am still new to programming. I am not sure why it is not alerting.
function validateForm() {
var p_form = document.getElementById("products");
p_form.addEventListener("submit", function(event) {
var payment_array = document.getElementsByName("credit_card");
for(var i = 0; i < payment_array.length; i++) {
if(payment_array[i].checked) {
selection_made = true;
break;
}
}
if(!selection_made) {
event.preventDefault();
alert("Payment Method must be selected.");
return false;
}
});}
Demo: http://jsfiddle.net/e4gfs67o/1/
Solution:
HTML:
<form id="products" name="myForm" action="FormProcessor.html" method="get">
<label for="payment">Payment Method?</label>
<input id="visa" name="credit_card" type="radio" value="Visa" />
<label for="visa">Visa</label>
<input id="masterCard" name="credit_card" type="radio" value="MasterCard" />
<label for="mastercard">MasterCard</label>
<input id="ae"name="credit_card" type="radio" value="American Express" />
<label for="americanexpress">American Express</label><br>
<button type='submit'>Submit</button>
</form>
Javascript:
var form = document.getElementById('products');
form.addEventListener('submit', function(event) {
var radios = document.getElementsByName('credit_card'),
len = radios.length,
i = 0,
selected = false;
for (; i < len; i++) {
if (radios[i].checked) {
selected = true;
break;
}
}
if (selected) {
return true;
} else {
event.preventDefault();
alert('Payment Method must be selected.');
return false;
}
});

Categories