Here I am facing problem in if condition it validates for subject and not validate for medium field. Here checkbox is coming from mysql. But it gives source like this only. Here Know the problem is with if conditional only how to overcome this?can any figure out what is the problem in my code?what I have to do here.I hope everyone understand the question.I don't understand why the second if conditional statement is not working.
function check() {
//alert('done')
var chk = document.getElementsByName('subject[]');
var reg = document.getElementsByName('regional[]');
var len = chk.length;
var regl = reg.length;
//alert(len);
if (len) {
for (i = 0; i < len; i++) {
if (chk[i].checked) {
return true;
} else {
alert('please select the subject');
return false;
}
}
}
if (regl) {
for (i = 0; i < regl; i++) {
if (reg[i].checked) {
return true;
} else {
alert('please select the regional');
return false;
}
}
}
}
<form name="f1" action="" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science<br/>
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi<br/>
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
Because if the first condition is getting false then it will stop executing the code because you have "return".
At a time both will not be validate as per you code.
First make all the subject checked and then try, you will get the second if will be working.
function check() {
var subjects = document.getElementsByName("subject[]"),
regionals = document.getElementsByName('regional[]'),
subjectSelected = false,
regionalSelected = false;
// check subject
for(var i=0;i<subjects.length;i++){
if(subjects[i].checked){subjectSelected = true;}
}
// check medium
for(var i=0;i<regionals.length;i++){
if(regionals[i].checked){regionalSelected = true;}
}
if(!subjectSelected || !regionalSelected){
if(!subjectSelected){ // subject not selected
alert("Please select a subject.");
}else{ // medium not selected
alert("Please select a regional.");
}
}
}
<form name="f1" action="" method="post">
Subject
<input type='checkbox' name='subject[]' value='science'>science<br/>
<input type='checkbox' name='subject[]' value='maths'>maths<br/>
Medium
<input type='checkbox' name='regional[]' value='Hindi'>Hindi<br/>
<input type='checkbox' name='regional[]' value='english'>english<br/>
<input type="submit" name="land" class="butt" value="SUBMIT" onClick="return check();">
</form>
the mistake you did very silly. whenever you will use the return key it will exit the function and won't process below or next codes. Moreover, I think you are trying to validate the form like if at least one subject and medium is selected the form is valid. Either you want to alert the user. The easy way to do that is first take two variable inside the function, one for subject another one for medium and set both of them to false, that means nothing is selected. Now run a loop and set the related variable true if the checkbox is checked, that means at least one is checked what you want. After two loops now write a if-else-then condition for below three states:
Both true -> at least one subject and medium is checked
one true, one false -> either subject or medium is not selected.
both false -> nothing selected.
if you are trying something else leave a comment and I will post the solution. besides, feel free to ask if you have further questions.
Related
All inputs from page
I have this html page which is dynamical created, which contains some divs. Every div-question(0,1,2, etc) contain an input based on which answer type the user chose. I want to validate every single inputs from page and:
If value of one input type number,text,date is != "" alert("something")
else send the value in an array;
If checkbox/radio is not checked alert("something");
I tried something like this:
let nrDiv = document.getElementsByClassName("div-question");
let existInput = nrDiv[0].querySelector("input[type='text']");
let numberInput = nrDiv[0].querySelector("input[type='number']");
if (document.body.contains(existInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container[0].querySelector("input[type='text']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
It's working but if I come with another for loop, for input type="number" is not working anymore. I'm getting value null. So if I come with this:
if (document.body.contains(numberInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container.querySelector("input[type='number']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
And for the checkbox and radio inputs I don't have any idea. I want something like this:
If all inputs are not empty and minimum one checkbox/radio is checked, send the answer and question in an array else alert("error");
I feel like this is simple once you add the required attribute and/or a pattern.
This is a simple POC:
<form action="">
<input type="text" required>
<input type="number" required>
<input type="checkbox" required>
<input type="radio" required>
<input type="date" required>
<button type="submit">Submit</button>
</form>
Notice that when you click the submit button, it does the verification you want, in this case != "".
I have 3 checkboxes, i wish to be able to click the box and it tick on/off and via jscript change the value of the input for posting to state weather item is accepted or not on another page. However i have logical script but it wont work, theres no errors but the checkboxes wont click on/off they just click on and thats it.. and the value wont change either i dont understand why.
Could somebody look at this short code and tell me why.
Thank you.
<input type="checkbox" id="paypal" name="paypal1" value=" " onclick='chbxpp();' >
</input>
<label for="paypal" class="checkboxes" >Show PayPal Accepted</label>
<br>
<input type="checkbox" id="facebook" name="facebook" value=" " onclick='chbxfb(this);' >
</input>
<label for="facebook" class="checkboxes" >Show FaceBook Contact Details</label>
<br>
<input type="checkbox" id="twitter" name="twitter" value=" " onclick='chbxtw(this);' >
</input>
<label for="twitter" class="checkboxes" >Show Twitter Contact Details</label>
function chbxpp()
{
if(document.getElementById('paypal').checked === true) {
document.getElementById('paypal').checked = false;
document.getElementById('paypal').value='no';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
if (document.getElementById('paypal').checked === false) {
document.getElementById('paypal').checked = true;
document.getElementById('paypal').value='yes';
var vv=document.getElementById('paypal').value;
console.log(vv);
}
}
function chbxfb(objfb)
{
var that = objfb;
(objfb);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
function chbxtw(objtw)
{
var that = objtw;
(objtw);
if(document.getElementById(that.id).checked === true) {
document.getElementById(that.id).checked = false;
document.getElementById(that.id).value='no';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
if (document.getElementById(that.id).checked === false) {
document.getElementById(that.id).checked = true;
document.getElementById(that.id).value='yes';
var vv=document.getElementById(that.id).value;
console.log(vv);
}
}
The objpp was my attempt at another method but just does the same thing...
p.s if i just didnt use jscript and just had the html, would the value not be valid if the checkbox was not clicked or would the value still be sent...
iv just fond this..
How to change the value of a check box onClick using JQuery?
states that the value wont be sent if the box is unchecked... But then how do i know after post what has been clicked.... will i receieve a not isset($_POST['paypal']) or an empty($_POST['paypal'])
I imagine your checkboxes begin with no check inside them or .checked === false, but when you call your function chbxpp(), it looks to see if your .checked property === true and if so it sets it back to false. The click event already changes the checkbox's .checked property for you, no need to do it in your code.
//If the checkbox is checked, set it to not checked...???
//But the problem is, the click event just set the .checked property to true
//so setting it back to false makes it like it never happened.
if(document.getElementById('paypal').checked === true) {
//document.getElementById('paypal').checked = false; //This part is a no-no
document.getElementById('paypal').value='yes';
}else{
document.getElementById('paypal').value='no';
}
Adding to Ryan Wilson's answer, set your cbx's initial value to false. (Also check the format of the cbx - the closing tag.)
<input type="checkbox" id="paypal" name="paypal1" value="false" onchange="chbxpp();" />
function chbxpp() {
// the cbx starts false. when it is clicked for the first time it
// becomes true.
if (document.getElementById('paypal').checked) {
// you don't need this.
//document.getElementById('paypal').checked = true;
document.getElementById('paypal').value = 'yes';
var vv = document.getElementById('paypal').value;
console.log(vv);
} else {
// you also don't need this.
//document.getElementById('paypal').checked = false;
document.getElementById('paypal').value = 'no';
var vv = document.getElementById('paypal').value;
console.log(vv);
}
}
Why are my conditional statements not working properly? I want to display bothe error messages at the same time.
function validate() {
if (firstName.value == "") {
document.getElementById('error').innerHTML = "*Field is empty";
return false;
} else if (lastName.value == "") {
document.getElementById('errorTwo').innerHTML = "*Field is empty";
return false;
} else {
return true;
}
}
<form name="form" action="action.php" method="post" onsubmit="return validate()">
<div class="wrapper">
<span>Name</span>
<br>
<input type="text" name="firstName" id="firstName" placeholder="First Name" onfocus="this.placeholder=''" onblur="this.placeholder='First Name'" />
<label id="error"></label>
<br>
<input type="text" name="middleName" id="middleName" placeholder="Middle Name (optional)" onfocus="this.placeholder=''" onblur="this.placeholder='Middle Name (optional)'" />
<input type="text" name="lastName" id="lastName" placeholder="Last Name" onfocus="this.placeholder=''" onblur="this.placeholder='Last Name'" />
<label id="errorTwo"></label>
<br>
<br>
</div>
Your conditional statements are working correctly, your understanding of them is a little off though.
An if / else if statement will stop running when a condition is matched, so if firstName.value is empty, then that if statement will be matched and the code will exit there and not evaluate the rest of the conditions.
You want to use independent conditional statements for each test, and instead of returning either true or false, set a variable to true or false and return that after the conditional checks.
So...
function validate()
{
var valid = true;
if(firstName.value=="")
{
document.getElementById('error').innerHTML="*Field is empty";
valid = false;
}
if(lastName.value=="")
{
document.getElementById('errorTwo').innerHTML="*Field is empty";
valid = false;
}
return valid;
}
Just a note on the code itself, the above comments are mainly correct, if you post your entire code, you'll probably get more helpful responses. Also, you can eliminate the =="" part of the checks and just test the value of the variable as an empty string evaluates to false.
Don't chain the validations together with if-else otherwise if the first name validation fails, then you will never check the last name validation.
Help yourself by quickly creating a JsFiddle :-)
Here it is:
http://jsfiddle.net/23tnpve4/1/
You will easily see some issues by trying:
As others mentioned, missing brackets etc
As others mentioned, if the first test fails the other fields are not checked so errors can by corrected only step by step.
There is no code that refreshes your error DIVs. In a new form check, the error fields have to be cleared first. Checking forms are cycles with several possible start statuses.
Try to collect the status of fields in an array and work them later, something like this:
window.validate = function()
{
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
// Clear
firstName.val('');
lastName.val('');
// Check
var errorNames = [];
if(firstName.value=="")
{
errorNames.push('firstName');
}
if(lastName.value=="")
{
errorNames.push('lastName');
}
// Inform
for (var i=0; i<errorNames.length; i++) {
document.getElementById(errorNames[i]).innerHTML="*Field is empty";
}
// Return value
return errorNames.length == 0;
}
The concept of this code will work more intuitively. I haven't checked it against typos, it is a draft, but I do hope it will help you.
I have a problem with validating the form in function validate() method. This line of code:
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
is being skipped because one or both of the conditions are false, but I'm not sure which one and as well as if the condition is proper to execute. I was thinking that radios[i].value == "yes" will correspond to the value attribute of that input radio button (In other words, the correct answer regarding that question).
When the submit button is clicked, I simply want javascript to tell me whether it's correct or not and to check if the radio button is checked.
Problem: I checked in the radio button, when submit button is clicked the alert for Please make sure you answer every question pops up 3 times and after that displays that I have the correct answer.
Here's the full code:
JavaScript:
// called when "Take Quiz" button is clicked
function takeQuiz()
{
// hide the intro
document.getElementById('intro').style.display = 'none';
// display the quiz
document.getElementById('message').style.overflow = 'auto';
document.getElementById('quiz').style.visibility = 'visible';
document.getElementById('gl_banner').style.display = 'block';
document.getElementById('gl_banner').style.visibility = 'visible';
}
//document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz()
{
var radios; // access elements by object name (DOM)
var i; // int variable
var right; // boolean variable to determine correct answer
radios = document.getElementById('question1').getElementsByTagName('input');
/*radios = document.getElementById('question2').getElementsByTagName('input');
radios = document.getElementById('question3').getElementsByTagName('input');
radios = document.getElementById('question4').getElementsByTagName('input');
radios = document.getElementById('question5').getElementsByTagName('input');*/
right = true;
// loop to check each radio button for validation
for(i = 0; i < radios.length; i++)
{
if(radios[i].value == "yes" && radios[i].checked == true) //DEBUG INFO: skips this step to else.
{
right = true;
}
else if(radios[i].checked == false)
{
right = false;
alert("Please check to make sure you have answered every question.");
}
}
if(right)
{
alert("You have answered correctly!");
}
else
{
alert("Wrong answer");
}
}
HTML Code:
<div id="message" style="overflow:hidden;"><div id="intro">Why not go ahead and take the quiz to test your knowledge based on what you've learned in Smartphone Photography.
There are only 5 questions surrounding the content of this site.
<br/>
<button id="takeQuiz" type="button" name="name" onclick="takeQuiz()" style="cursor:pointer;">Take Quiz!</button></div>
<div id="gl_banner" style="display:none; visibility:hidden;">Good Luck! :)</div>
<form id="quiz" action="#" method="post" style="visibility:hidden;" autocomplete="off">
<!--QUIZ-->
<h3>1. How many percent of modern camera phones use CMOS?</h3>
<div id="question1">
<input type="radio" name="question-1-answers" id="question-1-answers-A" value="A" />
<label for="question-1-answers-A">A) 20%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-B" value="B" />
<label for="question-1-answers-B">B) 80%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-C" value="C" />
<label for="question-1-answers-C">C) 50%</label>
<br/>
<input type="radio" name="question-1-answers" id="question-1-answers-D" value="yes" />
<label for="question-1-answers-D">D) 90%</label>
</div>
**Edited for a pure javascript solution.
I got the function to get the select value from this post.
I don't think you need to do a loop here, as you only actually need to check one value- the value of the checked radio.
At the moment your looping through all the radios, so you'll always get three wrong answers.
**Edited again to fix some code errors. I have tested the following, it is working for me.
function getRadioValue(name) {
var group = document.getElementsByName(name);
for (var i=0;i<group.length;i++) {
if (group[i].checked) {
return group[i].value;
}
}
return '';
}
document.getElementById('submit').onclick = validateQuiz; //calls the function "validateQuiz" when submit button is clicked
// check for validation in the quiz
function validateQuiz(){
right = true;
radio = getRadioValue("question-1-answers");
if(!radio.length) {
right = false;
alert("Please check to make sure you have answered every question.");
return;
}
if(radio == 'yes')
{
alert("You have answered correctly!");
}
else {
right = false;
alert("Wrong answer");
}
}
I am using checkboxes whose values is coming from database. Its name is same but name is fetching like:
<input type="checkbox" id="chkBankServices" name="<%=bs.getServiceID()%>">
<%=bs.getServiceDesc()%>
through this i am getting the values from the database.
Now i have to validate that at least one checkbox should be selected..
If any one can help me i shall be thankful to u.
If i am giving like this the javascript code:
var services = document.getElementsById( 'chkBankServices' );
if(!(services[0].checked) &&
!(services[1].checked) &&
!(services[2].checked) &&
!(services[3].checked) &&
!(services[4].checked) &&
!(services[5].checked) &&
!(services[6].checked) &&
!(services[7].checked) &&
!(services[8].checked))
{
alert( "Please select at least one service to submit." );
return false;
}
It's not giving any alert message.
Is anything wrong in that.
Plz help me...
Thanks in advance
in jQuery :
alert( $("#chkBankServices input[type=checkbox]:checked").length > 0 );
Try this:
var services = document.getElementById( 'chkBankServices' );
var checkboxes = services.getElementsByTagName('input');
var checked = false;
for (var i=0,i0=checkboxes.length;i<i0;i++)
if (checkboxes[i].type.toLowerCase()=="checkbox")
{
if (checkboxes[i].checked) checked = true;
}
and then:
if (!checked)
{
alert('Not checked');
return false;
}
There is no getElementsById method, since there should only be one element with a given id. Perhaps you meant to use getElementsByName? This allows multiple elements to be returned.
As this is really a client side issue, it would help if you could post a sample of the generated HTML, and we can guide you further.
Have you checked the rendered source to make sure your checkboxes are being given the expected names?
I don't know if this will help you with your specific problem, but your code would be easier to read if you avoided the massive if block and used a loop instead:
var checked = false;
for(var i=0;i<services.length;i++){
if(services[i].checked){
checked = true;
}
}
if(!checked){
alert( "Please select at least one service to submit." );
return false;
}
Looking at your code, I'm betting you have that checkbox in a repeater of some sort and are creating multiple checkboxes with the same ID which is invalid html. I would wrap it in a div/span or something with an id like below:
if (!isSomethingChecked()) {
alert( "Please select at least one service to submit." );
return false;
}
function isSomethingChecked() {
var parent = document.getElementById("chkBankServices");
for (var child in parent.childNodes) {
var node = parent.childNodes[child];
if (node && node.tagName === "INPUT" && node.checked) {
return true;
}
}
return false;
}
I assumed the HTML looks like :
<div id="chkBankServices">
<input type="checkbox" id="Checkbox1" />
<input type="checkbox" id="Checkbox2" checked="checked"/>
<input type="checkbox" id="Checkbox3" checked="checked"/>
<input type="checkbox" id="Checkbox4" />
<input type="checkbox" id="Checkbox5" />
<input type="checkbox" id="Checkbox6" />
<input type="checkbox" id="Checkbox7" />
</div>