I'm trying to not allow both checkboxes to be checked at the same time. Here is my vanilla JS. I have the function already validating to return true when one is checked and false when neither are checked. Radio boxes are not an option.
function valForm() {
var both = document.getElementById("cEmail1" & "cPhone1");
for (var i = 1; i <= 2; i++) {
if (document.getElementById("cEmail1").checked) {
return true;
} else if (document.getElementById("cPhone1").checked) {
return true;
} else if (both.checked) {
return false;
} else {
return false;
}
}
}
<form action="http://severien.com/grit/formecho.php" method="post" name="contactUsForm" onsubmit="return valForm()">
<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail" /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check2" id="cPhone1" type="checkbox" name="contactbyphone" /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div>
</form>
If radio boxes really aren't an option, then there are a few issues with your code. First of all, you are checking if each of the boxes is checked, and if either of them is checked, then you are immediately returning. The second, and much larger problem, is that your both element should be undefined. The & in JavaScript is a bitwise operator, and getElementById should only return one element. Instead, you could implement the equivalent of a logical XOR like so:
function valForm(){
return document.getElementById("cEmail1").checked != document.getElementById("cPhone1").checked;
}
You can't get two elements at the same time using getElementById, so you'll need to check them separately by using the && operator.
You also need to check this first, because the two if statements before this will preempt this check.
function valForm() {
var cEmail = document.getElementById("cEmail1");
var cPhone1 = document.getElementById("cPhone1");
if (cEmail.checked && cPhone1.checked) {
console.log("false");
return false;
} else if (cEmail.checked || cPhone1.checked) {
console.log("true");
return true;
} else {
console.log("false");
return false;
}
}
<form action="http://severien.com/grit/formecho.php" method="post" name="contactUsForm" onsubmit="return valForm()">
<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail" /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check2" id="cPhone1" type="checkbox" name="contactbyphone" /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div>
</form>
This should return false if neither or both are checked:
function valForm() {
var email = document.getElementById("cEmail1");
var phone = document.getElementById("cPhone1")
if (email.checked && !phone.checked || !email.checked && phone.checked) {
console.log('ok')
return true;
}
console.log('no ok')
return false;
}
<form action="http://severien.com/grit/formecho.php" method="post" name="contactUsForm" onsubmit="return valForm()">
<span class="box3"><label for="cEmail" class="l5" >Contact me by email</label>
<input class="check1" id="cEmail1" type="checkbox" name="contactbyemail" /></span>
<span class="box4"><label for="cPhone" class="l6">Contact me by phone</label>
<input class="check1" id="cPhone1" type="checkbox" name="contactbyphone" /></span> <br />
<div class="formSubmit"><input type="submit" value="Submit" /></div>
</form>
</div>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.slectOne').on('change', function() {
$('.slectOne').not(this).prop('checked', false);
$('#result').html($(this).data( "id" ));
if($(this).is(":checked"))
$('#result').html($(this).data( "id" ));
else
$('#result').html('Empty...!');
});
});
</script>
</head>
<body>
<input type="checkbox" class="slectOne" data-id="1 selected"/>
<input type="checkbox" class="slectOne" data-id="2 selected"/>
<input type="checkbox" class="slectOne" data-id="3 selected"/>
<input type="checkbox" class="slectOne" data-id="4 selected"/>
<input type="checkbox" class="slectOne" data-id="5 selected"/>
<input type="checkbox" class="slectOne" data-id="6 selected"/>
<input type="checkbox" class="slectOne" data-id="7 selected"/>
<input type="checkbox" class="slectOne" data-id="8 selected"/>
<input type="checkbox" class="slectOne" data-id="9 selected"/>
<input type="checkbox" class="slectOne" data-id="10 selected"/>
<span id="result"></span>
</body>
</html>
here is a good example to use as well
https://www.w3schools.com/code/tryit.asp?filename=FB6JK5HW3Z53
Related
I have a simple contact form with multiple checkboxes, when a user selects a checkbox it should go to the url/folder tied to the url that's in the value. The current problem is after a user checks the checkbox and clicks submit, then goes back to that page and the checkbox resets, the submit button still takes them to the previously selected checkbox.
Need a way to fully reset the form and disable the button so the submission doesn't get too confusing for the user. Thanks!
Here is my form code:
<form name="frm" id="myForm" method="post" >
<div class="provider-checkboxes">
<input type="checkbox" name="rGroup" id="r1" value="folder-1/" onclick="formaction(this)"/>
<label class="check-div" for="r1">Label 1</label>
<input type="checkbox" name="rGroup" id="r2" value="folder-2/" onclick="formaction(this)"/>
<label class="check-div" for="r2">Label 2</label>
<input type="checkbox" name="rGroup" id="r3" value="folder-3/" onclick="formaction(this)"/>
<label class="check-div" for="r3">Label 3</label>
<button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</div>
</form>
Here is the script:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var inputValue = $(this).attr("value");
$("." + inputValue).toggle();
});
});
$('[data-toggle="btns"] .btn').on('click', function(){
var $this = $(this);
$this.parent().find('.active').removeClass('active');
$this.addClass('active');
});
$('.selectme input:checkbox').click(function() {
$('.selectme input:checkbox').not(this).prop('checked', false);
});
$('.provider-checkboxes input:checkbox').click(function() {
$('.provider-checkboxes input:checkbox').not(this).prop('checked', false);
});
function formaction(checkbox){
document.getElementById("myForm").action = checkbox.value;;
}
function UncheckAll(){
var w = document.getElementsByTagName('input');
for(var i = 0; i < w.length; i++){
if(w[i].type=='checkbox'){
w[i].checked = false;
}
}
}
Consider the following code. Think this will help, based on what you have shared.
$(function() {
function setFormAction(frm, a) {
frm.attr("action", a);
}
function unCheckAll() {
$("input[type='checkbox']").prop("checked", false);
$(".provider-checkboxes .btn").hide();
}
$('.provider-checkboxes input:checkbox').click(function() {
unCheckAll();
$(this).prop("checked", true);
$(".provider-checkboxes .btn").toggle(300);
setFormAction($("#myForm"), "./" + $(this).val());
console.log($("#myForm")[0]);
});
unCheckAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="frm" id="myForm" method="post">
<div class="provider-checkboxes">
<input type="checkbox" name="rGroup" id="r1" value="folder-1/" />
<label class="check-div" for="r1">Label 1</label>
<input type="checkbox" name="rGroup" id="r2" value="folder-2/" />
<label class="check-div" for="r2">Label 2</label>
<input type="checkbox" name="rGroup" id="r3" value="folder-3/" />
<label class="check-div" for="r3">Label 3</label>
<button type="submit" class="btn btn-primary btn-lg btn-block">Next</button>
</div>
</form>
I'm trying to populate the multiple selected choice from checklist into PHP. However, only the "Reading" choice is populating in the new window and not the other choices that I have selected. For example, I have selected "Painting & Travelling" but after I clicked submit, the value that showing is "Reading".Kindly advise how to fix this. Thanks in advance. I'm new to web development.
Javascript
function validate(){
var x3=document.getElementById("hobbies");
if (x3.value == "")
{
alert("No blank values allowed")
return false;
}
else
{
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+x3.value+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}
Form
<form onsubmit="return validate()" method= "get">
<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading"/>Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting"/>Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling"/>Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking"/>Baking<br/><br/>
</div>
</form>
Please try the following:
<form onsubmit="return validate()" method= "get">
<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading" />Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting" />Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling" />Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking" />Baking<br/><br/>
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
function validate() {
var x3 = document.getElementsByName("hobbies[]");
var selectedVals = "";
for(var i = 0; i < x3.length; i++) {
if((x3[i].checked) && (x3[i].value != '')) {
selectedVals += (selectedVals == '')?x3[i].value:','+x3[i].value;
}
}
if(selectedVals == "") {
alert("No blank values allowed")
return false;
}
else {
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+selectedVals+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}
}
</script>
Hope this may help.
You need to fetch the values of checkbox one by one in loop:
<form onsubmit="return validate()" method= "get" name="demoForm">
<label>Hobbies : </label><br><br>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Reading"/>Reading<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Painting"/>Painting<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Traveling"/>Traveling<br/>
<input type="checkbox" id="hobbies" name="hobbies[]" value="Baking"/>Baking<br/><br/>
<button type="submit">click</button>
</form>
<script type="text/javascript">
function validate(){
var hobby = document.forms['demoForm'].elements[ 'hobbies[]' ];
var len = hobby.length;
var values="";
for (var i=0;i<len;i++)
{
if (hobby[i].checked)
{
values += hobby[i].value+",";
}
}
values = values.replace(/,\s*$/, "");
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+values+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0 ');
}
</script>
You can also fetch the values using $_GET['hobbies']
You set all elements with the same id
id is unique attribute so whatever you select the javascript will always return the first element value on x3 you can do this if you only want to submit selected checkboxes
<script type="text/javascript">
function validate() {
var x3 = document.getElementsByName("hobbies[]");
var values= "";
for(var i = 0; i < x3.length; i++) {
if(x3[i].checked) {
if(x3[i].value==''){
alert('No blank values allowed');
return false;
}
else{
values+= x3[i].value+',';
}
}
}
window.open('https://quiet-odyssey-258110.appspot.com/?hobbies[]='+values+'','mywin','left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
}
}
I'm trying to validate my form through JavaScript and instead of manually checking each radio button I decided to loop through a group of radio buttons and check to see if they were checked or not.
I'm simply trying to see if a group of radio buttons is checked or not. But the problem I'm facing is. It's returning both true and false when I check either of them. If I don't check either, they both return false but if I check one, it returns true and false.
Here is my code:
function validateForm(){
let firstliGroup = document.getElementsByName("yesnocheck");
for(i=0; i<firstliGroup.length; i++){
//console.log(firstliGroup[i].checked);
if(firstliGroup[i].checked == true){
console.log('success');
return true;
}
else {
console.log('failed');
return false;
}
}
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<input type="submit" value="Send">
</form>
Try this:
function getRadioValue(name) {
let elements = document.getElementsByName(name);
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return elements[i].value;
}
}
return null;
}
function validateForm() {
var yesnocheck = getRadioValue("yesnocheck");
console.log(yesnocheck);
return false;
}
If nothing is checked, then getRadioValue function will return null.
If any option was checked, it will return it's value.
Try using document.forms[0].yesnocheck.
function validateForm()
{
return (document.forms[0].yesnocheck.value.length > 0 &&
document.forms[0].yesnoremote.value.length > 0 &&
document.forms[0].yesnocable.value.length > 0 &&
document.forms[0].condition.value.length > 0);
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<label for="gateremote">Gate remote batteries checked?:</label>
<input type="radio" name="yesnoremote" value="Yes"><span>Yes</span>
<input type="radio" name="yesnoremote" value="No"><span>No</span>
<label for="internetcabletv">Internet and Cable TV checked?:</label>
<input type="radio" name="yesnocable" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocable" value="No"><span>No</span>
<label for="unitcondition">Unit Condition?:</label>
<input type="radio" name="condition" value="clean"><span>Clean</span>
<input type="radio" name="condition" value="light"><span>Light</span>
<input type="radio" name="condition" value="heavy"><span>Heavy</span>
<input type="radio" name="condition" value="superheavy"><span>SuperHeavy</span>
<input type="submit" value="Send">
</form>
I have nine checkboxes linked to nine images and three of them use the name 'correct' using the code shown below.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"/>
</div>
The remaining six are unnamed using the code shown below.
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4"/>
</div>
I currently have the following code to produce an alert if the three checkboxes with the name "correct" are checked but it isn't working.
<script>
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
</script>
Can anyone help me with this?
Loop over all of the checkboxes, checking their state. Once this is done, create a variable "correct" and initialize it to true. Then go to each state in the variable and, if you find that its name isn't "correct" and it is checked or its name is "correct" and it isn't correct, set the variable to false. Then check if the variable is true and, if it is, display the alert.
View an example here: https://repl.it/GxsE/9
Using ES6:
const correctInputs = [...document.querySelectorAll('input[name="correct"]')];
const alertIfThree = () => {
const checkedCorrectInputs = correctInputs.filter(input => input.checked);
if (checkedCorrectInputs.length > 2) {
alert('Alert');
}
};
correctInputs.forEach(input => input.addEventListener('click', alertIfThree));
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
document.querySelectorAll('input[name="correct"]') gets all inputs with name "correct".
[...CODE] is spread operator, it converts code from previous point to array.
correctInputs.forEach(input => input.addEventListener('click', alertIfThree)) adds click event listener to each of them. That event listener is function alertIfThree().
alertIfThree() filters out those input elements that are not checked and produces alert if there are more than 2 of them.
EDIT
In response to your comment:
// jshint esnext: true
const inputs = [...document.querySelectorAll('input[name="correct"], input[name="incorrect"]')];
const alertIfCorrect = () => {
const checkedInputs = inputs.filter(input => input.checked),
noIncorrectCheckedInputs = checkedInputs.find(input => input.name === 'incorrect') === undefined;
if (checkedInputs.length > 2 && noIncorrectCheckedInputs) {
alert('Alert');
}
};
inputs.forEach(input => input.addEventListener('click', alertIfCorrect));
<p>Correct:
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
<input type="checkbox" name="correct"/>
</p>
<p>Incorrect:
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
<input type="checkbox" name="incorrect"/>
</p>
const is ES6 constant. "The value of a constant cannot change through re-assignment, and it can't be redeclared".
[...CODE_HERE] is so called spread syntax. Here, it turns what it contains after ellipsis into an array. Other way to do it would be to use Array.from().
() => { and input => CODE_HERE are arrow functions. They are ES6's syntactic sugar for function declaration.
What stands before => are parameters. () stands for 0 parameters. If you wanted function that takes few parameters, those braces would need to have those few parameters inside them. For one parameter, parameter's name can replace braces altogether (like in second code in this bullet point).
What stands after => is either expression or group of statements. Statements are surrounded by curly brackets ({}). If you omit them, you are writing an expression that your function will return. For example input => input.checked is equivalent to function(input) { return input.checked; }.
filter() and find() are methods of array prototype. They respectively filter and search an array using condition defined in a function that is passed to them as a parameter. Read more by following those two links.
If you need something else explained, let me know. Those functions and structures here are pretty... fresh, so you can just not know them yet.
I put this in a JSfiddle and it works for me. I just wrapped your JS in a function and added an onclick event.
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct"onclick="validate()"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" class="chk" id="incorrect4" onclick="validate()"/>
</div>
<script type=text/javascript">
function validate()
{
var i, correct = document.getElementsByName('correct');
for (i = 0; i <= correct.length; i++) {
if (correct[i].checked) {
alert('correct');
return true;
}
}
alert('incorrect');
return false;
}
</script>
It will require some javascript. You will need o check the checkboxes each time one changes. So to start with you will need to check your checkboxes, assuming they have an assigned class of 'chk'. This can be done with a querySelector.
Each time a checkbox changes, the function 'check_checkboxes()' is called. This function will see for each checkbox with name='correct' if it is checked and then increment 'count'
var checkboxes = document.querySelectorAll(".chk");
var correct = document.querySelectorAll("[name=correct]");
function check_checkbox() {
var count = 0;
[].forEach.call(correct, function(item) {
if (item.checked) {
count++;
}
});
if (count >= 3) {
alert("count of 3 or more");
}
}
[].forEach.call(checkboxes, function(item) {
item.addEventListener("change", function() {
check_checkbox();
}, false);
});
<div class="nine">
<label for="correct1"><img class="picture1" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="correct1" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" />
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="http://placehold.it/40x40"/></label>
<input type="checkbox" class="chk" id="incorrect4" name="correct" />
</div>
Check the loop. Use for (i = 0; i < correct.length; i++) { instead for (i = 0; i <= correct.length; i++) {
var i, correct = document.getElementsByName('correct');
var correct_answers = [];
function validate(){
correct_answers = [];
for (i = 0; i < correct.length; i++) {
var element = correct[i].getAttribute("id");
var checked = correct[i].checked;
correct_answers.push({element,checked});
}
}
function show(){
document.getElementById('results').innerHTML ="";
for(var e=0;e<correct_answers.length;e++){
var box = document.createElement('div');
box.innerHTML = correct_answers[e].element+ " " + correct_answers[e].checked+ "<br>";
document.getElementById('results').appendChild(box);
}
}
<div class="nine">
<label for="correct1"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct1" name="correct"/>
</div>
<div class="nine">
<label for="correct2"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct2" name="correct"/>
</div>
<div class="nine">
<label for="correct3"><img class="picture1" src="picture1.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="correct3" name="correct"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect4"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect5"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect6"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect7"/>
</div>
<div class="nine">
<label for="incorrect1"><img class="picture4" src="picture4.jpg"/></label>
<input type="checkbox" onclick="validate()" class="chk" id="incorrect8"/>
</div>
<button onclick="show();">show results</button>
<div id="results"></div>
Use document.querySelectorAll('input[name]=correct') in your code.
I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>