Retrieve radiobuttons from the child div within the main div - javascript

I have the following html.. 1 main div having 2 child divs.
I need to loop through both the divs and retrieve the checked radiobutton in each. e.g.: 1st child div has maybe checked while 2nd div has wright checked, i need to retrieve both their values. How do i go about it
<DIV>
<DIV>
<TABLE>
<TBODY>
<TR>
<TD>
wrong<INPUT class=XX disabled value=wrong type=radio name=radiobutton>
wright<INPUT class=XX disabled value=wright type=radio name=radiobutton>
maybe<INPUT class=XX value=maybe CHECKED type=radio name=radiobutton ></TD>
</TR></TBODY></TABLE>
</DIV>
<DIV>
<TABLE><TBODY><TR>
<TD>
wrong<INPUT class=XX CHECKED value=wrong type=radio name=radiobutton>
wright<INPUT class=XX value=wright type=radio name=radiobutton>
maybe<INPUT class=XX value=maybe type=radio name=radiobutton ></TD>
</TR></TBODY></TABLE>
</DIV>
</DIV>

You have two groups of radiobuttons from what I understand.
So, here's my solution:
HTML
<div>
<div>
<table>
<tbody>
<tr>
<td>wrong
<input class="xx" disabled="disabled" value="wrong" type="radio"
name="radiobutton">wright
<input class="xx" disabled="disabled" value="wright" type="radio"
name="radiobutton">maybe
<input class="xx" value="maybe" checked="checked" type="radio" name="radiobutton">
</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
<tr>
<td>wrong
<input class="xx" checked="checked" value="wrong" type="radio" name="radiobutton2">wright
<input class="xx" value="wright" type="radio" name="radiobutton2">maybe
<input class="xx" value="maybe" type="radio" name="radiobutton2">
</td>
</tr>
</tbody>
</table>
</div>
</div>​
jQuery
var radiobutton = $("input[name='radiobutton']:checked").val();
var radiobutton2 = $("input[name='radiobutton2']:checked").val();
alert('1st - '+radiobutton+' / 2nd - '+radiobutton2);​
DEMO
EDIT
jQuery
var checked = new Array();
var pos = 0;
$("input[type='radio']:checked").each(function(){
checked[pos] = new Array(2);
checked[pos]['name'] = $(this).attr('name');
checked[pos]['value'] = $(this).val();
pos++;
});
var result = "";
for(i=0; i<pos; i++){
result += checked[i]['name'] + " - " + checked[i]['value'] + " / ";
}
alert(result);
DEMO

Is this what you are looking for: Working demo http://jsfiddle.net/79syA/
In your HTML you only have wrong input radio checked, also make your html lowercase is there any reason why it is upper case :)
Rest hope this fits your need & feel free to play around with demo! :)
code
$('.XX').each(function(){
if($(this).is(':checked')){
alert(" Checked value is ==> " + this.value);
}
})​

Related

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!

Return a string based on checkbox checked

I have a table with 2 checkboxes:
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
and I want to be able to identify which box is checked (by id), and be able to store a string as a variable, depending on the box. Here is my javascript:
var getCheck = function() {
if (document.getElementById('A').checked) {
return "A";
}
else if (document.getElementById('B').checked){
return "B";
}
else if ((document.getElementById('A').checked) && (document.getElementById('B').checked)) {
return "Both"
}
console.log(getCheck); // for debugging
};
So if I check 'A', I want getCheck to = 'A' as a string. Curious as to how to fix my Javascript to get it to work.
Here's an example of how you would do it with jQuery, it's just easier to do with it and since there's a jQuery tag...
Basically, you add a handler for elements that are checkboxes. Then you select only checked checkboxes with :checked and then you just access each element with the jQuery each function.
$(function(){
$('input[type=checkbox]').on('change', function(){
var checked = [];
$('input[type=checkbox]:checked').each(function(index, checkbox){
checked.push($(checkbox).attr('id'));
});
$('#result').text(JSON.stringify(checked, '/t'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
<pre id="result"></pre>
You need to check both first, since otherwise the function will return "A" and never reach the code that would return both. It is also possible to eliminate all the if-else complexity when returning from each if.
A helper function and some variables can reduce repetition and code length.
var isChecked = function(id){
var e = document.getElementById(id);
return (e && e.checked);
}
var getCheck = function() {
var A = isChecked("A");
var B = isChecked("B");
if (A && B) return "Both";
if (A) return "A";
if (B) return "B";
return "None";
}
For testing, you could add
window.onclick = function(){ console.log(getCheck()); }
demo via jsfiddle
fiddle example
The answer others provided is quite good for. And I want to make some addition:
If you want to get the value whenever user check the box, you can add a eventListen to the parent table as a delegation for the checkbox. Just as I show in the fiddle example
<table id="mytable">
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>

If a checkbox is selected, select two others

The table contains a few rows like that:
<tr>
<td>
<input type="checkbox" name="indicator[]">
</td>
<td>
<input type="checkbox" name="graduations[]">
</td>
<td>
<input type="checkbox" name="graduations[]">
</td>
<td>
<input type="checkbox" name="graduations[]">
</td>
<td>
<input type="checkbox" name="graduations[]">
</td>
<td>
<input type="checkbox" name="graduations[]">
</td>
</tr>
I need to disable 'graduations' being checked if 'indicator' is not checked. And if checked, i need to check exactly two 'graduations' in that row.
My actual code only limits the number of checked 'graduations'.
$(function() {
$('input[name=graduations\\[\\]]').click(function() {
if($(this).parent().siblings().children("input[name=graduations\\[\\]]:checkbox:checked").length >= 2)
this.checked = false;
});
});
You can try this:
$("#area_covered").click(function(){
if($("#area_covered").is(':checked'))
$('.area_covered').prop('checked', true);
else
$('.area_covered').prop('checked', false);
});
give some id to the checkbox you're going to click, and give some class to both of the other checkboxes which you want to be get checked also.
then use the above jquery tag, which would work for you definitely.\
Thanks & Enjoy coding :)
Updated try this simple FIDDLE
$(function(){
$("input[name^=graduations]").on("change",function(e){
if((!$("input[name^=indicator]").is(":checked")) || +$("input[name^=graduations]:checked").length > 2 ){
$(this).prop('checked',false);
}
});
});
makes it simple
Hope it helps

Radio buttons and checkboxes javascript

I have the below code.
2 radio buttons that enable+tick their checkboxes when selected and disable+untick them when the other radio button is clicked.
The code is working fine as a HTA but fails to work properly as a HTML. Knowing that the final app will be HTA, do I have to worry about the code not working fully in HTML?
Many thanks.
<table border=1>
<tr>
<td>
<form name="phaseform" action=""><font size=2>
<input type="radio" name="phase" value="1" id="phase" onclick="checkbox(0)" />
<label for="phase1">Phase 1</label>
</td>
<td><font size=2>
<input type="radio" name="phase" value="2" id="phase" onclick="checkbox(1)" />
<label for="phase2">Phase 2 (after 17 days)</label>
</td>
</tr>
<tr>
<td><font size=2>
<input type="checkbox" disabled id="TerminateP1" name="TerminateP1" value="IN">Terminate AD account<br>
<input type="checkbox" disabled id="MailboxAccessP1" name="MailboxAccessP1" value="IN">Grant mailbox access to manager<br>
</td>
<td><font size=2>
<input type="checkbox" disabled id="TerminateP2" name="TerminateP2" value="IN">Fully terminate AD account<br>
<input type="checkbox" disabled id="DisableMailboxP2" name="DisableMailboxP2" value="IN">Disable mailbox<br>
</td>
</tr>
</form>
<script type="text/javascript">
function checkbox(val)
{
document.phaseform.TerminateP1.setAttribute("disabled",1)
document.phaseform.MailboxAccessP1.setAttribute("disabled",1)
document.phaseform.TerminateP2.setAttribute("disabled",1)
document.phaseform.DisableMailboxP2.setAttribute("disabled",1)
document.phaseform.TerminateP1.setAttribute("checked",0)
document.phaseform.MailboxAccessP1.setAttribute("checked",0)
document.phaseform.TerminateP2.setAttribute("checked",0)
document.phaseform.DisableMailboxP2.setAttribute("checked",0)
if(val)
{
document.phaseform.TerminateP2.removeAttribute("disabled",val)
document.phaseform.DisableMailboxP2.removeAttribute("disabled",val)
document.phaseform.TerminateP2.setAttribute("checked",1)
document.phaseform.DisableMailboxP2.setAttribute("checked",1)
}
else
{
document.phaseform.TerminateP1.removeAttribute("disabled",val)
document.phaseform.MailboxAccessP1.removeAttribute("disabled",val)
document.phaseform.TerminateP1.setAttribute("checked",1)
document.phaseform.MailboxAccessP1.setAttribute("checked",1)
}
}
</script>
Try
function checkbox(val) {
var isone = !!val, istwo = !val;
document.phaseform.TerminateP1.disabled = isone;
document.phaseform.MailboxAccessP1.disabled = isone;
document.phaseform.TerminateP2.disabled = istwo;
document.phaseform.DisableMailboxP2.disabled = istwo;
document.phaseform.TerminateP1.checked = !isone;
document.phaseform.MailboxAccessP1.checked = !isone;
document.phaseform.TerminateP2.checked = !istwo;
document.phaseform.DisableMailboxP2.checked = !istwo;
}
Demo: Fiddle

JQuery Selectors (finding cell in a table that's in a td)

I have an HTML table
<table id="sometable">
<tr>
<td>
<table class="wTable">
<tr>
<td>
<input type="radio" name="rdGroup" val="0" />
</td>
<td>
<input type="radio" name="rdGroup" val="5" />
</td>
<td>
<input type="radio" name="rdGroup" val="10" />
</td>
</tr>
</table>
</td>
</tr>
</table>
The reason for the table within a TD is for the purpose of skinning and positioning. I'm not great when it comes to JQuery and was wondering if there was a selector technique to get access to that radio button when that cell is clicked.
For example, previously my code was set as (before skinning):
<table>
<tr>header stuff</tr>
<tr>
<td>data</td>
<td>data 2</td>
<td><input type="radio" name="rdGroup" value="0"> No Warranty </br>
<input type="radio" name="rdGroup" value="5"> 1 year Warranty </br>
<input type="radio" name="rdGroup" value="10"> 2 year Warranty </br>
</td>
<td>data 3</td>
</tr>
<tr>footer stuff</tr>
</table>
Above is the original basic table structure.
$("#dnn_ctr391_Account_ctl00_ctl01_grdItems tr:first,#dnn_ctr391_Account_ctl00_ctl01_grdItems tr:last").addClass("info");
The above added a class named info to the header and footer of the table (i didn't care for any of the data in them)
From there I created a td click function to process data:
$("#dnn_ctr391_Account_ctl00_ctl01_grdItems tr:not(.info) td:nth-child(7)").click(function() { //DO CODE HERE });
And within that click function I was able to access data from the other cells I needed:
var warval = 0;
warval = $(this).closest("tr").find("input[type=radio]:checked").val();
Is there a way for me to get access using the same style of coding to get access to when that cell is clicked to get the radio button value, and then leave that table to go back to the TD it is in, and then get access to the other td's using the $(this).closest("tr").find() method?
Thanks for any help you can provide.
I think you're looking for something like this:
$('table#sometable table.wTable td').click(function () {
var isChecked = $(this).children('input[type=radio]').val();
//To get 'back to the tr'
var $warval = $(this).closest("tr");
});
Ok, from what you said in the comments, I hope this is helpful:
First of all, I would advise changing the table markup to divs. This is not mandatory, but it will lead to cleaner and more manageable code. Something like this maybe:
<p>data 1</p>
<p>data 2</p>
<div>
<input type="radio" name="rdGroup" id="rdGroup_0" value="0" />
<label for="rdGroup_0">No Warranty</label>
</div>
<div>
<input type="radio" name="rdGroup" id="rdGroup_5" value="5" />
<label for="rdGroup_5">1 year Warranty</label>
</div>
<div>
<input type="radio" name="rdGroup" id="rdGroup_10" value="10" />
<label for="rdGroup_10">2 year Warranty</label>
</div>
<p>data 3</p>
<div class="footer">Footer</div>
Your jQuery hook could be as simple as this:
$(function() {
$('input[type=radio]').change(function() {
// do whatever needs to be done here when the radio button value changes
console.log("value '"+this.value+"' was selected for the warranty option");
});
});​
If you need to set the corresponding value when loading the form with the data stored in your DB, you could do it with this function (if you've set your radio box IDs as shown above):
var setWarrantyOption = function(value) {
$('#rdGroup_' + value).click();
};
You can fiddle around with the code here: http://jsfiddle.net/gruese/fsj2v/
Please tell me if that helps or if I've maybe misunderstood your problem.

Categories

Resources