group all radio buttons with different names - javascript

I am trying to find a way to validate all of my radio buttons to make sure atleast one of them is checked. The problem is doing it with the names and id's have to remain in the format that they are in.
So basically I want to have a way to group all of my radio buttons even with different names and id's.
I understad how to loop for all checked buttons in the table but some are outside of the table, the code is just an example of what I need to do.
<table id="table" width="100%" border="0" cellpadding="5">
<tr>
<td><input type="radio" name="blue" id="blue" value="blue1" /></td>
<td><input type="radio" name="blue" id="blue" value="blue2" /></td>
<td><input type="radio" name="red" id="red" value="red1" /></td>
<td><input type="radio" name="red" id="red" value="red2" /></td>
<td><input type="radio" name="blue" id="green" value="green1" /></td>
<td><input type="radio" name="green" id="green" value="green2" /></td>
</tr>
</table>

Something like this:
if($('input[type="radio"]:checked').length > 0){
//at least one radio on your page is checked
}

Assuming you are going for the HTML5 validation, just make one of them required, and then change it as they go:
<input required type="radio" name="blue" id="blue" value="blue1" />
JS:
$radios = $('input[type="radio"]');
$radios.on('change', function() {
if ($(this).is(':checked')) {
$radios.prop('required', false);
$(this).prop('required', true);
}
});
$('form').on('submit', function(e) {
if ($('input[type="radio"]:checked').length === 0) {
e.preventDefault();
alert("Must check at least one radio");
return false;
}
});

Given your posted html I'd suggest changing the name of all those posted <input /> elements to colour (or color, according to language preference) to clearly associate them together.
However, if that can't be done, and you're able to add a class-name as a means of associating the group:
var allInputs = $('input.colour'),
checked = allInputs.filter(':checked'),
choiceMade = checked.length > 0;
Incidentally:
…I think by adding the class if I checked one, it would check the rest in that class.
No, that behaviour - unchecking one element should another be checked - is entirely dependent on the <input /> sharing a name attribute and being semantically grouped. It doesn't matter how else you create an association, so long as you don't yourself create that functionality.

To make sure at least one radio button within table is checked and the one at the top of the page:
if ($('#top-radio').is(':checked') && $('#table :radio:checked').length) {
// valid, something is checked
}

Related

Storing multiple sets of radio button values into object angularjs (without jQuery)

In this slimmed down version of my controller and view, I am attempting to store the user selection of multiple sets of radio buttons, grouped in threes, within an object. I then will send the object within ajax call in order to store via SQL database. I have succeeded in doing this, however I had to use jQuery to do so. Any ideas on ways to do this within the angularjs framework, hence avoiding the jQuery usage? In case you’re wondering, the radio buttons represent present and absent, in order to keep attendance for a large list of students. Thank you!
<tr ng-repeat="s in rollCallList">
<td align="left">{{s.Last_Name}}, {{s.First_Name}}</td>
<td>
<input name="{{s.dc_number}}" id="id1{{s.dc_number}}" type="radio" value="P" ng-checked="radiocheck" />P
<input name="{{s.dc_number}}" id="id2{{s.dc_number}}" type="radio" value="A" />A
<input name="{{s.dc_number}}" id="id3{{s.dc_number}}" type="radio" value="X" />X
</td>
</tr>
<tr>
<td colspan="2">
<button class="btn" ng-show="SaveAttBtn" ng-click="SaveAtt(RollCallDate)">Save Attendance</button>
<button class="btn" ng-show="DeleteAttBtn" ng-click="DeleteAtt(RollCallDate)">Delete Attendance</button>
</td>
</tr>
$scope.SaveAtt = function (dt) {
$scope.rollCallList.forEach(function (obj) {
var dc = obj.dc_number;
var attVal = $('input[name=' + dc + ']:checked').val();
obj.status = attVal;
obj.classDate = dt;
console.log(obj);
});
}
<input name="dcNumber_{{s.dc_number}}" type="radio" ng-model="s.status" ng-value="'P'" />P
<input name="dcNumber_{{s.dc_number}}" type="radio" ng-model="s.status" ng-value="'A'" />A
<input name="dcNumber_{{s.dc_number}}" type="radio" ng-model="s.status" ng-value="'X'" />X
When looping through your items, s.status will have the selected ng-value. As for ng-checked, you should set the s.status to equal to the value you want to be auto selected. (P,A,X)

Radio input not working with localStorage

Radio input not working with localStorage
I used localStorage for many examples and work with me good except starRating.
Here is example example
I tried many codes , but does not work
Please give me example. Sorry I'm newbie.
<table>
<thead>
<tr>
<th STYLE="width:200px">link</th>
<th STYLE="width:200px">rating</th>
<th STYLE="width:200px">Options</th>
</tr>
</thead>
<tr>
<td>
<A CLASS="flink" HREF="https://www.google.com" TARGET="_blank">site a</A>
</td>
<td>
<span class="starRating">
<input CLASS="inputrating" CHECKED id="rating_9_5" type="radio" name="rating_9" value="5">
<label for="rating_9_5">5</label>
<input CLASS="inputrating" id="rating_9_4" type="radio" name="rating_9" value="4">
<label for="rating_9_4">4</label>
<input CLASS="inputrating" id="rating_9_3" type="radio" name="rating_9" value="3">
<label for="rating_9_3">3</label>
<input CLASS="inputrating" id="rating_9_2" type="radio" name="rating_9" value="2">
<label for="rating_9_2">2</label>
<input CLASS="inputrating" id="rating_9_1" type="radio" name="rating_9" value="1">
<label for="rating_9_1">1</label></span>
</td>
<td>
add
</td>
</tr>
<tr>
<td>
<A CLASS="flink" HREF="https://www.google.com" TARGET="_blank">site b</A>
</td>
<td>
<span class="starRating">
5
4
3
2
1
add
$(".starRating").on("click", function(){
selected_rating = $('input', this).data("inputrating");
selected_id = $('input', this).data("rating-id");
console.log(selected_rating)
});
You need to change your event binding to the Radio Buttons, not the spans that contain them.
Next, you need to access the values of the radio buttons, rather than using the jQuery .data() method, which I'm not sure what you are doing with.
this.value
In the event handler is all you need for that.
Next, you need to actually store the values, which you didn't have any code for:
if(window.localStorage){
localStorage.setItem("Site A Rating", this.value);
} else {
console.log("localStorage not supported.");
}
Here is a working Fiddle: https://jsfiddle.net/6jfey3cj/4/
And a screen shot showing the different site's ratings in localStorage.
The key issue you are struggling with is how to decide which element is best to trigger your function on. You are currently triggering on .starRating which is a span. It is possible to use that as the trigger but makes much more sense to simply fire the function whenever someone chooses a value on .inputrating which is a class that is unique to all your star rating radio buttons.
Try this code out:
$(".inputrating").on("change", function(){
checked_rating = $(this).val();
checked_id = $(this).attr('id');
console.log(checked_rating);
console.log(checked_id);
});
If you notice I changed click to change. This will make it so that your code only fires once on rating select. That way if you end up running an ajax function to update a database it won't keep getting called over and over if the user decides to spam click the same radio button over and over.
Here is a working fiddle demonstrating the solution: JSFiddle
You can change your javascript function as below
$(".inputrating").on("click", function(){
selected_rating = $(this).val();
selected_id = this.id;
console.log(selected_rating);
console.log(selected_id);
});
updated fiddle -
https://jsfiddle.net/tfhg15xw/2/

Can't set checked attribute in radio button (radio button inside table)

I tried setting radio button checked to checked="checked" however this does not seem to work .
I have tried using
$(id_radio).prop('checked',true);
document.getElementById("id_radio").checked = true;
document.getElementById("id_radio").checked = true;
document.getElementById("id_radio").checked;
$(id_radio).attr('checked',checked);
But none of them seems to be changing the attribute of checked to checked="checked"
Below is my code
js_file.js
$(document).ready(function(){
$("document").on("click",".class_radio3",function(){
var id_radio=$(this).attr('value');
$(id_radio).prop('checked',true);
console.log(id_radio);
});
});
My code for creating table
<br>
<p class="uk-text-primary uk-text-bold"><u> General Message </u></p>
<table class="uk-table uk-border-rounded uk-grid-width-* uk-panel-box uk-text-justify" border="1">
<!--create top table -->
<tr> <!--tr defines a row --> <!-- define row 1 -->
<th class="uk-width-1-10"> Recipient </th> <!-- th defines a header cell-->
<th class="uk-width-1-3"> Message </th>
<th class="uk-width-1-10"> Action </th>
<th class="uk-width-1-10"> Default message </th>
</tr>
<!-- row 2 : display results onwards and creates dynamically -->
<!-- input fields at the bottom -->
<?php
include "../connect.php";
$get_data2admin = $db->query("SELECT ID,message,user FROM test_table_1 WHERE user='General'");
if( $get_data2admin->num_rows >0 ){ //if selected rows is more than zero
while($row_msg = $get_data2admin->fetch_assoc()){
$row_msg_id=$row_msg['ID']; //$row_msg['ID'] directly using it wont display in id tag attribute
echo "<tr>";
echo "<td>".$row_msg['user']."</td>";
echo "<td>".$row_msg['message']. "</td>";
?>
<td>Delete</td>
<?php
if($row_msg['user']=='General'){
echo "<td>"."<input class='class_radio3' type='radio' name='name_radio2' value='$row_msg_id' checked=''/>"."</td>";
}
else{
echo "<td>"."-"."</td>";
};
echo "</tr>";
}
}
?>
</table>
What could be the issue? Any insight/solution? Am a beginner in PhP any advice would be helpful. Thank you
Note
Its printing out the right id selected so i dont think its selection issue
A sidenote: another issue if i try using e.preventDefault at
$("document").on("click",".class_radio3",function(e){
e.preventDefault();
The radio button becomes un-clickable.Why is that so?
Update 1: Picture of what is the issue
Try This
HTML
if($row_msg['user']=='General'){
echo "<td>"."<input id='$row_msg_id' class='class_radio3' type='radio' name='name_radio2' value='$row_msg_id' />"."</td>";
}
JS
var id_radio=$(this).attr('id');
$('#' + id_radio).prop('checked',true);
Check the below,
You can use attr like below but i would recommend use prop
function chk(element) {
$(element).attr("checked", "checked");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="age">10</label>
<input type="radio" name="age" value="10" onclick="chk(this);" />
<label for="age">15</label>
<input type="radio" name="age" value="15" onclick="chk(this);" />
I think there are a couple of issues here... one is that only one radio can be checked per group - i.e. radios with the same "name". Having checked="" is the same as checked="checked" - the absence of the attribute altogether is the "unchecked" state.
div {
width: 50%;
float: left;
}
<div>
<h1>Group 1</h1>
<p><input type="radio" name="group1" value="1" checked="checked" />1</p>
<p><input type="radio" name="group1" value="2" checked="checked" />2</p>
<p><input type="radio" name="group1" value="3" checked="checked" />3</p>
<p><input type="radio" name="group1" value="4" checked="checked" />4</p>
<p><input type="radio" name="group1" value="5" checked="checked" />5</p>
</div>
<div>
<h1>Group 2</h1>
<p><input type="radio" name="group2" value="1" checked="checked" />1</p>
<p><input type="radio" name="group2" value="2" />2</p>
<p><input type="radio" name="group2" value="3" />3</p>
<p><input type="radio" name="group2" value="4" />4</p>
<p><input type="radio" name="group2" value="5" />5</p>
</div>
Secondly, in your code, you are saying (if I understand what PHP is outputting correctly), onclick of this input (radio), set the thing with an id that is the same as my value's property "checked" to true. That thing with an id is the a tag. An a tag does not have this checked property. See below where I'm setting its background to red (via a class), instead.
By default, a radio button will become checked on click, so you don't need to reiterate this default behavior.
I have also updated the code to respond when an input's value changes, as opposed to when the document is clicked and the target was the input. It is a little lighter performance-wise to listen for the more limited scope than the broader one you had. The approach that you used used to be referred to as a "live" listener in jQuery and is more appropriate for when JS is adding and removing elements that you're listening for on the page; in your case, PHP is rendering them, so we don't need it.
Additionally, jQuery selectors require a # to indicate id, a . to indicate class, and without these selectors, it assumes it is a tag. See below where I am appending a # to select the a with the id.
// This is listening for any radio buttons who were clicked, instead of any clicks on the document (it's a little more efficient)
$("input[type=radio]").on("change", function() {
// get the other radio buttons in this group
var $group = $('input[name=' + $(this).attr('name') + ']');
// Go through the group and if the input is checked, add the class to the corresponding element, otherwise, remove it
$group.each(function() {
var id_radio = "#" + $(this).attr('value');
if ($(this).is(":checked")) {
$(id_radio).addClass("radio-is-checked");
} else {
$(id_radio).removeClass("radio-is-checked");
}
});
});
.radio-is-checked {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="uk-text-primary uk-text-bold"><u> General Message </u>
</p>
<table class="uk-table uk-border-rounded uk-grid-width-* uk-panel-box uk-text-justify" border="1">
<!--create top table -->
<tr>
<!--tr defines a row -->
<!-- define row 1 -->
<th class="uk-width-1-10">Recipient</th>
<!-- th defines a header cell-->
<th class="uk-width-1-3">Message</th>
<th class="uk-width-1-10">Action</th>
<th class="uk-width-1-10">Default message</th>
</tr>
<!-- row 2 : display results onwards and creates dynamically -->
<!-- input fields at the bottom -->
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<!-- Since the radio in this row is checked by default, also apply the corresponding class -->
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='one' checked />
</td>
</tr>
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='two' />
</td>
</tr>
<tr>
<td>$row_msg['user']</td>
<td>$row_msg['message']</td>
<td>Delete
</td>
<td>
<input class='class_radio3' type='radio' name='name_radio2' value='three' />
</td>
</tr>
</table>
Thirdly, the "default" behavior of a radio button is to become checked. By doing e.preventDefault you're cancelling that default behavior, so it doesn't become checked!

how to toggle multiple inputs within a table depending on radio button selection

Assume the following html:
<tr>
<td>
<label for="c1_testRdio">Have you taken any tests in this class?:</label>
<br>
<label>Yes<input type="radio" class="testRdio" name="c1_testRdio" value="Yes"></label>
<label>No <input type="radio" class="testRdio" name="c1_testRdio" value="No" checked></label>
<label>How Many? <input type="text" class="howManyTests" name="c1_howManyTests" disabled></label>
</td>
<td>
<label for="c1_whatGradesTests">What were your grades?:</label><br>
<input type="text" name="c1_whatGradesTests" disabled>
</td>
</tr>
if radio with value="Yes" is selected, what jQuery (1.5 compatible ) code would enable the 2 text inputs, c1_howManyTests and c1_whatGradesTests?
Have tried:
$('.testRdio').change(function(){
//var txt = $(this).closest("td").next("td").children('.howManyTests');
var txt = $(this).parent().next('label>input[type="text"]');
console.log(txt.id);
this.value == 'No' ? txt.removeAttr('disabled') : txt.attr('disabled', 'disabled');
});
Try this:
$('.testRdio').change(function () {
$(this).closest('tr').find('input[type="text"]').attr('disabled', this.value === 'No');
});
The older jq version that doesnot have prop, attr (used to do the job of prop as well) used to take bool values for disabled.
Demo
Also i had to fix your markup a lot as well (Now i see its fixed in the question already)
$('.testRdio').change(function(){
$(this).closest('tr').find('input[type="text"]').attr('disabled',$(this).val()=="No");
});
jsFiddle example
Your code was a little messy, so I rebuilt it: http://jsfiddle.net/QgJac/1/
I think hiding the whole div is better. They don't really need to see those questions if they select 'No'.

check to see if a particular checkbox is checked in a td using jquery

I am trying to make textbox readonly or not depending on the value of a checkbox of personalLoan. If personalLoan checkbox is checked I want the text to be not readonly. If it is unchecked then I want the text box to be readonly. Here is one of the rows
<tr id="mytableRows">
<td class="even"><input type="checkbox" value="true" name="homeLoan" ></td>
<td class="odd"><input type="checkbox" value="true" name="autoLoan" ></td>
<td class="even"><input type="checkbox" value="true" name="personalLoan" ></td>
<td class="odd"><input type="checkbox" value="true" name="noLoan" ></td>
<td class="odd"><input type="text" name="peronalAmount" value="1" readonly></td>
</tr>
I so far has this code
$(document).ready(function(){
$('.test tr').click(function (event) {
$(this).find(':checkbox').each(function(p){
if($(this).attr('name') == 'personalLoan'){
if ($(this).is(':checked')) {
alert("checked");
}else{
alert("unchecked");
}
}
});
});
});
This tells me the current status of the checkbox but what I really need is to know onchange of the personalLoan checkbox so I can make the textbox readonly or not in that row (td)
thanks
For my own sanity, here is what I understand the solution to be.
$('input[type=checkbox]', '.test').on('change', function(e) {
if (this.name === 'personalLoan') {
$(this).parents('tr').find('input[type=text]').prop('readonly', !this.checked);
}
});
Assuming a table with class test, this allows input when personalLoan is checked, and toggles to readonly when unchecked.
Demo on jsFiddle. (I've highlighted the checkbox in red.)
If this isn't it, then I really have no idea what you're trying to do.
It seems to me that you really want radio buttons, not checkboxes, and that the amount field should be set to disabled rather than readonly if the user selects "no loan".
Anyhow, here's an approach you can take. I've put the code in–line for convenience, it can re-implemented in jQuery or whatever you want, it's just an example of how to do what you seem to be trying to do.
The timeout is used so that the one click event can be used for any element in the form, including the reset button.
<form onclick="
var form = this;
setTimeout(function() {
form.personalAmount.readOnly = form.loanType[3].checked;
},0);
">
<table>
<tr>
<td><input type="radio" value="homeLoan" name="loanType">Home</td>
<td><input type="radio" value="autoLoan" name="loanType">Auto</td>
<td><input type="radio" value="personalLoan" name="loanType">Personal</td>
<td><input type="radio" value="true" name="loanType">None</td>
<td><input type="text" name="personalAmount" readonly></td>
<tr>
<td colspan="4">
<input type="reset">
</table>
</form>

Categories

Resources