trying to make validation on radiobutton - javascript

I have a problem with validation on radiobutton.
I did try by having a loop to check if the radiobutton is checked or not but it turns out give delivery flag still true
var optDelivery=document.getElementsByName("f__deliver");
var deliveryFlag=false;
for (var i=0;i<optDelivery.length;i++){
if (optDelivery.checked){
deliveryFlag=true;
}
}
if (deliveryFlag===true){
alert("AAAA");
optDelivery.style.background="white";
optDelivery.style.color="#000";
} else{
alert("A");
optDelivery.style.background="#DE8971";
optDelivery.style.color="#FFE9D6";
optDelivery.focus();
return false;
}

You need to access each input radio by its index, also the condition needs to be inside the loop
Also instead of return falseset deliveryFlag to false
const optDelivery = document.getElementsByName("f__deliver");
for (let i = 0; i < optDelivery.length; i++) {
const deliveryFlag = optDelivery[i].checked ? true : false;
if (deliveryFlag === true) {
console.log("AAAA");
optDelivery[i].style.background = "white";
optDelivery[i].style.color = "#000";
} else {
console.log("A");
optDelivery[i].style.background = "#DE8971";
optDelivery[i].style.color = "#FFE9D6";
optDelivery[i].focus();
}
}
<input type="radio" name="f__deliver" id="">
<input type="radio" name="f__deliver" id="">
<input type="radio" name="f__deliver" id="">
<input type="radio" name="f__deliver" id="" checked>
<input type="radio" name="f__deliver" id="">

var optDelivery=document.getElementsByName("f__deliver");
var deliveryFlag=false;
for (var i=0;i<optDelivery.length;i++){
if (optDelivery[i].checked){
deliveryFlag=true;
}
if (deliveryFlag===true){
alert("AAAA");
optDelivery[i].style.backgroundColor="white";
optDelivery[i].style.color="#000";
optDelivery[i].focus();
}else{
alert("A");
optDelivery[i].style.backgroundColor="#DE8971";
optDelivery[i].style.color="#FFE9D6";
}
deliveryFlag = false;
}
<input type='radio' name = 'f__deliver'>
<input type='radio' name = 'f__deliver' checked>
<input type='radio' name = 'f__deliver'>

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 " />

Check(validate) radio buttons with an if else if true no alert if not checked alert must be check

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

check for empty radio input

I want to check if the user selects a radio button. I have coded this:
HTML
<form action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
//etc
<button type="submit" class="myButton" onclick="sendSuccess()">Submit</button>
</form>
JS
function sendSuccess(){
var len = document.formRate.ratingInput1.length;
var flag;
for(i=0; i<len; i++){
if (document.formRate.ratingInput[i].checked){
flag = true;
}
else{
flag = false;
break;
}
}
if(flag === false){
console.log('noooooo');
return false;
}else{
console.log('yesssss');
}
}
But its not working.
You can do it with jQuery using Attribute Equals Selector [name="value"] to find radio button with same name and :checked to get only checked elements. You can use length to check if you get any checked radio button or not. The length will be zero of none of radio button is checked and will be greater then zero if one or more radio button is checked.
Live Demo
if($('[name=ratingInput1]:checked').length)
console.log('Yes');
else
console.log('No');
Working demo http://jsfiddle.net/cXPYQ/
Hope this fit your needs :)
Code
$("form").submit(function () {
var flag = true;
$(':radio').each(function () {
name = $(this).attr('name');
if (flag && !$(':radio[name="' + name + '"]:checked').length) {
alert(name + ' group not checked');
flag = false;
}
});
return flag;
});
try this
<form name="formRate" action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
<button type="submit" class="myButton" onclick="return sendSuccess();">Submit</button>
</form>
function sendSuccess(){
var flag = false;
var len = $('input:radio[name="ratingInput1"]:checked').size();
if(len == 0){
console.log('noooooo');
flag = false;
}else{
console.log('yesssss');
flag = true;
}
return flag;
}
Its a simple form with radio buttons, so all you need is give the form a name formRate, and no need for jQuery, the following will work
HTML
<form name="formRate" action="myServlet" method="post">
<input type="radio" id="rating-input-1-5" name="ratingInput1" value="5">
<input type="radio" id="rating-input-1-4" name="ratingInput1" value="4">
<input type="radio" id="rating-input-1-3" name="ratingInput1" value="4">
<button type="submit" class="myButton" onclick="return sendSuccess();">Submit</button>
</form>
Javascript
function sendSuccess() {
rating = document.forms["formname"]["ratingInput1"].value;
if(rating > 0){
console.log(rating);
}
else {
console.log('No rating');
}
return false;
}
var flag = $('[name="ratingInput1"]').is(':checked');
will return false if no radio with that name is chosen.

How to disable other checkbox on click of one check box?

I have a group of check boxes with same name, what I need is when I click any one of them, other checkboxes must get disabled. how should I apply Javascript over it?
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
<input type="checkbox" name="finallevelusers[]" value="1"/>
Please help...
You could do
$('input').attr('disabled',true);
...if you really need it. But you might be better off using radio buttons.
Try the demo
<script type="text/javascript">
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].checked !=true)
document.test.finallevelusers[i].disabled='true';
}
</script>
probably you want them enabled again when user uncheck the checkbox
for (i=0; i<document.test.finallevelusers.length; i++){
if (document.test.finallevelusers[i].disabled ==true)
document.test.finallevelusers[i].disabled='false';
}
<script type="text/javascript">
function disableHandler (form, inputName) {
var inputs = form.elements[inputName];
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.onclick = function (evt) {
if (this.checked) {
disableInputs(this, inputs);
}
else {
enableInputs(this, inputs);
}
return true;
};
}
}
function disableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = true;
}
}
}
function enableInputs (input, inputs) {
for (var i = 0; i < inputs.length; i++) {
var currentInput = inputs[i];
if (currentInput != input) {
currentInput.disabled = false;
}
}
}
</script>
</head>
<body>
<form name="aForm" action="">
<p>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
<label>
<input type="checkbox" name="finallevelusers[]" value="1">
</label>
</p>
</form>
<script type="text/javascript">
disableHandler(document.forms.aForm, 'finallevelusers[]');
</script>
Hope This solution helps you-
your DOM could be something like this :
<div class="checkboxes">
<input type="checkbox" name="sameCheck" class="checkbox" id="1" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="2" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="3" onchange="checkChange()">
<input type="checkbox" name="sameCheck" class="checkbox" id="4" onchange="checkChange()">
</div>
And your logic is this :
let checkbox = document.querySelectorAll('.checkbox')
let b = false;
function checkChange(){
b = !b
if(b){
for(let i = 0 ; i< checkbox.length; i++){
if(checkbox[i].checked === false){
checkbox[i].disabled = 'true';
}
}
}else{
for(let i = 0 ; i< checkbox.length; i++){
checkbox[i].removeAttribute('disabled');
}
}
}
Try code like this
<script>
function uncheck(){
for(var ii=1; ii<=4; ii++){
if(document.getElementById("q6_"+ii).checked==true){
document.getElementById("q6_"+ii).checked=false;
}
}
}
</script>

Categories