Asp radio buttons is not calling javascript function - javascript

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.

Related

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!

How to invoke a onclick event on specific dynamic button on javascript

I am working on a usercontrol file which contains a textbox and a button.
The control renders multiple records on one page and hence creating and rendering the textboxes and buttons dynamically.
I am trying to invoke a javascript function to validate whether the textbox has value. My problem is I am not able to determine which button is being clicked as it is dynamically created. (As I am integrating this control in parent page gridview and hence it becomes dynamic.)
Please advise community. What I am assuming is I am not able to set the index to the button Id I am retrieving before calling the closure.
I tried following few links available on this website but finally I have post my issue here to seek specific answer.
Below is my code snipeet.
HTML:
function validateSubmit() {
var btn = document.getElementsByClassName('frmBtn').length;
var btnId = document.getElementById('<%=commentSubmitButton.ClientID%>').id;
for (var j = 1; j <= btn; j++) {
(function(j){
btnId[j].onclick = function(){
alert('INSIDE CLICK');
var e = document.getElementsByClassName('frmTextBox')[j].value;
if (e == '') {
document.getElementsByClassName('lbl')[j].style.display = 'block';
}
}
})(j);
}
}
<div class="frmContent">
<p style="float: right; padding-top: 2em;">
<asp:Button ID="commentSubmitButton" runat="server" Text="Submit" CssClass="frmBtn" OnClientClick="validateSubmit(this);" />
</p>
<p>
<label for="txtComment" class="frmLabels">
Type Comment Here
<label id="lblStar" class="lbl" style="display:none;color:red;">*</label>
</label>
<asp:TextBox ID="txtComment" runat="server" Height="60" Width="75%" TextMode="MultiLine" CssClass="frmTextBox" ></asp:TextBox>
</p>
</div>
JAVASCRIPT:
Finally I figured it out.
I wonder why I kept inclining toward conventional JavaScript approach when such things can be achieved easily with so nice and so advanced jquery. I observed few concepts on jquery and it helped me made this little thing work in very few lines. Here is the relevant code I wrote with jquery.
It is working now satisfactorily. Thank you all.
jquery code
function validateSubmit(btnid)
{
//debugger;
var txtbox = $(btnid).parent().parent().find('.frmTextBox')[0];
var lblRequired = $(btnid).parent().parent().find('.lbl')[0];
if (txtbox.value == '') {
lblRequired.style.display = 'block';
event.preventDefault();
} else {
lblRequired.style.display = 'none';
}
}

I need to select asp:radiobutton(asp control) while clicking on html table cell

I have a table with multiple cells each having one asp radio button control:
I want to be able to check/uncheck radio button(which is asp control, not html) when i click anywhere on table cell. I want to write one javascript/jquery function to which i can pass value from td 'onclick' event and then check/uncheck the corresponding radio button present inside that 'td'. Is it possible?
Why won't this work for you?
<td id="td1" onclick="checkRadioButton($('#<%=rdnQ10aOption1.ClientID%>'));" >
<asp:RadioButton ID="rdnQ10aOption1" runat="server" GroupName="Q10a" />
</td>
function checkRadioButton(radioButt) {
radioButt.prop("checked", true);
}
It is my first answer applied to your code.
Yes you can, use ClientID to select the control with JQuery.
You must put the Jquery in your .aspx file.
<asp:RadioButton ID="Foo" runat="server" />
To select it with Jquery use:
$('#<%=Foo.ClientID%>')
And if you want to do it in a more generic way read Rick Sthrahl's post: A-generic-way-to-find-ASPNET-ClientIDs-with-jquery
Basically it boils down to:
function $$(id, context) {
var el = $("#" + id, context);
if (el.length < 1)
el = $("[id$=_" + id + "]", context);
return el;
}
In simple usage:
alert( $$("Foo").attr("id") );
Or if I want to be specific about the container:
alert( $$("Foo",$("#wrapper")).attr("id") );
My main problem is, i cannot access the control id directly since i have to write generic function which should accept control id I am passing as parameter and there i should be able to retrieve and access it.
So i passed 'this.children' as parameter which sends childnodes collection of td.(in my page, radiobutton is always first child of td. so i can just pass 'this.children' as parameter in all onclick functions without specifying rdn btn id )
I retrieved it using $('#' + tdchild[0].id).
<td onclick="checkRadioButton(this.children);" >
<asp:RadioButton ID="rdnQ10aOption1" runat="server" GroupName="Q10a" />
</td>
function checkRadioButton(tdchild) {
$('#' + tdchild[0].id).prop("checked", true);
}

Updating of the asp.net dropdown control using javascript

In my ASP.Net default.aspx, I have dropdown list control and following javascript code
<asp:DropDownList ID="ddlGenres" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="EntityDataSource2" DataTextField="cityID" DataValueField="cityID" OnSelectedIndexChanged="ddlGenres_SelectedIndexChanged" ClientIDMode="Static" >
<script type="text/javascript">
var ddlClientID = '<%=ddlGenres.ClientID%>';
//document.getElementById(ddlGenres)
function SetddlVal(nIndx)
{
//$("#ddlGenres")
var ddlListSelect = document.getElementById(ddlClientID);
ddlList.SelectedIndex = nIndx;
}
</script>
====================================================================
In a external javascript file, I am calling the function SetddlVal.
I debugged the code and the ddlList selectedIndex is successfully changed within the script.
=====================================================================
The issue I am facing is, when the SelectedIndex value is changed in the javascript, The ddlGenres_SelectedIndexChanged code is not being triggered.
Please let me know if I am missing anything.
Thanks
Nate
In javascript the property of an <select> input is selectedIndex not SelectedIndex.
Change your function to this:
function SetddlVal(nIndx)
{
var ddlListSelect = document.getElementById('<%=ddlGenres.ClientID%>');
ddlListSelect.selectedIndex = nIndx;
}

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