One function that will work with multiple elements - javascript

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();
}

Related

RadComboBox on OnClientItemChecked get sequence

I actually want to achieve in a multi select checkbox to have a sequence. When i access OnClientItemChecked
on RadComboBox i get alert which is working here is the HTML code below.
<telerik:RadComboBox RenderMode="Lightweight" OnClientItemChecked="OnClientItemChecked" ID="cbo_Tag" runat="server" CheckBoxes="true" EnableCheckAllItemsCheckBox="true" Skin="MetroTouch" CssClass="form-control" Width="100%" />
Here is the code for javascript function below
function OnClientItemChecked(sender, eventArgs) {
var item = eventArgs.get_item();
console.log(item)
console.log(sender)
console.log(eventArgs)
alert("Checked");
}
i need to access by sequence when i select in checkbox sequentially one by one it i need to sequence the checkbox in an array with their value. If i use Checkbox All then their sequence should be from top to bottom how can i achieve so.Here is a image e.g.
You can try the following:
<script type="text/javascript">
var checkItems = []
function OnClientItemChecked(sender, eventArgs) {
var checkItems = eventArgs.get_checkedItems();
}
</script>
Whenever you click on a unchecked checkbox the checkBox id will be added to the checkBoxIds array.

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");
});

jquery issues with tr click changes checkbox

My condition: I have a checkbox inside <tr>, written in <asp:repeater> on an user control, placed in an aspx page.
My goal: when <tr> is clicked, JQuery changes (or specifically, toggles) the checkbox checked attribute as well as the css class of the <tr> itself.
I've tried several methods, and so far, only this one works for me: http://jsfiddle.net/xixonia/WnbNC/
, but unfortunately, all of the checkboxes are toggled instead of only the selected one, just like the example on jsfiddle.net. moreover, if I clicked on the checkbox itself, all of the other checkboxes are checked instead of the clicked one.
What I've done:
$(".moduleTableItem").click(function (e) {
// Toggles CSS
if (!$(this).closest('tr').hasClass("tr.active")) {
$(this).closest('tr').css('background-color', 'blue');
$(this).closest('tr').addClass("tr.active");
} else {
$(this).closest('tr').css('background-color', 'red');
$(this).closest('tr').removeClass("tr.active");
}
// Toggles Checkbox
$(':checkbox').prop('checked', function (i, value) {
return !value;
});
ASP:
<asp:Repeater ID="repModuleGeneral" runat="server" EnableViewState="true">
<ItemTemplate>
<tr id="trModuleGeneral" class="moduleTableItem" runat="server">
<td>
<input type="checkbox" id="cbxSelect" class="cbxSelect" runat="server" autopostback="false" /></td>
<td>
<asp:Label ID="lblNo" runat="server" /></td>
</tr>
</ItemTemplate>
</asp:Repeater>
This is my first question. Please let me know if my question is somewhat unclear. Any code snippets or working solution would be appreciated.
Thank you.
Change
$(':checkbox').prop('checked', function (i, value) {
To
$(this).find(':checkbox').prop('checked', function (i, value) {
this used here will point to the current clicked tr.
This wont work if you directly click on the checkbox. Why, you ask? Because the checkbox lies inside tr, to which you've assigned a click event to. So, when click on a checkbox which is unchecked, these two actions are triggered :
Checkbox selected because of default checkbox action - checkbox set to true.
The click on the tr is triggered. You've got a checkbox prop event there. Reverts the selection done by default action.
So its a basic counter action, which cancels the default actions of the checkbox. To rectify this, you'll have to check if the default target is NOT a checkbox and then run the prop function :
$(".moduleTableItem").click(function (e) {
// Toggles CSS
if (!$(this).closest('tr').hasClass("tr.active")) {
$(this).closest('tr').css('background-color', 'blue');
$(this).closest('tr').addClass("tr.active");
} else {
$(this).closest('tr').css('background-color', 'red');
$(this).closest('tr').removeClass("tr.active");
}
//check here
if (!$(e.target).is(":checkbox")) {
// Toggles Checkbox
$(this).find(':checkbox').prop('checked', function (i, value) {
return !value;
});
}
});
Demo : http://jsfiddle.net/hungerpain/Kph8M/
But, just as a side thought, if you have control over IDs generated over the checkboxes, you could assign the same id as the for attribute in the label. Your HTML would look like this :
<tr class="moduleTableItem">
<td>
<input type="checkbox" id="cbxSelect1" class="cbxSelect" />
</td>
<td>
<label for="cbxSelect1">Text</label>
</td>
</tr>
Not the id attribute of the checkbox and the for attribute of the label. A lot of hassle will be solved by this. And you could use the change event of the check box. Also, did some optimisations to your code. It would look something like this :
$(".moduleTableItem :checkbox").change(function (e) {
//cache this - you are using it more than once.
var $tr = $(this).closest('tr');
// check if class is active - I took away if..else and made it ternary
var bg = $tr.hasClass("tr.active") ? 'red': 'blue';
//set css and toggleClass. Anyway you're switching everytime. Why not use toggle?
$(this).closest('tr').css('background-color', bg).toggleClass("tr.active");
});
Demo : http://jsfiddle.net/hungerpain/Kph8M/4/

Radio Buttons clear check when clicked again

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);
});
}

How do I select the foot in numeric paging? RadGrid

I currently have a js function that binds onchange to onbeforeunload or a confirmbox only if there are changes on the grid.
I am trying to select the footer paging anchors so that it doesn't trigger for confirm or onbeforeunload. The user should select the numeric paging regardless if there are changes or not on the grid.
There is no ID or class name on the anchors so I'm having trouble accessing it.
Thanks in advance.
RadGrid properties:
<telerik:RadGrid
runat="server"
ID="DataGridFooItems"
AllowSorting="true"
AutoGenerateColumns="false"
EnableViewState="True"
GridLines="Vertical"
AllowPaging="True"
PagerStyle-Mode="NumericPages">
<MasterTableView
AllowPaging="true"
DataKeyNames="foopersonID,fooItemID"
AllowAutomaticDeletes="true"
CommandItemDisplay="None"
NoMasterRecordsText="" >
This is what the .aspx generates below:
<TFOOT>
<TR class=rgPager>
<TD colSpan=20>
<TABLE style="WIDTH: 100%" border=0 cellSpacing=0>
<TBODY>
<TR>
<TD class="rgPagerCell NumericPages">
<DIV class="rgWrap rgNumPart">
<A class=rgCurrentPage onclick="returnfalse;"href="javascript:__doPostBack('ctl00$ph$FOO$rgItems$ctl00$ctl03$ctl01$ctl02','')"><SPAN>1</SPAN></A><SPAN>2</SPAN><SPAN>3</SPAN><SPAN>4</SPAN><SPAN>5</SPAN><SPAN>6</SPAN><SPAN>7</SPAN><SPAN>8</SPAN><SPAN>9</SPAN><SPAN>10</SPAN><SPAN>...</SPAN>
</DIV></TD></TR></TBODY></TABLE></TD></TR></TFOOT>
UPDATE: Answer!
Found it! with some research and tweaking of a similar Telerik Solution.
I composed this:
I declared a variable which selected a class.
Then I searched through the object for all the anchors.
Afterwards, I used a loop through anchors if it is not on the
current page(should not have a click event, since the user is
already on the page.) && if the anchor has a href of __doPostback.
Then i set the attribute onclick event to a confirmation. This step
wrapped the __doPostback.
Source: http://www.telerik.com/community/forums/aspnet-ajax/grid/radgrid-paging---pageindexchanged-event-issue.aspx
function preventPromptOnFooter() {
var pagerCell = $('[class="rgPagerCell NumericPages"]')
var anchors = $(pagerCell).find('a');
for (var i = 0; i < anchors.length; i++) {
if (anchors[i].className != "rgCurrentPage" && anchors[i].href.indexOf("javascript:__doPostBack") > -1) {
var clickScript = anchors[i].attributes["onclick"].value;
anchors[i].onclick = disableOnbeforeUnloadForFooter;
}
}
function disableOnbeforeUnloadForFooter() {
window.onbeforeunload = null;
}
}
You could try:
var pageLinks = document.querySelectorAll(".rgWrap.rgNumPart a");
Which works in Chrome, Firefox 3.5+, ie8+, Opera 10 and Safari 3.2+. If you have to support older browsers, you could try a combination of getting the parent div by its classname and then using getElementsByTagName('A'). Or use a library like jQuery to implement advanced CSS selectors cross browser.
Found it! with some research and tweaking of a similar Telerik Solution.
I composed this:
I declared a variable which selected a class.
Then I searched
through the object for all the anchors. anchors
Afterwards, I used a loop
through anchors if it is not on the current page(should not have a
click event, since the user is already on the page.) && if the
anchor has a href of __doPostback.
If step (3.) is true, it set the attribute onclick event to a confirmation. This step wrapped the __doPostback.
Source:
http://www.telerik.com/community/forums/aspnet-ajax/grid/radgrid-paging---pageindexchanged-event-issue.aspx
function preventPromptOnFooter() {
var pagerCell = $('[class="rgPagerCell NumericPages"]')
var anchors = $(pagerCell).find('a');
for (var i = 0; i < anchors.length; i++) {
if (anchors[i].className != "rgCurrentPage" && anchors[i].href.indexOf("javascript:__doPostBack") > -1) {
var clickScript = anchors[i].attributes["onclick"].value;
anchors[i].onclick = disableOnbeforeUnloadForFooter;
}
}
function disableOnbeforeUnloadForFooter() {
window.onbeforeunload = null;
}
}

Categories