Using Javascript form validation in WordPress - Firefox issues - javascript

I have been struggling for a while to get javascript to validate a WordPress based HTML form which uses radio buttons. I finally came up with a solution with was a bit long-winded but worked - at least in IE and Chrome - however, it doesn't work in Firefox (which suggests my code is a bit sloppy). I think my radio button reference is the issue. Can anyone help with what I have done wrong - apart from use an inefficient approach for validation :-)?
A simplified version of my form:
<script>
function validateForm()
{
var aa=document.forms["personalise"]["motivation"]["1a"];
var ab=document.forms["personalise"]["motivation"]["1b"];
var ac=document.forms["personalise"]["motivation"]["1c"];
var ad=document.forms["personalise"]["motivation"]["1d"];
var ae=document.forms["personalise"]["motivation"]["1e"];
if (!(aa.checked == true || ab.checked == true || ac.checked == true || ad.checked == true || ae.checked == true))
{
alert("Question 1 must be completed");
return false;
}
}
</script>
<form name="personalise" action="insertdatatest.php" onsubmit="return validateForm()" method="post">
1. Are you seriously planning to quit </b>:
<input id="1a" type="Radio" title="" name="motivation" value="1" /> Within the next 2 weeks
<input id="1b" type="Radio" title="" name="motivation" value="2" /> Within the next 30 days
<input id="1c" type="Radio" title="" name="motivation" value="3" /> Within the next 3 months
<input id="1d" type="Radio" title="" name="motivation" value="4" /> No, I am not currently planning to quit
<input id="1e" type="Radio" title="" name="motivation" value="5" /> I have already quit
<input type="submit" value = "Submit">
</form>
I am a real newbie at web development, so any help would be much appreciated.

Thanks again TheDeadMedic for your help. Actually I found a slightly different way of doing it which worked in all three browsers which was set up for multiple radio button questions (hence the blOK entries). In case it is useful to any others, the code is below. Flix.
<script>
function validateForm() {
var inputs;
var i;
var blOK;
blOK = false;
inputs = document.getElementsByName( "motivation" );
for (i=0;i<inputs.length;i++)
{
if ( inputs[i].checked ) {
blOK = true ;
break ;
}
}
if (!blOK)
{
alert( "Question 1 must be completed" );
return false;
}
</script>

Here's a cleaner way of doing things:
function validateForm() {
var inputs = document.getElementsByName( "motivation" );
for ( var i = 0; i < inputs.length; i++ ) {
if ( inputs[i].checked ) return true;
}
alert( "Question 1 must be completed" );
return false;
}

Related

How to use if condition in document.getelementbyname in javascript

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.

validatin script for radio button not Working

I am getting errors. The script is not working. Help
thanks in advance.
I want to check if all my set of radio buttons are checked when button next is click.
other ways of doing this also are welcome
<div class="qheader">
9) What's the world's most widely spoken language?</div>
<div class="qselections">
<input type="radio" value="a" name="question9">a) English<br>
<input type="radio" value="b" name="question9">b) Spanish<br>
<input type="radio" value="c" name="question9">c) Mandarin<br>
<input type="radio" value="d" name="question9">d) French<br>
</div><br>
<div class="qheader">
10) Which continent is host to the most countries in the world?</div>
<div class="qselections">
<input type="radio" value="a" name="question10">a) Asia<br>
<input type="radio" value="b" name="question10">b) Africa<br>
<input type="radio" value="c" name="question10">c) Europe<br>
</div>
</div>
<input type="button" value="Next" name="B3" onclick="showdesc()">
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
});
</script>
function clicked() {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
}
JSFiddle
I reproduced your problem with slight modifications, works well for me. I guess it's just a syntax error in the portion of your code, not present in the fiddle. Cross check and let me know.
Try and modify your click call, make it direct like in the fiddle.
//try this script
if(!$(this).find("input[name=radio]").is(':checked')){
alert("hi");
}

How do I properly validate the form using input radios?

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");
}
}

How to retrieve the value from a radio button in javascript?

Ok, I've checked a lot of other answers but the solutions posted there are beyond the scope of the class I am taking. IE we haven't discussed how to do it that way.
Anyways, I'm simply trying to get the value from a radio button here is my html code and my javascript.
<script type="text/javascript">
function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
</script>
and the actual button looks like this in my html code.
Milwaukee: ($20) <input type="radio" name="radCity" value="20" />
When I alert(arrivalcity); all I get is NaN. I don't understand why, shouldn't it return the string 20??
Allow me to clarify. I have 3 different city choices. I have edited it to show exactly what I have when I begin my form.
<form name="reservations">
<p>First Name: <input type="text" name="txtFirstName" />
Last Name: <input type="text" name="txtLastName" /></p>
<span style="font-weight:bold;">Arrival City:</span><br />
Milwaukee: ($20) <input type="radio" name="radCity" value="20" /><br />
Detriot: ($35) <input type="radio" name="radCity" value="35" /><br />
St. Louis: ($40) <input type="radio" name="radCity" value="40" />
I need to get the value from whatever one is selected. I can't hardcode it into my script.
This function will do what you want, through the querySelector method:
function selectedRadio(){
var selValue = document.querySelector('input[name="radCity"]:checked').value;
alert(selValue);
}
JSFiddle
Reference
Do you have a form named reservation in your body?
It will work like this:
<form name="reservations">
<input type="radio" name="radCity" value="20" />
</form>
​function bookTrip()
{
var arrivalcity;
arrivalcity = document.reservations.radCity.value;
alert(arrivalcity);
}
See it running here: http://jsfiddle.net/eBhEm/
​
However, I would prefer this instead:
<input type="radio" id="radCity" value="20" />
And then use getElementById
function bookTrip()
{
var arrivalcity;
arrivalcity = document.getElementById("radCity").value;
alert(arrivalcity);
}
See this running on jsfiddle.
function bookTrip() {
var arrivalcity= document.reservations.radCity;
for (var i = 0, iLen = arrivalcity.length; i < iLen; i++) {
if (arrivalcity[i].checked) {
alert(arrivalcity[i].value);
}
}
}
i believe this should help.
see it working here
http://jsfiddle.net/eBhEm/24/
You can use querySelector in browsers that support it, but not all browsers in use do. The old fashioned (reliable, robust, works every where) method is to loop over the collection to find the one that is checked:
function getValue() {
var buttonGroup = document.forms['reservations'].elements['radCity'];
// or
// var buttonGroup = document.reservations.radCity;
// Check for single element or collection, collections don't have
// a tagName property
if (typeof buttonGroup.tagName == 'string' && buttonGroup.checked) {
return buttonGroup.value;
} else {
// Otherwise, it's a collection
for (var i=0, iLen=buttonGroup.length; i<iLen; i++) {
if (buttonGroup[i].checked) {
return buttonGroup[i].value;
}
}
}
}
Note that the test between an HTMLCollection and DOM element uses a property that DOM elements must have but an HTMLCollection should not have, unless a member of the collection has a name of "tagName".

How do I make sure that at least one checkbox is checked?

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>

Categories

Resources