jQuery problem with multiple radio selects - javascript

I'm trying to validate a form that contains several different radio buttons. A few radio buttons in the form have the same classname 'video_type'.
In the jQuery validation script, after the form is submitted I want to check if any of the radio buttons with the classname 'video_type' have been selected. If the user has selected at least one radio button with the classname 'video_type' and the value as 1, it should return true. Otherwise it should return false.
At the moment I'm using this:
HTML:
<input type="radio" name="video_option_1" class="video_option" value="1">Yes
<input type="radio" name="video_option_1" class="video_option" value="0">No
<input type="radio" name="video_option_2" class="video_option" value="1">Yes
<input type="radio" name="video_option_2" class="video_option" value="0">No
jQuery:
$("#completeOrderForm").submit(function(){
if($(".video_type").val() == 0){
$("#showerrors").show().html("Please select a video type.");
return false;
}
});
But I realise it's incorrect. What do I need to do?

This should work:
if ($(".video_option[value='1']:checked").length == 0) {
$("#showerrors").show().html("Please select a video type.");
return false;
}
Basically you're selecting every element with the class .video_option that have the value 1 ([value='1']) and are checked (using the :checked selector). It then counts the amount of elements selected, if the result is 0 no radio's are checked.
Fiddle: http://jsfiddle.net/bjorn/UwufF/6/
EDIT
You talk about radio buttons with the classname video_type yet the code shows video_option, I went by the code when making the example.

Related

JQuery: Getting a series of checkboxes to validate

I'm trying to get a group of checkboxes as part of an overall form I created in the admin area of WordPress to validate. Basically, custom fields. Here's what the code looks like:
<div><label><input type="checkbox" value="0-2" name="_ecp_custom_5[]" /> 0-2</label></div>
<div><label><input type="checkbox" value="3-5" name="_ecp_custom_5[]" /> 3-5</label></div>
<div><label><input type="checkbox" value="6-8" name="_ecp_custom_5[]" /> 6-8</label></div>
and so on.....
So I have this in my JavaScript:
jQuery(document).ready(function($) {
$('[name="_ecp_custom_3"]').attr("required", true);
$('[name="_ecp_custom_5[]"]').prop("checked", true);
});
First line for a text field, works great. But the checked one underneath doesn't work at all. If I submit the form without checking a box, the form still publishes and when it comes back, all the fields are now checked even though I didn't check any of them.
Puzzled what to do in regards to that since there's going to be several rules in this validation function.
If you are using html:
An html element name and id cannot include special characters, such as [ ], and must begin with a letter (A-Z), (a-z).
Aside from that, your jQuery references an element with the name=_ecp_custom_5 and not name=_ecp_custom_5[]. Simply remove the [] in your names and your code will work.
Update
The $('[name=foo]').prop("checked", true) sets all checkboxes with name=foo to checked. I'm a bit confused about what you are asking at this point, since it seems like you are confused about why your form is submitting all checkbox inputs as checked?
You want to require that at least one checkbox is checked, right?
You can iterate all inputs with the name attribute value of "_ecp_custom_5[]" by using jQuery.each(). With that, you can create any flag variable that will be used on any condition.
Please refer to the snippet below if you can't visualize what I am trying to say.
If you want to require that at least one checkbox is checked, you can use this example as your basis
$(function() {
$('#btnValidate').click(function() {
var flag = false;
$.each($('[name="_ecp_custom_5[]"]'), function(index, value) {
var checkboxStatus = $(this).prop('checked');
if (checkboxStatus == true) {
flag = checkboxStatus;
}
});
if (flag == false) {
alert('No checkbox has been checked')
} else {
alert('Success!')
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label>
<input type="checkbox" value="0-2" name="_ecp_custom_5[]" /> 0-2
</label>
</div>
<div>
<label>
<input type="checkbox" value="3-5" name="_ecp_custom_5[]" /> 3-5
</label>
</div>
<div>
<label>
<input type="checkbox" value="6-8" name="_ecp_custom_5[]" /> 6-8
</label>
</div>
<button id="btnValidate" style="margin-top: 20px;">Validate</button>
How I did it?
I iterated all inputs with the name attribute value of "_ecp_custom_5[]".
Then I created a boolean variable named "flag" (default value is false) that is being changed to true only if a checkbox from the iteration has the prop('checked') value of true. If no checkbox has been checked, then the "flag" variable's value will remain false which will then be checked by my condition.

Make checkboxes required

I already looked to similar questions but I still can't figure out how to fix it. On my webpage, I have some radio checkboxes which I would like to be required before going to the next question.
I have the following partial code:
<p>
Select the option that fits most to you<br><br>
<label>
<input type="radio" name="typesport" value="teamsport" >
I prefer a teamsport</label><br>
<label>
<input type="radio" name="typesport" value="individual">
I prefer an individual sport</label><br>
</p>
Next question
Can someone help me with getting a javascript code, that actually works for all radio-boxes, where you could only go to the next question when 1 radio-box is selected?
Cheers,
Max
Edit: What I've tried so far is the following:
I added "required" to the label, so it looked like this:
<label><input type="radio" name="typesport" value="teamsport" required> I prefer a teamsport</label><br>
I also added the ID to the button:
Next question
Furthermore, I used this JS script:
$(document).ready(function () {
$('#checkBtn').click(function() {
checked = $("input[type=radio]:checked").length;
if(!checked) {
alert("You must check at least one radio.");
return false;
}
});
});
However, this works fine for only one question. When I add this to all the other questions, I still can go to the following question when I click on the button Next question, and that is not what I want.
Radio boxes are fairly simple in nature in that you should always have at least one option in a radio-group checked by default. Preferably a N/A or 'Please Select' option.
In which case you would want to validate against the 'Please Select' option instead:
//when user clicks <a> element
$(".next-button").click(function() {
//group on radio button name and test if checked
if ($("input[name='typesport']:checked").val() == 'select') {
alert('Nothing is checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Select the option that fits most to you<br><br>
<label><input type="radio" name="typesport" value="select" checked="true" > Please Select </label><br>
<label><input type="radio" name="typesport" value="teamsport" > I prefer a teamsport</label><br>
<label><input type="radio" name="typesport" value="individual"> I prefer an individual sport</label><br>
</p>
Next question
However
If you really want to validate that an option has been checked:
This should work:
//when user clicks <a> element
$(".next-button").click(function()
{
//group on radio button name and test if checked
if (!$("input[name='typesport']:checked").val()) {
alert('Nothing is checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Select the option that fits most to you<br><br>
<label><input type="radio" name="typesport" value="teamsport" > I prefer a teamsport</label><br>
<label><input type="radio" name="typesport" value="individual"> I prefer an individual sport</label><br>
</p>
Next question
HTML5 supports the required attribute for radio buttons. I did some searching and HTML5: How to use the "required" attribute with a "radio" input field has more detailed information about this attribute.
You can set a radio button checked by default by using the checked attribute.
To check if it's checked or not, use this code :
if ($('input[name=typesport]').attr('value') != undefined) {
//execute code when it is checked
} else {
//execute code when it's not checked
}

selecting radio options doesnt change checked attribute

I am generating an HTML form with some radio buttons and checkboxes. the generated code for the radio buttons for instance are like these:
<input id="101_2" type="radio" name="101" value="2" >
<input id="101_3" type="radio" name="101" value="3" checked="true">
Using JavaScript I can make a for cycle to see what radio is checked using the check attribute.
The problem is that if I manually click in another radio option (from the same group as in the example), visually in the HTML I can see that another radio is selected, but the JavaScript is still saying that the input 101_3 is the selected radio option. If I look at the HTML using firebug I can see that the new selected option is indeed not selected (doesn't have the checked attribute)... despite I have selected manually.
Any ideas on this?
Fist and formost when naming your radio buttons or any type of DOM input element never start the name of an input element with a number, always start the name of your input element with a letter.
For your posted code you would name your radios in similar fashion, one01 or x101 or o101,ect...
Do the same thing with your ids' of any DOM element. Never start an id of a DOM element with a number.
--HTML
<input id="x101_2" type="radio" name="x101" value="2">
<input id="x101_3" type="radio" name="x101" value="3" checked="checked">
<br /><br />
<button type="button" onclick="WhatsChecked()">Whats Checked?</button>
--JavaScript
function WhatsChecked() {
var radCk = document.body.querySelectorAll('input[name="x101"]:checked')[0];
alert(radCk.id);
};
--Fiddler
fiddler

radio button selection in jquery

I have a set of two radio buttons having same id
<input type="radio" id="rad" name="mode"value="test" />test
<input type="radio" id="rad" name="mode" value="dev"/>dev
user have to select any one of the radio button.so while validating if second radio is selected the following validation alerts always.
if ($('#rad').prop('checked') != true ) {
alert(' Please Choose mode!!')
return false;
}
I only have to alert if user did not select any one of them.and no need to alert if user selected one radio button.
In my case if user select first radio button it alerts anything but choosing second radio it alerts Please Choose mode.
ID of element uniquely identifies the html element! read this if you keen :) https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really
Also : http://jsfiddle.net/Pkq3B/
have fun, lemme know how it goes!
you could use class like this:
if (!$('.rad').is(':checked')) {
alert(' Please Choose mode!!')
return false;
}
html
<input type="radio" class="rad" name="mode"value="test" />test
<input type="radio" class="rad" name="mode" value="dev"/>dev
Try to use length of checked radio buttons like,
if (!$('input[name="mode"]:checked').length) {
alert(' Please Choose mode!!')
return false;
}
Working demo
You don't need jQuery for that purpose. You can use pure JavaScript:
if((document.getElementById('rad').value!='test')||document.getElementById('rad').value!='dev'))
{
alert("please select");
}

Radio input and alert in Javascript

I need some help.
I have program that changes table values based on user input in radio box
similar to this page:
clicky
But the problem is I want users to select the radio input only once; if they select another
radio then values of tables get messed up.
So what I want to know is how can I make an alert box when user selects the radio input twice?
Similar to this website clicky try clicking radio button twice and alert popsup.
Please can anyone help?
It's difficult to prevent an event on a radio button input node without bringing in help from outside libraries. A simple solution is to just disable the buttons from within an onclick function attached to each input node. Like so: http://jsfiddle.net/c73Mh/ . If they still need to be able to select the radio buttons for whatever reason, you can cancel the selection by selecting the button that was initially selected from within that same function. Hope this helps!
For simplicity in my example I'm assuming that the id of each radio button is a combination of the name and value attributes. In addition to what I've given you below you will need to add a reset() function of some kind that sets selectedValues = {}; and deselects all radio buttons.
<input type="radio" name="group1" value="A" id="group1A" onclick="radioClicked(this);" />First option
<input type="radio" name="group1" value="B" id="group1B" onclick="radioClicked(this);" />Second option
<input type="radio" name="group2" value="A" id="group2A" onclick="radioClicked(this);" />First option
<input type="radio" name="group2" value="B" id="group2B" onclick="radioClicked(this);" />Second option
var selectedValues = {};
function radioClicked(rb) {
if (selectedValues[rb.name] === undefined) {
selectedValues[rb.name] = rb.value;
doTableProcessing();
}
else {
alert("You can't change the selected values");
document.getElementById(rb.name + selectedValues[rb.name]).checked = true;
}
}

Categories

Resources