RadioButtonList not firing SelectedIndexChanged every time - javascript

I have a RadioButtonList with "Not Applicable", "Not Available", "Leave" and "Available" options.
I am throwing confirm message box on click of "Leave" in RadioButtonList from Server side as below
protected void rdlUser_SelectedIndexChanged(object sender, EventArgs e)
{
radWindowManager.RadConfirm("Are you sure you want to take leave?", "confirmLeave" + this.ClientID, 300, 100, null, "");
}
If user clicks "Cancel", then it will automatically selects "Available" with below code.
The following is the javascript code to "Ok" or "Cancel" leave.
function confirmLeave<%=this.ClientID%>(arg) {
if (arg == true) {
alert("User has selected Leave.")
}
else {
var rdlUser = docment.getElementById("<%= rdlUser.ClientID %>");
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}
If the user clicks "Leave" for the 2nd time, the SelectedIndexChanged does not fire at all.
I am flexible to move Server Side code to Client side also.
Update
The following is the relevant HTML code
<table id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser">
<tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT01" disabled="disabled" onclick="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser$0\',\'\')', 0)" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0">Not Applicable</label></span></td>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT02" onclick="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser$1\',\'\')', 0)" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1">Not Available</label></span></td>
</tr><tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT03" onclick="javascript:setTimeout('__doPostBack(\'ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser$2\',\'\')', 0)" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2">Leave</label></span></td>
</tr><tr>
<td><span class="available"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3" class="Available" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT04" checked="checked" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3">Available</label></span></td>
</tr>
Update 2
I am stuck here -- I need to point this.ClientID of RadioButtonList to $this of jQuery. Thats it. There by I can execute the 2nd Answer provided by #smoksnes
Update 3
If user selects "Not Available" or "Leave" then it should throw error message as "Do you want to take Leave?" and if he selects "Cancel", then the selection of RadioButtonList should point out to "Available". Otherwise it should select "Not Available" or "Leave" accordingly.

Since you're open to the idéa of moving the code to the client instead. Remove the OnSelectedIndexChange on your radiobutton to skip the postback. You should be able to do something like this instead:
// Put this in a script-tag.
$(document).ready(function(){
$('#<%=this.ClientID%>').change(function(){
var radioBtnId = this.id;
radconfirm('Are you sure you want to take leave?', function(arg){
if (arg == true) {
alert("User has selected Leave.")
}
else {
var rdlUser = docment.getElementById(radioBtnId);
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}
});
});
})
Below is a snippet that uses id's without server code.
$('#radio1').change(function(e){
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to take leave?', function(arg){
// Not really sure what you want to do here...
if (arg == true) {
alert("User has selected Leave.")
}
else {
// Select "Available instead".
$this.siblings('input').prop('checked',true);
// Unselect "Leave"
// With javascript
var rdlUser = document.getElementById(radioBtnId);
rdlUser.checked = false;
// With jQuery
$this.prop('checked', false);
}
});
});
// Mocked for now...
function radconfirm(value, callback){
var result = confirm(value);
callback(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="radios" id="radio1" value="Leave"/> <label for="radio1" >Leave</label>
<input type="radio" name="radios" id="radio2" value="Available"/> <label for="radio2" >Available</label>
UPDATE:
I've updated the script to fit the new HTML. Here we bind the event to the monday control instead. Note that you might want to set a CssClass on your control instead of using ID. Then you can use the same script for all your controls (MyMonday, MyTuesday etc). It would look something like this:
<asp:MyControl CssClass="day-control" runat="server" id="MyMondayControl" />
If so, you should be able to change the script below to start with:
$('.day-control input').change....
Otherwise you need to use the clientID.
$('#<% MyMondayControl.ClientID %> input').change ....
Don't know why onclick="javascript:setTimeout" is getting added for
the HTML
That's because you are using server controls with AutoPostBack for your radiobuttons. Remove that and you should be fine. Read more about it in this question.
In the snippet below I've taken the liberty to assign to CSS-classes to the different radiobuttons. One will determine when to run the "check if leave"-script. And one is for knowing which radiobutton to select if the user chooses to stay. The css classes are leave-check and select-if-not-leave. You can add them with the CssClass property.
You might also want to check what HTML is rendered. The HTML you provided is using table with tr, so just make sure that the css-class is actually rendered on the input. Otherwise you will need to adjust the selector.
// Change to the id of the table instead. Something like:
// $('#<% MyMondayControl.ClientID %> input').change ....
// Here I just the ID generated in the HTML, but you shouldn't use that one.
$('#ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser span.leave input').change(function(e){
e.preventDefault();
var radioBtnId = this.id;
var $this = $(this);
radconfirm('Are you sure you want to take leave?', function(arg){
// Not really sure what you want to do here...
if (arg == true) {
alert("User has selected Leave.")
}
else {
// Select "Available instead".
// Here we use the css class "select-if-not-leave" to find the element which should be selected if the user decides to stay.
var $parent = $this.closest('table') // Get the table.
// Select the available input.
$parent.find('span.available input').prop('checked',true);
// Unselect "Leave" With javascript
var rdlUser = document.getElementById(radioBtnId);
rdlUser.checked = false;
// Unselect "Leave" With jQuery (You only need one)
$this.prop('checked', false);
}
});
});
// Mocked for now...
function radconfirm(value, callback){
var result = confirm(value);
callback(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser">
<tr>
<tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT01" disabled="disabled" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_0">Not Applicable</label></span></td>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT02" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_1">Not Available</label></span></td>
</tr><tr>
<td><span class="leave"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2" class="Leave" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT03"/><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_2">Leave</label></span></td>
</tr><tr>
<td><span class="available"><input id="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3" class="Available" type="radio" name="ctl00$ContentPlaceHolder1$MyUser$MyMonday$rdlUser" value="SLOT04" checked="checked" /><label for="ctl00_ContentPlaceHolder1_MyUser_MyMonday_rdlUser_3">Available</label></span></td>
</tr>
</table>
UPDATE 2:
When I write jQuery script in Day UserControl, then I can use only .leave and .available classes but not .day-control. 2. When I write
the jQuery script in UserControl where MyMonday, MyTuesday,...
MyFriday are declared, then I can use only .day-control but not .leave
and .available classes. #smoksnes Please address this ambiguity.
Where you put you script does not matter, as long as the script looks the same. Preferably, you should put it in a js-file together with your other scripts. Here's a little info how the script and jQuery selectors works:
If you use .day-control span.available input it will first look for a some element with the css class day-control, and a element that is a span WITH css-class available, and lastly an input under the span. If there are several elements that fulfills the criterias I just mentioned it will return all these elements. This script should only be rendered once, since it will capture the events for all your DayUserControl, since they all share the same css class day-control.
However, if you use #<%=this.ClientID%> span.leave input it will start by looking for the element with the specific id (this.ClientID) and there should be only one of those. That is why you need to render that particular script once for every DayUserControl, since it will be unique for that specific user control.

Pass caller object to radconfirm function.(http://docs.telerik.com/devtools/aspnet-ajax/controls/window/alert,-confirm,-prompt-dialogs/radconfirm-dialog).
Pass caller object from server
protected void rdlUser_SelectedIndexChanged(object sender, EventArgs e)
{
//var oConfirm = radconfirm(text, callBackFn, oWidth, oHeight, callerObj, oTitle, imgUrl);
radWindowManager.RadConfirm("Are you sure you want to take leave?", "confirmLeave", 300, 100, null, "");
}
One javascript function to validate all controls in a list.
function confirmLeave(arg) {
if (arg == true) {
alert("User has selected Leave.")
}
else {
//get callerid and validate
var rdlUser = docment.getElementById("<%= rdlUser.ClientID %>");
var radioButtons = rdlUser.getElementsByTagName('input');
radioButtons[1].checked = true;
}
}
I referred documentation and I didn't test this code hope this helps.

Related

Javascript function to send alert firing regardless of value returned

The function created to send an alert based on a radio box's value returning as null is firing and sending alert while radio box has a value that should not be null. Somewhere else on the page is a function that hides the tables these radios appear on, and is what initially made this task out of my reach. If this div didn't hide, and these tables weren't generated dynamically then it could have been solved by adding a required attribute to the radio. This actually works as long as the div is showing, however breaks when hidden. I've essentially been tasked to take the long way around making this radio required.
Here is the javascript
<script type="text/javascript">
$(function validate() {
$(document).submit(function() {
<%For z = 0 to TotalUnits - 1%>
if ($("input[name='checkradio<%=z%>']:checked").length == 0)
alert("Select Yes or No for Needs Repair checkbox <%=z%>");
return false;
}
<%Next%>
$("submitbutton").click(function() {
$("#formID").submit();
document.getElementsByName("checkradio").addEventListener('click',
validate);
});
});
});
</script>
Here is the HTML
<label id="checklabel" name="checklabel">The Vehicle Requires Repair</label>"
<label id="yesradio">
<input type="radio" ((name="checkradio" & z)) value="1" id="Radio1"> Yes</label>
<label id="noradio">
<input type="radio" ((name="checkradio" & z)) value="0" id="Radio0"> No</label>
Here is the script that hides the div (I cleaned the concat. but left the meat in its own tags)
<script>
<%for z = 0 to TotalUnits - 1%>
$( document ).ready(function() {
$("div.section<%=z%>").hide();
});
<%next%>
</script>
<%response.write(TmpString)%>
Here is my submit button (stripped off the label)
<input value="Submit" type="submit" id="submitbutton" name="submitbutton"
onsubmit="validate()">
The alert should only fire when the submit button is pressed and the value of the radio is null.
Because each radio button is a control it is own right, you need to check if any of the controls that are linked together (via the name attribute) are checked.
Firstly, getElementsByName() returns an array (notice the s on Elements), so there is no .value for you to check.
(Oh, and be aware that having multiple <label id="yesno"> is invalid, as elements need to have a unique id attribute. In this case you're probably best just removing the id="yesno" completely.)
But it's a lot, lot easier to do this via jQuery...
<script type="text/javascript">
$(function() {
$(document).submit(function() {
<%For z = 0 to TotalUnits - 1%>
if ($("input[name='checkradio<%=z%>']:checked").length == 0)
alert("Select Yes or No for Needs Repair checkbox <%=z%>");
return false;
}
<%Next%>
$("submitbutton").click(function() {
$("#formDVIR").submit();
});
});
});
</script>
By using the selector of input[name='checkradio<%=z%>']:checked you're asking jQuery to find all input controls with a name of checkradio1 (or whatever z is) and only those which are checked. If the length of the resultant jQuery object is more than 1 you know at least one is selected
push me or so
const myId=document.getElementById(“myId”);
myId.addEventListener(“click”, function () { alert(“message and stuff”)});

Asp radio buttons is not calling javascript function

I am working on using asp :radio buttons. I am trying to use 2 radio buttons so that if any one of them is selected then other will be unchecked. I am calling JavaScript function on change event of these buttons. That function will add some values and return the out put in the textboxes.I tried to use normal asp buttons then switch to radio button groups and now trying radio button list. need to call javascript function on radio button change event.These buttons will checked and unchecked but java script function is not returning correct values. I guess there are some naming conventions which are not correct or something is not working . looking forward for help to fix this. Neither one of these 3 way is working.
My test.aspx file contains
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="span2">Test Career:</div>
<div class="span8">
<asp:RadioButton ID="TestCareerList" runat="server" clientmode=Static Text="MasterDegree">
</div>
</ContentTemplate>
</asp:UpdatePanel>
Document.ready function in aspx page
$(document).ready(function () {
$("input:radio").click(function ()
{
updateYears();
}
}
javascript function is:
function updateYears() {
var yrsDocTemp = parseFloat(yrsDoc);
var yrsMastTemp = parseFloat(yrsMast);
if ($("ContentPlaceHolder2_drpEmplClass").val() != "" && $("#ContentPlaceHolder2_StudentCareerList]").SelectedValue!= "") {
var updateValue = 0;
//Get EmplCalss
if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GA") {
updateValue = updateValue + 1;
}
else if ($("#ContentPlaceHolder2_drpEmplClass").val() == "GAF" || $("#ContentPlaceHolder2_drpEmplClass").val() == "GAP") {
updateValue = updateValue + .5;
}
if ($("#ContentPlaceHolder2_Career").Text =="DoctoralDegree")
{
yrsDocTemp = yrsDocTemp + updateValue;
}
else if ($("#ContentPlaceHolder2_Career").Text == "MastersDegree") {
yrsMastTemp = yrsMastTemp + updateValue;
}
}
//Update the fields
$("#ContentPlaceHolder2_drpYearsDoctoral").val(yrsDocTemp);
$("#ContentPlaceHolder2_drpYearsMasters").val(yrsMastTemp);
}
I am calling this function under document.ready function like this-
$("input:RadioButtonList[ID=^TestCareerList").change(function(){
updateYears();
});
$("#ContentPlaceHolder2_drpEmplClass").change(function () {
updateYears();
});
When I debug the javascript code I see the names of buttons have been changed.
<tr>
<td>
<input id="ContentPlaceHolder2_TestCareerList_0" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="MastersDegree" />
<label for="ContentPlaceHolder2_TestCareerList_0">Master</label>
</td>
<td><input id="ContentPlaceHolder2_TestCareerList_1" type="radio" name="ctl00$ContentPlaceHolder2$TestCareerList" value="DoctoralDegree" />
<label for="ContentPlaceHolder2_TestCareerList_1">Doctoral</label>
</td>
</tr>
Kindly looking for help.
This is trying to bind to your server-side elements:
$("input:RadioButtonList[ID=^TestCareerList")
But JavaScript has no knowledge of the server-side code. It only operates on the client-side code. And, as you've noticed, your client-side HTML is different. So your JavaScript needs to target that code. Something like this:
$("input:radio[ID=*TestCareerList")
The same would be true for any other selectors you have. As you're discovering, WebForms controls are famously not great for finely controlling your client-side code. ASP.NET MVC makes this a lot easier, but may be a pretty fundamental shift for what you're doing.
One thing that may help is setting your ClientID property on some controls to Static. Take care when doing this however and debug your HTML accordingly, because if you end up with repeated id values in your HTML then it's invalid and the behavior of the JavaScript when selecting on that id would be undefined.

ASP.NET MVC 4 Having trouble selecting the correct input element using js/jquery

I'm working with a form that I've built using HTML helpers, like so:
#using (Html.BeginForm("CreateNewRoom", "Admin", FormMethod.Post, new { #enctype = "multipart/form-data", #class = "form-vertical", style = "margin-top:-30px" }))
{
<fieldset>
<legend>Create a new Room</legend>
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Room name:</label>
<div>
#Html.TextBoxFor(x => x.name, new { #id = "room", #class = "form-control-static", #style = "margin-bottom:5px;", #autofocus = "true" })
</div>
</div>
...
<div class="form-toolbar sepa">
<label class="darkBlue toolbar-label">Display:</label>
<div>
#Html.RadioButtonFor(x => x.display, "True") Yes&nbsp
#Html.RadioButtonFor(x => x.display, "False") No&nbsp
</div>
...
Just in case it helps, Chrome DevTools informs me that this is the HTML being displayed by my radio button helper:
<input id="display" name="display" type="radio" value="True">
" Yes "
<input checked="checked" id="display" name="display" type="radio" value="False">
" No "
I have a Javascript file which dynamically plays with the elements on the page. I would like for js to add a class to an element on the page, to simply change its opacity to 0.5, if it finds that the "No" radio button is selected.
if ($('input[name="display"]').val() === "False") {
if (($('#selectedRoomName')) && ($('#selectedRoomArrow')))
$('#selectedRoomName').addClass('obscured');
$('#selectedRoomArrow').addClass('obscured');
} else {
//sad
}
I've used this block in $(document).ready and in $(input[name="display"]).change, to make js add the class if display is 'False' when the page loads, and also to add it if the 'False' radio button is selected.
However, I found that js had a problem reading the value of the input, and thinks that it is true almost all the time, even if the false button is selected. I'm assuming it must be something to do with the fact that the two inputs have the same name?
My question is, how do I ensure that js always picks the input that is currently selected, and will this make sure that it reads the correct value?
UPDATE: I have changed $('input[name="display"] to $('input[name="display"][checked="checked"]'), in an effort to make js home in on whichever radio button is checked. This solves the problem where js did not know which button was checked on page load. However, now it always targets whichever button was checked on page load, instead of the button that's actually checked currently.
Apologies if I seem like a complete novice, but I am, so...
Any and all suggestions on how to better organise my code are welcome; I'm very unfamiliar with best practises in web dev.
Thanks!
Just change the following line in your change event from :
if ($('input[name="display"]').val() === "False") {
to:
if ($(this).val() === "False") {
This will check for the value of the radio button that is current clicked.
I used a combination of #Ehsan's answer, and a partial solution that I included in an update to the the question.
I decided to place the js block in a function, which took the element whose value I was checking as a parameter:
function checkdisplay(dispradio) {
var a = document.getElementById("selectedRoomName");
var b = document.getElementById("selectedRoomArrow");
if ((a) && (b)) {
if (dispradio.val() === "False") {
a.className += " obscured";
b.className += " obscured";
} else {
a.className = a.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
b.className = b.className.replace(/(?:^|\s)obscured(?!\S)/g, '');
}
}
}
Then I called the function in two places like so:
//first for document load
$(document).ready(function () {
checkdisplay($('input[name="display"][checked="checked"]'));
});
and
//and then for change events
$('input[name="display"]').change(function () {
checkdisplay($(this));
});
Seems like [checked="checked"] was needed to let js know which button was checked on page load, but that then needed to be removed for onchange events, or js would target whichever button was checked on page load, rather than the button that was actually checked!
Many thanks for your partial solution #Ehsan, it helped me come up with this one!

I have two checkboxes that need to be checked before the form may be submitted

<input type="checkbox" value="On" name="policy" id="policy"></font>
<b><font face="Verdana" color="#ff0000" size="1">*</font></b>By checking the box, you are verifying with your digital signature that you have read and agree to all terms and conditions of the FEG agent agreement.
</td>
</tr>
<tr class="gr">
<td class="rowdot_lno">Do you agree?:</td>
<td class="rowdot_lno">
<input type="checkbox" value="On" name="iagree" id="iagree">
<b><font face="Verdana" color="#ff0000" size="1">*</font></b>I understand that I will be charged $24.95.
</td>
</tr>
I have a <form method="post" action="enroller.dhtml" name="mainform" onSubmit="update_prices()"> and a button <input type="submit" value="Continue">
I've tried a few things but to no avail. The form can be submitted without the checkboxes being checked. Here's the latest bit of jQuery I've tried.
$('input[type=checkbox]').each(function () {
if($(this).is(':checked')) {
return true;
}
});
alert("Please select at least one to upgrade.");
return false;
});
Also I found this on fiddle but it's not really working.. I tried to customize it to my needs.
http://jsfiddle.net/shryme/D3Ldj/
If you have an onSubmit on your submit button or add it though jquery, call a function which would :
if ($('input[type=checkbox] :checked').length == 0) {
alert("Please select at least one to upgrade.");
return false;
} else { return true; }
I hope this is what you are looking for.
From this line:
Please select at least one to upgrade
It seems that you need at least one checkbox checked. If that is the case, you could do something like this:
$("form").submit(function(){
var length = $("input[type=checkbox]").not(":checked").length;
if (length > 1) {
alert("Please select at least one to upgrade.");
return false;
}
});
Which checks to see how many checkboxes are not checked, determines if that number is less than the required number, and if it is, triggers the error message.
You can also further simplify the length variable if you are comfortable with CSS selectors:
var length = $("input[type=checkbox]:not(:checked)").length;
Here's an example.
I would suggest to do it with some MVVM framework but here's some code to do it with jQuery. I made it so that the submit button is disabled unless both boxes are checked.
Fiddle with 2 checkboxes and a submit button
function areChecked(){
var is_1_checked = $('#check_1').is(':checked');
var is_2_checked = $('#check_2').is(':checked');
return is_1_checked == is_2_checked == true;
}
function enableButton(val){
$('#submit').attr('disabled', false);
}
$('#check_1').on('click', function(){
if (areChecked())
enableButton(false);
});
$('#check_2').on('click', function(){
if (areChecked())
enableButton(false);
});

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources