Am having problems with my code when submitting to a form. If nothing is entered in the textbox, then the correct error comes up, but when there are valid entries for the Radio Button responses, it still displays an error saying 'Please select a score' and such like when there is a score selected.
I can't seem to see what I have entered wrong.
All the best
CP
<form name="promoForm2" method=post enctype=multipart/form-data action=reactsubmit.php onSubmit="return validateForm();">
<ul class=mainForm id="mainForm_1">
<SCRIPT type=text/javascript>
function validateForm()
{
var x=document.forms["promoForm2"]["DJcomment"].value;
if (x==null || x=="")
{
alert("Please enter a comment.");
return false;
}
var x=document.forms["promoForm2"]["score"].value;
if (x==null || x=="")
{
alert("Please enter a score for the track.");
return false;
}
var x=document.forms["promoForm2"]["FavMix"].value;
if (x==null || x=="")
{
alert("Please select your favourite mix.");
return false;
}
}
</SCRIPT>
<table border='0'><tr><td>Support: </td><td><input type="radio" name="DJsupport" value="Yes">Yes<input type="radio" name="DJsupport" value="No">No</td></tr>
<tr><td>Favourite Mix: </td><td><input type="radio" name="FavMix" value="Enemy (Original Mix)">Enemy (Original Mix)</td></tr>
<tr><td></td><td><input type="radio" name="FavMix" value="Enemy (Original Mix)">Enemy (Original Mix)</td></tr>
<tr><td></td></tr><tr><td>Score: </td><td><input type="radio" name="score" value="1">1<input type="radio" name="score" value="2">2<input type="radio" name="score" value="3">3<input type="radio" name="score" value="4">4<input type="radio" name="score" value="5">5<input type="radio" name="score" value="6">6<input type="radio" name="score" value="7">7<input type="radio" name="score" value="8">8<input type="radio" name="score" value="9">9<input type="radio" name="score" value="10">10<td></tr><tr><td>Comment: (Required) </td><td><textarea name="DJcomment" rows="5" cols="40"></textarea></td></tr>
<tr><td></td><td><p class="mainForm"><input id="saveForm" class="mainForm" type="submit" value="Submit Reaction" /></td></tr></li></form>
</html>
To check the value of your radio buttons check their checked properties.
You'll need to check all radio buttons of a certain name in order to determine whether one was selected for its group.
function checkRadios(group) {
for (var i = 0; i < group.length; i++) {
if (group[i].checked) {
return true;
}
}
return false;
}
function validateForm() {
var x=document.forms["promoForm2"]["DJcomment"].value;
if (x == null || x == "") {
alert("Please enter a comment.");
return false;
}
if (!checkRadios(document.forms["promoForm2"]["score"])) {
alert("Please enter a score for the track.");
return false;
}
if (!checkRadios(document.forms["promoForm2"]["FavMix"])) {
alert("Please select your favourite mix.");
return false;
}
}
Live demonstration here.
document.forms["promoForm2"]["score"] is an array of input elements that you will need to iterate through to check if any one is checked.
var x=document.forms["promoForm2"]["FavMix"];
var pass=false;
for(var i=0;i<x.length;i++){
if (x[i].checked==true) {
pass=true;
break;
}
}
if(pass==false){
alert("Please select your favourite mix.");
return false;
}
See my JSFiddle.
Related
function validate()
{
var payment = checkRadio();
if (payment == false)
{
alert("Please select one button")
}
}
function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
else
{
return false;
}
}
}
The html code below creates the radio buttons for the client to select one of the payment methods
<P> Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
</P>
<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
My problem is that when I execute this code and run it on chrome nothing happens. If someone could spot out where about I went wrong I would really appreciate it.
You need to surround your html code with <form>
<form>
Payment Options:
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
<INPUT TYPE="button" VALUE=" SUBMIT " onClick="validate()">
</form>
And in your javascript change the checkRadio to:
function checkRadio()
{
var payment = document.getElementsByName('payment');
var paymentType = '';
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
console.log(payment[i].value)
paymentType = payment[i].value;
}
}
return paymentType != '' ? true : false;
}
JSFiddle: https://jsfiddle.net/ttgrk8xj/16/
In your code you are checking only the first element is checked because you are returning from function in first iteration.
function checkRadio()
{
var payment = document.getElementsByName("payment");
for(i = 0; i < payment.length; i++)
{
if(payment[i].checked)
{
return true;
}
}
return false;
}
I have a register form with 2 fields includes random int and a result input field for the answer
there's a Javascript code to check fields are not empty when submitting
I'm trying also to calculate the 2 fields and compare it with the result value
Here's the HTML :
<form method="post" id="contactForm" enctype="multipart/form-data" name="q_sign">
<input type="text" name="q_name" id="senderName"/>
<input type="text" name="q_mail" id="senderEmail" />
<input name="val1" type="text" disabled id="val1" value="php random value1" readonly="readonly" />
<input name="val2" type="text" disabled id="val2" value="php random value2" readonly="readonly" />
<input type="text" name="total" id="total" />
<input type="submit" id="sendMessage" name="sendMessage" value="Register" onClick="return check_data(this.form)" />
Javascript part :
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if(document.q_sign.q_name.value==''){
alert("please enter your name");
return false;
}else if(document.q_sign.q_mail.value==''){
alert("please enter your email");
return false;
}else if(document.q_sign.total.value!=(val1+val2)){ //Issue is here
alert("wrong answer");
return false;
}else{
return true;
}}
maybe this is your expect below
function check_data(form) {
var val1 = (document.q_sign.val1.value);
var val2 = (document.q_sign.val2.value);
if (document.q_sign.total.value != (eval(val1) + eval(val2))) {
alert("wrong answer");
return false;
} else {
return true;
}
}
I have a Form With Multiple Values For A Common Field "service". I have created an option "Other" For selection. And I want to validate with javascript input field next to "other" option.
Code is as follows
<label for="service" style="font-size:15px; vertical-align:top;">Service You Want*</label>
<input type="checkbox" name="service[]" id="Complete new set up " value="Complete new set up ">Complete new set up<br>
<input type="checkbox" name="service[]" id="Standardization" value="Standardization ">Standardization<br>
<input type="checkbox" name="service[]" id="Training" value="Training">Training <br>
<input type="checkbox" name="service[]" id="Trouble shooting " value="Trouble shooting ">Trouble shooting <br>
<input type="checkbox" name="service[]" id="Addition of new techniques" value="Addition of new techniques">Addition of new techniques<br>
<input type="checkbox" name="service[]" id="Hands on training" value="Hands on training">Hands on training<br>
<input type="checkbox" name="service[]" id="Seminars & Workshops" value="Seminars & Workshops">Seminars & Workshops<br>
<input type="checkbox" name="service[]" id="Preparations of documents" value="Preparations of documents ">Preparations of documents <br>
<input type="checkbox" name="service[]" id="Other" onclick="enable_text(this.checked)" value="other" >Other
<input type="text" name="other_text"><br>
For "Other" option, Input Text Field get Enabled if "other" options is checked.
working javascript used to enable input field is :
<script>
function enable_text(status)
{
status=!status;
document.formname.other_text.disabled = status;
}
</script>
javascript used To select atleast one service is working and it is as follows:
<script>
var chks = document.getElementsByName('service[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert("Please Select At Least One Service.");
return false;
}
</script>
But I am not getting how to validate input field if "Other" option from checkboxes is selected.
Try Following javascript :
<script>
var chks = document.getElementsByName('service[]');
var hasChecked = false;
for (var i = 0; i < chks.length; i++)
{
if (chks[i].checked)
{
hasChecked = true;
break;
}
}
if (hasChecked == false)
{
alert("Please Select AtLeast One Service.");
return false;
}
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
if (document.getElementById("Other").checked && isBlank(document.getElementsByName('other_text').value)) {
alert("Please Enter Details ABout Other Services You Want......... ");
document.contactus.other_text.focus();
return false;
}
</script>
I'm using http://www.somacon.com/p143.php javascript for radio buttons to change the submit onclick location.href depending on which radio button is selected. But I think I may have an issue with my syntax as the button isn't working properly (I don't think it is pulling the value from the radio buttons properly). Thanks in advanced!
Here is the code:
<head>
<script type="text/javascript">
<!--
// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if(!radioObj)
return;
var radioLength = radioObj.length;
if(radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for(var i = 0; i < radioLength; i++) {
radioObj[i].checked = false;
if(radioObj[i].value == newValue.toString()) {
radioObj[i].checked = true;
}
}
}
//-->
</script>
</head>
<body>
<form name="radioExampleForm" method="get" action="" onsubmit="return false;">
<p><label for="number0"><input type="radio" value="http://www.google.com" name="number" id="number0"> Zero</label>
<label for="number1"><input type="radio" value="http://www.ebay.com" name="number" id="number1"> One</label>
<label for="number2"><input type="radio" value="http://www.gamestop.com" name="number" id="number2"> Two</label>
<label for="number3"><input type="radio" value="http://www.amazon.com" name="number" id="number3"> Three</label>
<label for="number4"><input type="radio" value="http://www.usatoday.com" name="number" id="number4"> Four</label>
<p>
<input type="button" onclick="location.href='+getCheckedValue(document.forms['radioExampleForm'].elements['number']);" value="Show Checked Value">
ORIGNAL SUBMIT CODE THAT MADE AN ALERT BOX RATHER THAN location.href = <input type="button" onclick="alert('Checked value is: '+getCheckedValue(document.forms['radioExampleForm'].elements['number']));" value="Show Checked Value">
</form>
</body>
It's just a syntax error.
Change it to:
onclick="window.location.href = (getCheckedValue(document.forms['radioExampleForm'].elements['number']));"
I want to avoid using a for loop to validate a set of radio buttons. I know that its possible to use their boolean value to do this I just cannot seem to execute it. Is there a better way to do this?
Here are my buttons:
<form method="post" name="newUser" onsubmit="return proc()">
First name:<br />
<input type="text" id="fName" /><br />
<div id="first_name_error"></div>
Last name:<br />
<input type="text" name="lName" /><br />
<div id="last_name_error"></div>
E-mail address:<br />
<input type="text" name="eMail" /><br />
<div id="email_error"></div>
Gender:<input type="radio" name"sex" value="male" />Male
<input type="radio" name="sex" value="female" />Female<br />
<div id="gender_error"></div>
Here is my JS:
function proc(){
var errmsg = "";
if (document.forms["newUser"]["fName"].value == "")
{
document.getElementById('first_name_error').innerHTML = "*This field is required";
document.getElementById('first_name_error').style.color = "red";
}
if (document.forms["newUser"]["lName"].value == "")
{
document.getElementById('last_name_error').innerHTML = "*This field is required";
document.getElementById('last_name_error').style.color = "red";
}
if (document.forms["newUser"]["eMail"].value == "")
{
document.getElementById('email_error').innerHTML = "*This field is required";
document.getElementById('email_error').style.color = "red";
}
if (document.forms["newUser"].sex == false)
{
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
}
return false;
}
I think you'd better assign two ids to two radio buttons (radbtnMale, radbtnFemale for example)
Then check:
if (document.getElementById("radbtnMale").checked == false && document.getElementById("radbtnFemale").checked == false) {
document.getElementById('gender_error').innerHTML = "*Please select gender";
document.getElementById('gender_error').style.color = "red";
} else {
//
}
Try this (jQuery):
if($('input[name=n]:checked').length==0){
//error
}else{
//OK
}