How can I vaildate radio buttons? - javascript

How i put validation on check box?
Here is my code:
<script>
function Validate(){
var cntct = document.getElementById("contact").value;
if (cntct.value=="")
{
alert("Please select contact medium");
return false;
}
}
</script>
<input type="radio" name="contact" id="contact" value="SMS">
<label>SMS</label> <input type="radio" name="contact" id="contact" value="CALL">
<label>CALL</label> <input type="radio" name="contact" id="contact" value="EMAIL">
<label>EMAIL</label>
please help..

in case of checkboxes and radiobuttons, the element is checked when the "checked" property is true:
function Validate(){
var selectedValue = "";
var cntct = document.getElementsByname("contact");
for(var i=0;i<cntct.length;i++) {
if (cntct[i].checked)
{
selectedValue = cntct.value;
}
}
if(selectedValue == "") {
alert("Please select contact medium");
return false;
}
return true;
}
UPDATE
I just noticed that you have multiple elements with the same ID. This is not allowed, in such case the browser will return only the last element with that ID. You need to iterate over the elements with the same name and pick one with attribute checked. See the code above

Simple:
if(cntct == "")
{
}
The cntct variable is the value!

How i put validation on check box?
I presume you mean "how do I make sure one of the radio buttons is checked when the form is submitted" (supposing there is a form you haven't shown).
The simple way is to make one checkbox selected by default, then you know that one will always be selected and you don't have to check, e.g.
<input type="radio" name="contact" value="CALL" checked>
<input type="radio" name="contact" value="EMAIL">
The other way is to loop over the radio buttons when the form is submitted (or whatever event you decide to base the validation on) and make sure one is checked. e.g.
function checkButton() {
var nodes = document.getElementsByName('contact');
for (var i=0, iLen=nodes.length; i<iLen; i++) {
// If find a checked one, job's done
if (nodes[i].checked) return true;
}
// Otherwise, none were checked
return false;
}
There is an input type text with a name of contact, but it won't have a checked property so will be treated like an unchecked radio.

Please try this:
<script>
function SubmitIt()
{
if (document.forms.myform.elements.contact.value == "")
{
alert("Please select contact medium...");
}
}
</script>
<form name="myform" id="myform">
<input type="radio" name="contact" id="contact" value="SMS">
<label>SMS</label> <input type="radio" name="contact" id="contact" value="CALL">
<label>CALL</label> <input type="radio" name="contact" id="contact" value="EMAIL">
<label>EMAIL</label>
<button onclick="SubmitIt();">Submit</button>
</form>

Related

how to validate checkbox and radio button in jquery

I am unable to validate the checkbox and radio button. Actually i just need to insert validation for user at least select one thing weather checkbox or radio.
see my code. that's not working for me.
<script>
$(".submit").click(function(){
var checkBoxCount = $(".jobwork:checkbox:checked").length;
if($(".jobwork:checkbox:checked").length < 1 || ($("input[name=jobwork]:checked").length <= 0)){
alert("Please select atlease one jobwork");
return false;
};
})
http://api.jquery.com/prop/#entry-examples
$(".submit").click(function(){
var isChecked= $(".jobwork")[0].prop('checked');
if (!isChecked) {
alert("Please select atlease one jobwork");
return false;
};
})
You have to check whether the checkboxes has a prop called checked in them. It is available only if the checkbox is checked.
$(".submit").click(function(){
var checked = $(".jobwork").prop('checked');
if(!checked){
alert("Please select atlease one jobwork");
return false;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="jobwork" name="check">
<input type="checkbox" class="jobwork" name="check">
<input type="checkbox" class="jobwork" name="check">
<br>
<input type="button" class="submit" value="submit">

Uncheck a checkbox and another checkbox will untick

I have two checkboxes in a form. onclick if a checkbox called email is unchecked how can I get the other checkbox to also uncheck (if it is checked) ?
document.getElementById('email').onclick = function() {
if (!this.checked) {
!document.getElementById("other").checked;
} else {
// if not checked ...
}
};
Am I completey barking up the wrong tree? Any help appriciated
To synchronize the checking of the both at the same time you need just to use this.checked of the first clicked one on the checked attribute of the second one like :
document.getElementById("other").checked = this.checked;
NOTE : That will work on one way, what means the check will be synchronized just when you click on the first checkbox that you've attached the click event to.
document.getElementById('email').onclick = function() {
document.getElementById("other").checked = this.checked;
};
<input id="email" type="checkbox" /> CHECKBOX 1
<br>
<input id="other" type="checkbox" /> CHECKBOX 2
You can make it like :
<form id="test" action="#" method="post">
<div>
<input type="checkbox" name="check" id="check"/>
</div>
<div>
<input type="checkbox" name="check2" id="check2"/>
</div>
</form>
document.getElementById('check').onclick = function() {
if (!this.checked) {
document.getElementById("check2").checked = false;
} else {
// other logic ...
}};
Test it online on jsfiddle : https://jsfiddle.net/3dtq0w8x/
In your test code you are not setting the checked property of "other" to any value.
You are just reading its value, then inverting it (with !).
You could try:
document.getElementById("other").checked = false;
You can add event listener to email checkbox (which is a good practice) and then check if it is check or not and deal with the other checkbox according to that
For example
var ckb = document.getElementById('email')
ckb.addEventListener("click", function(e){
if(!e.target.checked)
document.getElementById('ot').checked = false;
})
<input type="checkbox" name="na" value="email" id="email">Email<br>
<input type="checkbox" name="na" value="other" id="ot">Other
This should help
function check() {
if(document.getElementById("email").checked){
document.getElementById("other").checked = true;
}else{
document.getElementById("other").checked = false;
}
}
HTML
<input type='checkbox' id='email' name='checkbox' onclick="check()" >email
<input type='checkbox' id='other' name='checkbox'>other

form action to toggle a function?

<form action="" method="get" >
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
I have the following radio form and when I hit submit, I would like it to toggle some function in my js script. However, if I do something like:
document.getElementById("start").addEventListener('click',function ()...
Nothing works. I think I need something for the action tag, but I can only find examples that link to other websites/pages, which isn't what I want. Is toggling a function possible to do using the forms?
Thanks!
You're on the right track:
document.getElementById("start").addEventListener('click', function(e) {
e.preventDefault();
console.log('start!!');
const selected = document.querySelector('input[name="gender"]:checked');
console.log('you selected: ' + (selected ? selected.nextSibling.textContent : 'null'));
// your code here
});
<form>
<input type="radio" name="gender" id="male_sub">male<br>
<input type="radio" name="gender" id="female_sub">female<br>
<input type="submit" value="Let's Start!" id="start"><br>
<form>
You don't need an action or a method attribute. Make sure to use e.preventDefault() to prevent the form from submitting (redirecting the page) if you want to handle the form's values yourself.
You can define the submit function on form tag using onsubmit, Also this solution is accurate if you have multiple form tags on the same page.
function submitForm(form, event) {
event.preventDefault();
var val;
var radios = form.elements['gender'];
// loop through list of radio buttons
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) { // radio checked?
val = radios[i].value; // if so, hold its value in val
alert(val);
break; // and break out of for loop
}
}
alert("nothing selected");
return false;
}
<form onsubmit="return submitForm(this,event)">
<label><input type="radio" name="gender" id="male_sub" value="male">male</label><br>
<label><input type="radio" name="gender" id="female_sub" value="female">female</label><br>
<input type="submit" value="Let's Start!" id="start"><br>
</form>

jQuery validation to ensure that at least one radiobutton value is true

I've a form that has two questions. The first question asks whether the product value is greater than a fixed certain amount and the second question asks if the product value is less than the fixed amount. When the user tries to submit the form, the form should be validated to confirm that at least one question has been answered as yes. If both questions are answered as no, the form valid property $("#form").valid() should be false and a div containing an error message should be displayed on the page. How can I achieve this using jQuery validation?
A simplified version of the form looks something like
<form id="billing" method="POST">
<div>
<label for "billAmountLess">Value is less than 1000</label>
<input id="billAmountLessY" name="billAmountLess" type="radio" required value="True">
<label for "billAmountLessY">Yes</label>
<input id="billAmountLessN" name="billAmountLess" type="radio" required value="False">
<label for "billAmountLessN">No</label>
</div>
<div>
<label for "billAmountMore">Value exceeds 1000</label>
<input id="billAmountMoreY" name="billAmountMore" type="radio" required value="True">
<label for "billAmountMoreY">Yes</label>
<input id="billAmountMoreN" name="billAmountMore" type="radio" required value="False">
<label for "billAmountMoreN">No</label>
</div>
<div id="errorDiv" style="display:none">Error!!!!
</div>
<div>
<input type="submit" value="Submit">
</div>
</form>
The jQuery validation that I'm trying is
$('#billing').validate({
rules: {
billAmountMore: {
equalTo: {
param: '#billAmountMoreY',
depends: function(element) {
$("errorDiv").show();
return $("#input[name='billAmountLess']:checked").val() == "false";
}
}
}
}
});
I've created a jsfiddle for this.
You can use this code
function validate(){
console.log($("input[name='billAmountLess']:checked").val());
console.log($("input[name='billAmountMore']:checked").val());
}
to retrieve the radio button value.
In your code this line:
return $("#input[name='billAmountLess']:checked").val() == "false";
should remove the "#" before 'input' as it's indicating the 'id' of an element. Maybe that's why it's not working.
Simple you can do this in custom validation function. Update your form tag -
<form id="billing" onsubmit="return validate();" method="POST">
Then -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function validate(){
var billLess = $("input[name='billAmountLess']:checked").val();
var billMore = $("input[name='billAmountMore']:checked").val();
if(billLess == "False" && billMore == "False"){
$("#errorDiv").show();
return false;
}
else{
return true;
}
}
</script>

Enable/disable a form element after checking radio button checked states

I have ten or so questions with radio buttons. They all need to be set to true, before a user can move on to another level. If and only if these ten questions have be answered to true, I'd like to have one of the elements on the form be enabled for further editing. This, I can do on the server side, but don't know how to do it in JavaScript. Any help? Much appreciated. Thanks.
<div>
<label> First Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
<div>
<label> Second Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][researched]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][researched]" type="radio" value="false" />No</label>
</div>
<div>
<label> Third Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
This code extends to several more of questions.
I've been able to select radios by doing so:
var first_ten = $(':radio[name="project[person_attributes][is_complete_and_works]"][value=true], :radio[name="project[person_attributes][researched]"][value=true], etc…);
Now, I have no idea how to iterate over each and when I click on each radio, whether yes or no, I'd like to see the result for the element to be enabled. Any thoughts much appreciated.
Something like the following will do the job:
<script type="text/javascript">
function proceed(form) {
var el, els = form.getElementsByTagName('input');
var i = els.length;
while (i--) {
el = els[i];
if (el.type == 'checkbox' && !el.checked) {
form.proceedButton.disabled = true;
return;
}
}
form.proceedButton.disabled = false;
}
</script>
<form onclick="proceed(this);">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="submit" name="proceedButton" disabled>
</form>
Note that this is considered bad design as if javascript is not available or enabled, the user can never click the button. Better to deliver the form in a useful state and the, when submitted, use script to validate that the buttons are all checked and cancel the submit if they aren't.
Then at the server you can also check the state and only show the next page if the current one passes validation. If it doesn't, return the user to the first page.
That way neither you or the user care if the script works or not, the page still functions. Of course it might be a better experience if the script does work, but at least the choice isn't binary and it also gives you a simple fallback to support a very wide array of browsers with minimal effort.
So a better solution is:
<form onsubmit="reurn validate(this);" ...>
...
</form>
Then in the function:
function validate(form) {
// if validateion fails, show an appropriate message and return false,
// if it passes, return undefined or true.
}
And always validate at the server since you really have no idea what happened on the client.
Edit
Form controls don't need a name and ID, just use a name. In a radio button set, only one control can be checked, you can't check all of them.
It seems to me that what you are trying to do is to see if at least one radio button has been checked in each set. You can do that based on the code above and selecting each set as you encounter it, e.g.
function validateForm(form) {
// Get all the form controls
var control, controls = form.elements;
var radios = {};
var t, ts;
// Iterate over them
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
// If encounter a radio button in a set that hasn't been visited
if (control.type == 'radio' && !radios.hasOwnProperty(control.name)) {
ts = form[control.name];
radios[control.name] = false;
// Check the set to see if one is checked
for (var j=0, jLen=ts.length; j<jLen; j++) {
if (ts[j].checked) {
radios[control.name] = true;
}
}
}
}
// Return false if any set doesn't have a checked radio
for (var p in radios) {
if (radios.hasOwnProperty(p)) {
if (!radios[p]) {
alert('missing one');
return false;
}
}
}
}
</script>
<form onsubmit="return validateForm(this);">
<input type="radio" name="r0">
<input type="radio" name="r0">
<br>
<input type="radio" name="r1">
<input type="radio" name="r1">
<br>
<input type="reset"><input type="submit">
</form>
Note that your form should include a reset button, particularly when using radio buttons.

Categories

Resources