Radio Buttons clear check when clicked again - javascript

I have a set of three radio buttons and they have mutual exclusion in them, as I implemented group name property, but the problem is, in the initial stage, none of the radio button is selected,
But when I select any of the radio button, then I cannot deselect the same, although mutual exclusion is in progress, but I want them to deselect as well.
My code aspx is:
<td>
<asp:RadioButton ID="AChk" runat="server" CssClass="itemRightAlign" GroupName="A"/>
</td>
<td>
<asp:RadioButton ID="DChk" runat="server" CssClass="itemRightAlign" GroupName="A"/>
</td>
<td>
<asp:RadioButton ID="WChk" runat="server" CssClass="itemRightAlign" GroupName="A"/>
</td>

You have both a code problem and a misunderstanding.
The misunderstanding is about how the mutual exclusion radio buttons work (or are supposed to work) (or are expected by the users to work).
The code problem is that in a mutually exclusion radio buttons group you need to initially select one of them.
So, I believe there are two ways of solving the problem:
Keep the radio buttons groud. Add a "none" button to the set, so that it works as if none of the other three are selected. And initially select this "none" button.
change the radio buttons to check boxes, so the user might select and deselect each of them. Then implement your own exclusion logic. I don't recommend this one.

You would need to use javascript...
doing binding in jquery, it's easier, and the name= should match your rendered groupname "name=" attribute...
var lastChecked = null;
$('input[name=A]').click(function(){
if (lastChecked == this) {
this.checked = false;
lastChecked = null;
}
lastChecked = this;
});

Use this to deselect:
var radios = document.getElementsByName('A');
for(var i=0; i<radios.length; i++)
{
radios[i].checked = false;
}

You can deselect a radio button by using the attribute ondblclick.
<input type="radio" name="RadioGroup1
" value="1" ondblclick="uncheckRadio();">
Apple</label>
When you double click on the radio button, just call a javascript function to set the checked property to false.
function uncheckRadio() {
var choice = document.form1.RadioGroup1;
for (i = 0; i < choice.length; i++) {
if ( choice[i].checked = true )
choice[i].checked = false;
}
}

Here is a similar implementation using the attribute ondblclickand jQuery. Also, this will allow you to include this functionality within controls with a dynamically generated client ID.
Code behind:
foreach (ListItem li in rbl.Items)
li.Attributes.Add("ondblclick", string.Format("clearCurrentRadioButtonSelection(\"{0}\")", rbl.UniqueID));
ASPX page
function clearCurrentRadioButtonSelection(controlName) {
var id = "input[name=" + controlName + "]";
$(id).each(function () {
$(this).attr('checked', false);
});
}

Related

Checkbox changestate on mouseover C# ASP.NET JAVASCRIPT

I am creating a checkbox group dynamically and adding them to placeholder control.
c#:
for (j = d; j < b; j++)
{
plhdr_seat.Controls.Add(new LiteralControl("<td>"));
CheckBox cb = new CheckBox();
cb.Checked = true;
cb.ValidationGroup = "seat";
cb.ID = "check_" + j.ToString();
cb.Attributes.Add("onmouseover", "javascript:seatcall(//what is the argument)");
cb.Text = j.ToString();
plhdr_seat.Controls.Add(cb);
plhdr_seat.Controls.Add(new LiteralControl("</td>"));
}
js:
<script type="text/javascript">
function seatcall(//what to pass)
{
//how to code? I have tried:document.getElementById(this).checked=false;
}
</script>
I've got:
I want these checkboxes to be unchecked onmouseover. How to do? Please help me with this code.
Can't undo myself from the feeling that you could have done some more research yourself on this one. The main problem with your current tries is that checked="false" is far from valid html.You have to completely remove the checked attribute.
The best way to accomplish this is by using jQuery. Add a class to you checkboxes, so they get rendered like this:
<input type="checkbox" checked="checked" class="hoverCheckbox"/>
Then, using jquery, bind the hover event of the checkboxes:
$('.hoverCheckbox').hover(function () {
$(this).removeAttr("checked");
});

Select Radio Button Using Javascript with No ID

I am trying to select a radio button on a webpage using Javascript inside an Applescript. For this particular button, there is no element ID, so I'm no really sure how to select this radio button.
There's really no other identifying elements for this form (or that I see, at least).
Note: There's several radio buttons on this page, and the only unique identifier between them is the "value."
HTML:
<input type="radio" size="4" name="Level" value="p;29">
Javascript/Applescript:
do JavaScript "document.getElementById('p;29').checked = true;" in doc
If you have no other input elements, you can safely use
document.getElementsByTagName("input")[0]
Otherwise, you can do:
for (i=0; i<document.getElementsByTagName('input').length; i++) {
var myInput = document.getElementsByTagName('input')[i];
if (myInput.type == 'radio')
{
//myInput is the radio element. Do something with it
}
}
I ended up using the value and name fields to target the element and check it. Here is the working script:
do JavaScript "var elements = document.getElementsByName('Level');
for (i=0;i<elements.length;i++) {
if(elements[i].value == 'p;29') {
elements[i].checked = true;
}
}" in doc

How to check if any of a series of checkboxes are checked in javascript

I have a series of checkboxes that I populate using a foreach loop (php). The code looks like this:
<input type="checkbox" name="artist_group[]" id="{{$fb_data['fbid']}}" class="input-hidden" data-name="{{$fb_data['name']}}" value="{{$fb_data['fbid']}}" style="display:none;" />
<label for="{{$fb_data['fbid']}}">
<img src="https://graph.facebook.com/{{$fb_data['fbid']}}/picture?width=200&height=200" width="140" height="140" alt="{{$fb_data['name']}}"/>
<article class="artistName">{{$fb_data['name']}}</article>
</label>
What I would like to do is check if any of the checkboxes are checked using javascript. However, I can't do this using the "getElementById" because I want each checkbox to have a unique id (so I can pull the data). I have the name of the checkbox group as an array, so I can send all of the checked boxes to my backend. Can I do the following?:
if (document.getElementByName('artist_group').checked) {
alert("checked");
}
Thank you for your help.
You have iterate over the checkboxes and test whether any of them is checked or not. Note that the method name is getElementsByName (Elements with s):
var boxes = document.getElementsByName('artist_group[]');
var checked = false;
for (var i = 0, l = boxes.length; i < l; i++) {
if (boxes[i].checked) {
checked = true;
break;
}
}
If you are not opposed to newer JavaScript methods, you can also use Array#some:
var checked = Array.prototype.some.call(boxes, function(input) {
return input.checked;
});
With jQuery, it's even simpler:
var checked = $('input[name="artist_group[]"]:checked').length > 0;
Since you tagged jQuery in your question as well, you can use jQuery's $.each.
Just select the elements by the class and not id.
$('.input-hidden').each(function() {
//this will iterate through all checkboxes
if ($(this).is(':checked')) {//Per #Felix's comment, this.checked is a more native way of doing it, I personally just prefer to use $(this) when I'm in jQuery context, to be consistent. Using this.checked is quicker though.
//this will apply just to the checked checkboxes
}
});
You can also get ONLY the selected checkboxes by:
$('input:checked').each(function() {
//this will only apply to selected checkboxes
});
Hope this helps!
As you also used the jQuery tag for your question: IF you're using jQuery anyway (don't just add it only for this task, that's an overkill!):
if ( ! $('input[name="artist_group"]').is(':not(:checked)') ) {
// all are selected
}

Highling radio buttons with JS

Here is my radio button:
<label>
<input type="radio" id="chk1" name="chooseSupp" onclick="change(this);">
Chosen Supplier
</label>
Here is my Javascript which highlights the cell:
<script type="text/javascript">
function change(obj) {
var tr=obj.parentNode.parentNode;
tr.style.backgroundColor=(obj.checked)? 'red' : 'transparent';
}
</script>
The problem is, when I click on a radio button, it highlights okay but then when I click on a different radio button, it is also highlighted, but the highlighting on the first button does not go away.
My radio button is in a loop, not sure if that is relevant to any possible solution.
Any ideas?
function change(obj) {
var tr=obj.parentNode.parentNode.parentNode;
var tbl = tr.parentNode;
var inputs = tbl.getElementsByTagName("input");
for(var i = 0;i<inputs.length;i++)
inputs[i].parentNode.parentNode.parentNode.style.backgroundColor='transparent';
tr.style.backgroundColor=(obj.checked)? 'red' : 'transparent';
}
Make all other inputs transparent first. then apply your style to the new one.
you could alternatively check if the other inputs are checked to, like you do for the current input. That would be usefull if you work with checkboxes.

One function that will work with multiple elements

I have about 50 RadioButtonList on a form with a checkbox next to them. When you check the checkbox the radioButtonList gets enabled. I have the code to make it work for one but I am looking for a way to write one function that will work for all 50 RadioButtonList instead of writing fifty different functions. The checkboxes and RadioButtonLists are in a table. Thanks in advance
<script type="text/javascript">
function dis() {
var controlObject = document.getElementById('MainContent_RadioButtonList1');
controlObject.removeAttribute('disabled')
RecursiveDisable(controlObject);
return false;
}
function RecursiveDisable(control) {
var children = control.childNodes;
try { control.removeAttribute('disabled') }
catch (ex) { }
for (var j = 0; j < children.length; j++) {
RecursiveDisable(children[j]);
//control.attributes['disabled'].value = '';
}
}
function able() {
var controlObject = document.getElementById('MainContent_RadioButtonList1');
controlObject.setAttribute('disabled')
RecursiveDisable2(controlObject);
return false;
}
function RecursiveDisable2(control) {
var children = control.childNodes;
try { control.setAttribute('disabled') }
catch (ex) { }
for (var j = 0; j < children.length; j++) {
RecursiveDisable2(children[j]);
//control.attributes['disabled'].value = '';
}
}
function disable() {
var checkbox = document.getElementById('MainContent_CheckBox1');
if (
checkbox.checked == true)
dis();
else
able();
}
</script>
<table>
<tr>
<td><asp:CheckBox ID="CheckBox1" runat="server" OnClick="return disable();" /></td>
<td>
<asp:RadioButtonList ID="RadioButtonList1" runat="server" Enabled="false">
<asp:ListItem value="1">ListItem 1</asp:ListItem>
<asp:ListItem value="2">ListItem 2</asp:ListItem>
<asp:ListItem value="3">ListItem 3</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td><asp:CheckBox ID="CheckBox2" runat="server" OnClick="return disable();" /></td></td>
<td>
<asp:RadioButtonList ID="RadioButtonList2" runat="server" Enabled="false">
<asp:ListItem value="1">ListItem 1</asp:ListItem>
<asp:ListItem value="2">ListItem 2</asp:ListItem>
<asp:ListItem value="3">ListItem 3</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
</table>
REWRITE
I believe that the action you want to perform is to toggle the enabled/disabled state of a drop down list that matches a given radio button. The radio buttons and drop down lists are stored in a table. If a radio button is "checked", you want the drop down list enabled. Otherwise, you want it disabled.
Create a custom attribute in the markup that binds the checkbox to its target drop-down list. For example, modify the markup like this:
<asp:CheckBox ID="CheckBox1"
runat="server"
target="DropDownList1" />
Then, iterate over all the checkboxes on the form using a piece of JavaScript and set an event handler for them.
(I chose target as my attribute name below, you can use whatever you like to save keystrokes, so long as it doesn't collide with an established DOM attribute.)
function setCheckBoxHandlers()
{
var boxes = document.getElementsByTagName("input");
for (box in boxes)
{
// Only bind those that have a target attribute; leave all
// others alone.
if (box.getAttribute("type").toLowerCase() == "checkbox" &&
box.getAttribute("target") != null)
{
// Set up the onclick handler.
box.onclick = toggleCheckBox;
}
}
}
function toggleCheckBox(e)
{
// Mozilla browsers pass the event source as argument zero. Microsoft
// doesn't; get it from the window.
e = e || window.event.source;
var target = document.getElementById(e.getAttribute("toggleTarget"));
if (e.checked)
{
target.removeAttribute("disabled");
}
else
{
target.setAttribute("enabled");
}
}
As this is a drop-down list, I see no need to enable/disable the idividual ListItems within it.
Your HTML looks like it might actually be generated (if not, it's likely a candidate for it), so this should work pretty well provided that I've understood the problem correctly.
UPDATE
I have it working, but you're right: ASP.NET's funky table-based layouts wreak havoc with what you want to do. Good news is, it CAN be done. :)
You can find the working solution at http://jsfiddle.net/tyrantmikey/RxY5s/. Note the following:
During document load, you need to call setCheckBoxHandlers.
I had to split the function into two parts. One for the on click handler, the other for the tree traversal.
The checkbox should include a TARGET attribute that points to its matching radiobuttonlist. (Its value should be the ID of the radio button list.)
You don't need to set the onclick handler in the tag; this will happen automatically when you call setCheckBoxHandlers. This is a nice solution, as it makes it easier to add new rows to your table later.
Hope this does the trick for you!
<asp:CheckBox ID="CheckBox1" runat="server" OnClick="return disable(this);" />
function disable(c) {
return c.checked ? dis() : able();
}

Categories