Input Field Validation If Adjoining Checkbox Is Checked - javascript

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>

Related

Validate radio button in javascript

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

Disable button if all checkboxes are unchecked

I have a list of checkboxes, and I need to disable my submit button if none of them are checked, and enable it as soon as at least one gets checked. I see lots of advice for doing this with just a single checkbox, but I'm hung up on getting it to work with multiple checkboxes. I want to use javascript for this project, even though I know there are a bunch of answers for jquery. Here's what I've got - it works for the first checkbox, but not the second.
HTML:
<input type="checkbox" id="checkme"/> Option1<br>
<input type="checkbox" id="checkme"/> Option2<br>
<input type="checkbox" id="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript:
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
I'd group your inputs in a container and watch that for events using addEventListener. Then loop through the checkboxes, checking their status. Finally set the button to disabled unless our criteria is met.
var checks = document.getElementsByName('checkme');
var checkBoxList = document.getElementById('checkBoxList');
var sendbtn = document.getElementById('sendNewSms');
function allTrue(nodeList) {
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].checked === false) return false;
}
return true;
}
checkBoxList.addEventListener('click', function(event) {
sendbtn.disabled = true;
if (allTrue(checks)) sendbtn.disabled = false;
});
<div id="checkBoxList">
<input type="checkbox" name="checkme"/> Option1<br>
<input type="checkbox" name="checkme"/> Option2<br>
<input type="checkbox" name="checkme"/> Option3<br>
</div>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
html
<input type="checkbox" class="checkme"/> Option1<br>
<input type="checkbox" class="checkme"/> Option2<br>
<input type="checkbox" class="checkme"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
js
var checkerArr = document.getElementsByClassName('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
for (var i = 0; i < checkerArr.length; i++) {
checkerArr[i].onchange = function() {
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
}
I guess this code will help you
window.onload=function(){
var checkboxes = document.getElementsByClassName('checkbox')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkbox"/> Option1<br>
<input type="checkbox" id="check2" class="checkbox"/> Option2<br>
<input type="checkbox" id="check3" class="checkbox"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Few suggestions
1.Always id should be unique. HTML does not show any error, if you give multiple objects with the same id but when you try to get it by document.getelementbyid it always return the first one,because getelementbyid returns a single element
when there is such requirement, you should consider having a classname or searching through the element name because getelementsbyclassname/tag returns an array
Here in the markup i have added an extra class to query using getelementsbyclassname
To avoid adding extra class, you can also consider doing it by document.querySelectorAll
check the following snippet
window.onload=function(){
var checkboxes = document.querySelectorAll('input[type=checkbox]')
var sendbtn = document.getElementById('sendNewSms');
var length=checkboxes.length;
for(var i=0;i<length;i++){
var box=checkboxes[i];
var isChecked=box.checked;
box.onchange=function(){
sendbtn.disabled=isChecked?true:false;
}
}
// when unchecked or checked, run the function
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check1" /> Option1<br>
<input type="checkbox" id="check2" /> Option2<br>
<input type="checkbox" id="check3" /> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Hope this helps
Something like this would do. I'm sure you can do it with less code, but I am still a JavaScript beginner. :)
HTML
<input type="checkbox" class="checkme" data-id="checkMe1"/> Option1<br>
<input type="checkbox" class="checkme" data-id="checkMe2"/> Option2<br>
<input type="checkbox" class="checkme" data-id="checkMe3"/> Option3<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
JavaScript
//keep the checkbox states, to reduce access to the DOM
var buttonStatus = {
checkMe1: false,
checkMe2: false,
checkMe1: false
};
//get the handles to the elements
var sendbtn = document.getElementById('sendNewSms');
var checkBoxes = document.querySelectorAll('.checkme');
//add event listeners
for(var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].addEventListener('change', function() {
buttonStatus[this.getAttribute('data-id')] = this.checked;
updateSendButton();
});
}
//check if the button needs to be enabled or disabled,
//depending on the state of other checkboxes
function updateSendButton() {
//check through all the keys in the buttonStatus object
for (var key in buttonStatus) {
if (buttonStatus.hasOwnProperty(key)) {
if (buttonStatus[key] === true) {
//if at least one of the checkboxes are checked
//enable the sendbtn
sendbtn.disabled = false;
return;
}
}
}
//disable the sendbtn otherwise
sendbtn.disabled = true;
}
var check_opt = document.getElementsByClassName('checkit');
console.log(check_opt);
var btn = document.getElementById('sendNewSms');
function detect() {
btn.disabled = true;
for (var index = 0; index < check_opt.length; ++index) {
console.log(index);
if (check_opt[index].checked == true) {
console.log(btn);
btn.disabled = false;
}
}
}
window.onload = function() {
for (var i = 0; i < check_opt.length; i++) {
check_opt[i].addEventListener('click', detect)
}
// when unchecked or checked, run the function
}
<input type="checkbox" id="check1" class="checkit" />Option1
<br>
<input type="checkbox" id="check2" class="checkit" />Option2
<br>
<input type="checkbox" id="check3" class="checkit" />Option3
<br>
<input type="submit" name="sendNewSms" class="inputButton" disabled="true" id="sendNewSms" value=" Send " />

Javascript form submission error

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.

Multiple Radio Buttons that change Submit onclick location.href...possible syntax error

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']));"

How to confirm a radio button selection with an alert box

So i have this code:
<html>
<head>
<title>Form</title>
<script type="text/javascript">
function showConfirmationDialog() {
var textbox = document.getElementById('textbox');
var location = document.getElementById('location');
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n');
}
function formfocus() {
document.getElementById('textbox').focus();
}
window.onload = formfocus;
var option;
</script>
</head>
<body>
Your name:
<input type="text" name="FirstName" id="textbox" <br><br/>
Your Address:
<input type="text" name="address" id="location" <br></br><br></br>
Choose your location:
<form name="Radio" id="destination" action="">
Bristol:
<input type="radio" name="selection" value="bristol" onClick="option=0">
London:
<input type="radio" name="selection" value="london" onClick="option=1">
Birmingham:
<input type="radio" name="selection" value="birmingham" onClick="option=2" />
</form>
<br></br> Click:
<input type="button" value="Submit" onclick="showConfirmationDialog();" /><br></br>
</body>
</html>
... This code basically represents a form for a user to fill in and at the end select one of three option provided via the radio buttons. What I wanted to find out was that how do I get the selection from one radio button which the user will need to select, displayed within the alert box after they press submit.
Something like this...
function getSelRadioValue()
for(i = 0; i< document.forms['Radio'].elements['selection'].length ; i++){
if(document.forms['Radio'].elements['selection'][i].checked == true)
return document.forms['Radio'].elements['selection'][i].value;
}
return null;
}
var selectedRadioValue = getSelRadioValue(); //use this variable in your alert.
if(selectedRadioValue == null)
alert("please select a destination");
else if(confirm("You have selected " + selectedRadioValue))
//deal with success
You need to loop through the selection radios to get the checked value:
var selection = document.Radio.selection;
var selectionResult = "";
for(var i = 0; i < selection.length; i++) {
if(selection[i].checked) {
selectionResult = selection[i].value;
}
}
alert('You chosen:'+'\n'+'\n'+'Name: '+textbox.value +'\n'+'Address: ' +location.value+'\n' + 'Location: '+selectionResult);

Categories