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;
}
Related
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 " />
This is what I have on the HTML side of things. I have a form with the id of products, a name of myForm, an action tag a method of get, and onsubmit returns the function validateForm(); I have a full fledged order form
<form id="products"name="myForm"action="FormProcessor.html"method="get"
onsubmit="return validateForm();">
<label for="payment">Payment Method?</label>
<input id="visa" name="credit_card" type="radio" value="Visa" />
<label for="visa">Visa</label>
<input id="masterCard" name="credit_card" type="radio"value="MasterCard" />
<label for="mastercard">MasterCard</label>
<input id="ae"name="credit_card"type="radio"value="American Express" />
<label for="americanexpress">American Express</label><br>
This is what I have on the js side of things, I am also trying to write it in vanilla js. I have not learned jQuery yet i am still new to programming. I am not sure why it is not alerting.
function validateForm() {
var p_form = document.getElementById("products");
p_form.addEventListener("submit", function(event) {
var payment_array = document.getElementsByName("credit_card");
for(var i = 0; i < payment_array.length; i++) {
if(payment_array[i].checked) {
selection_made = true;
break;
}
}
if(!selection_made) {
event.preventDefault();
alert("Payment Method must be selected.");
return false;
}
});}
Demo: http://jsfiddle.net/e4gfs67o/1/
Solution:
HTML:
<form id="products" name="myForm" action="FormProcessor.html" method="get">
<label for="payment">Payment Method?</label>
<input id="visa" name="credit_card" type="radio" value="Visa" />
<label for="visa">Visa</label>
<input id="masterCard" name="credit_card" type="radio" value="MasterCard" />
<label for="mastercard">MasterCard</label>
<input id="ae"name="credit_card" type="radio" value="American Express" />
<label for="americanexpress">American Express</label><br>
<button type='submit'>Submit</button>
</form>
Javascript:
var form = document.getElementById('products');
form.addEventListener('submit', function(event) {
var radios = document.getElementsByName('credit_card'),
len = radios.length,
i = 0,
selected = false;
for (; i < len; i++) {
if (radios[i].checked) {
selected = true;
break;
}
}
if (selected) {
return true;
} else {
event.preventDefault();
alert('Payment Method must be selected.');
return false;
}
});
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 would like to build a javascript so a user can choose only one option between the the mentioned below. Could you give me some pointers how to do this since I am a javascript noob.
Thank you!
This is the picture of the part of a menu
<td><label for="dock_books_search_visible_online"> Visible online?</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" /> </td>
<td><label for="dock_books_search_visible_online_yes"> Yes</label></td>
<td><input type="checkbox" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" /> </td>
<td><label for="dock_books_search_visible_online_no"> No</label></td>
For single selection from multiple options we use Radio Buttons not CheckBoxes.
You should use some thing like this.
<input type="radio" name="option" value="Yes" id="yes" />
<input type="radio" name="option" value="No" id="no" />
But still if you want to go the other way round, Just add the following script in your head tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(':checkbox').bind('change', function() {
var thisClass = $(this).attr('class');
if ($(this).attr('checked')) {
$(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$(this).attr('checked', 'checked');
}
});
});
</script>
Here is the fiddle for above.
Hope this helps.
This looks like a job for radio buttons, not checkboxes.
you got a point to use radio buttons any way here is the javascript solution
i used it in my project when there is search criteria and search result in data grid by
ajax having 13 records when i check one record it disables the rest
code for javascript enable disable check boxes jsfiddle
<form name="mainForm" method="GET">
Visible online?
<input type="checkbox" name="option" value="checkedVisibleOk" id="option" onclick="changeCheckBox();"/>
yes
<input type="checkbox" name="option" value="checkedVisibleNok" id="option" onclick="changeCheckBox();"/>
no
</form>
<script>
var serNoChecked="";
function changeCheckBox() {
try {
var max = document.mainForm.option.length;
var count = 0;
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == true) {
count++;
serNoChecked = i;
}
}
if (count == 1) {
for (var i = 0; i < max; i++) {
if (document.mainForm.option[i].checked == false) {
document.mainForm.option[i].disabled = true;
}
}
}
else if (count == 0) {
for (var i = 0; i < max; i++) {
document.mainForm.option[i].disabled = false;
}
}
if (null == max) return false;
if (count == 0) {
return true;
}
else if (count > 0) {
return false;
}
}
catch (e) {
alert(e.message);
}
}
</script>
Try using Radio Button's, Give them the same name to group them and only allow 1 to be selected:
<td>
<label for="dock_books_search_visible_online"> Visible online?</label>
</td>
<td>
<input type="radio" name="option" value="checkedVisibleOk" id="dock_books_visible_ok" />
</td>
<td>
<label for="dock_books_search_visible_online_yes"> Yes</label>
</td>
<td><input type="radio" name="option" value="checkedVisibleNok" id="dock_books_visible_nok" />
</td>
<td>
<label for="dock_books_search_visible_online_no"> No</label>
</td>
Check this JSFiddle.
Hi why are you using checkbox? Checkboxes are not for the functionality that you want. Radio buttons are exact what you want to use.
<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>
For further details look here
function toggle(chkBox, field) {
for ( var i = 0; i < field.length; i++) {
field[i].checked = false;
}
chkBox.checked = true;
}
<td>
<INPUT type="checkbox" name="xyz" onClick="toggle(this,document.myform.xyz);" value="${incident.incidentID}">
</td>
Use radio buttons and ensure that the name tag is consistent with all options and it'll automatically select just one w/o the need for additional code or JS.