what event fires when you click on a asp:checkbox? - javascript

I have something that depending if it is clicked or unclicked will do something. The thing is, that i tried to do an onclick and it will not fire. Is there some other thing that is needed for selecting/unselecting a checkbox?
ASP:
<div id = "gridDiv">
Turn on/off some code:
<asp:Checkbox runat="server" name = "gridlock" id = "gridLockAttribute" />
</div>
ClientSide:
$("#gridLockAttribute").click(function(){
try{
alert("test");
}catch(err){
}
});
It doesnt seem to alert.

ASP.NET may be name-mangling your ID if the control is within another control, so things like $("#gridLockAttribute") won't work. You have to use either:
$("#<%= gridLockAttribute.ClientID %>")
Or:
$('[id$=gridLockAttribute]')
I'd prefer the first method.
Furthermore, if you are trying to get the checkbox to cause a postback automatically, you'll need to set the AutoPostBack attribute on the checkbox to True.

Related

Get value of selected RadioButtonList in aspx

I have an aspx application with a RadioButton list like below:
<asp:RadioButtonList runat="server" ID="rblIsDiesel" RepeatLayout="Flow" RepeatDirection="Horizontal">
<asp:ListItem Text="Diesel" class="carFuel" Value="true" Selected="True" />
<asp:ListItem Text="Petrol" class="carFuel" Value="false" />
</asp:RadioButtonList>
In jQuery I am able to get the Buttons using the below:
var buttons = $('span.carFuel input:radio');
However, I am missing how to get the value of which RadioButton is selected.
What I am trying to do in pseudo code would be:
if (buttonSelected == Diesel) {
alert("Diesel")
}
else {
alert("Petrol")
}
And secondly, fire an alert on toggling between the buttons.
if (valueChanged) {
alert("You changed fuel type");
}
For the first question, I was trying to add :checked to the selector and then use .val() but that is giving me an undefined value. I believe the buttons selector I have above is working OK as if I add a debugger line, I can see 2 objects and the correct client side ids for the radio buttons.
And for the second part, I believe I will need to use the jQuery change event - just not sure on the correct selector.
The key thing you seem to be missing is the ClientID.
When a Web server control is rendered as an HTML element, the id attribute of the HTML element is set to the value of the ClientID property.
With that, what you then do is look for the input control that is checked:
var selectedRB = $('#<%= rblIsDiesel.ClientID %> input:checked');
Then to get the value, just call val().
var selectedValue = selectedRB.val();
But remember, this gets the value of the radiobutton, not the text. So with how you have it setup, you would see true or false as the value. And to be honest, I'm not totally sure I understand why the values would be true and false in your implementation - but that is beside the point.
To capture when the selected radiobutton changes, there is a handy change function that you can use:
$('#<%= rblIsDiesel.ClientID %> input').change(function() {
alert("You changed fuel type");
});

Using JavaScript or JQuery to automatically check asp:checkbox when a button is pressed

I have a feature that allows the user to search the database for an item that matches the string they type in. For example, if they type in "Superman" it'll return whatever is in the database that is associated with Superman. Next to each item in the resulting list is a checkbox. If the user selects a checkbox, they can then press the "delete" button to remove that item from their list. I want to be able to select all of the checkboxes by pressing a "select all" button. Sometimes the lists are really long and if the user wants to delete all of the items, it would be time consuming to select and delete each one individually.
The checkbox is an asp:checkbox inside of an asp:TemplateField. The asp:TemplateField is inside an asp:GridView. Here is the checkbox code:
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="uxSelectAdd" runat="server" />
</ItemTemplate>
For the "select all" button, I'm using a regular input type:
<input type="submit" value="Select All" id="uxSelectAll" />
Here are the contents of the js file I'm using in my resources folder(I'm using the alert function for debugging. For some reason, the alert pops up when the page loads, rather than when I click on the button. Clicking the button doesn't do anything):
$(document).ready(function () {
$('#uxSelectAll').click(function (e) {
$(searchCheckBoxSelector).prop('checked', true);
alert("helloooo");
});
});
This is the js that is included in the front-end code at the top inside of a script tag:
<script type="text/javascript">
var searchCheckBoxSelector = '#<%=uxSearchedComics.ClientID%> input[id*="uxSelectAdd"]:checkbox';
</script>
I know that .live is no good since it's been removed in the version of javascript that we're now using, so I tried changing .live to .click instead. That didn't work. I also tried adding this js to the front-end instead of what was already there, just to experiment and see if this works:
<script type="text/javascript">
$(document).ready(function () {
$('#uxSelectAll').click(function () {
alert('hello world');
});
});
</script>
For some reason, that didn't work either. Am I missing something obvious? I wanted to at least get an alert to work before I tried adding in code to check all of the checkboxes for me but not even the alert works. I'd appreciate any help or nudges in the right direction.
Here are the .js files I'm using in the front-end code:
<script src="../../../../resources/js/ItemSlotEdit.js" type="text/javascript"></script>
<script src="../../../../resources/js/plugins/jquery-1.11.0.js" type="text/javascript"></script>
I want to share the solution I'm using. I've kept the input element exactly the same and this solution is in a separate js file that I've included into the .aspx front-end file.
$(document).ready(function () {
$('#body').on('click', 'input[type=submit]#uxSelectAll', function () {
$(this).toggleClass("checked");
var isChecked = $(this).hasClass("checked");
$('input[type=submit]#uxSelectAll').val(isChecked ? "Unselect All" : "Select All");
$(this).prev().find(":checkbox").prop("checked", isChecked);
return false;
});
});
The reason the button wasn't working before is because the button was in a div that doesn't exist when the page loads. The div appears after the user clicks the search button and the search results come in. The search results are populated into a div that appears dynamically. So, in order to access the button you need to include a parent container in the selector. Otherwise the event delegation doesn't go through. I used the #body container because I have only a single Select All button and a single checkbox so it doesn't conflict with anything. The toggleClass function alternates between giving and removing the "checked" class on each click, and you can modify the text of an input element by using the .val property.
I hope this helps someone.

ASP.NET Hidden field's OnValueChange

I have several different scenarios, all with different longitudes and latitudes (and other data, but that's beside the point) in JSON. I am parsing the JSON ok, and have been able to get the desired values. What I would like to do is transfer these values to the CodeBehind.
What I am doing so far is something like this:
This is the responsible script:
function getScenarioDetails(json) {
$("#Welcome").text("Welcome user " + json.user);
$("#longitude").val(json.current_loc.lon).change();
$("#latitude").val(json.current_loc.lat).change();
}
And these are the hidden fields:
<form runat="server">
<asp:HiddenField runat="server" id="longitude" OnValueChanged="valueChanged" />
<asp:HiddenField runat="server" id="latitude" OnValueChanged="valueChanged" />
</form>
I realise that the value is being changed. But something is going wrong with the OnValueChanged as it is not firing. What exactly am I doing wrong?
I will try to explain this, First the client id is generated based on the NamingContainer parents so if your hidden fields are nested in a container you should use the property ClientIDMode and set the value to Static to ensure the client id is the same in your script.
The ValueChange event is fired when a control cause a postback so if you put a button that has the onclick event it cause a postack and the ASP.Net lifecycle starts executing the ValueChange event for your hidden inputs, Some controls as DropDownList has a property AutoPostBack when it set to true it makes a postback as soon the javascript change event happens, so it not wait until a postback occurs. The HiddeField doesn't have a AutoPostBack property so if you really need to postack after you change the values you could make a postback so:
function getScenarioDetails(json) {
$("#Welcome").text("Welcome user " + json.user);
$("#longitude").val(json.current_loc.lon);
__doPostBack('longitude', '');
.....
}

why wont javascript "checkbox.disable" grey out associated label in ASP.NET?

I'm using some javascript to disable the checkboxes in a checkboxlist like so:
var objItem = document.getElementById("<%= resCBL.ClientID %>");
var checkBoxes = objItem.getElementsByTagName("input");
if (form1.secTB.value == 0) {
checkBoxes[0].disabled = true;
This code works fine, but when the page renders in IE, the text attribute for the checkbox is rendered as a label, and so only the checkbox seems to grey out, instead of the checkbox AND the text.
If I simply set
Enabled = false
in the .aspx codebehind, it greys out everything, but makes it impossible (with my current method) to re-enable the CB and un-grey the label.
Could anyone tell me how to work around this and help me understand why it's doing this?
Add the disabled attribute to the InputAttributes of the CheckBox instead:
CheckBox1.InputAttributes.Add("disabled", "disabled");
http://geekswithblogs.net/jonasb/archive/2006/07/27/86498.aspx
The problem is that an <asp:checkbox /> control gets rendered out like this:
<span><input type='checkbox'></span>
The real problem comes when you have a checkbox like this: <asp:CheckBox Enabled="false"/>.
This gets rendered out like this:
<span disabled='disabled'><input type='checkbox' disabled='disabled'></span>
If you look at the HTML output from a checkbox control you'll see there is an associated <label for="checkbox_client_id">Text</label> - this is why setting the checkbox as disabled doesn't grey-out the text.
When viewing the page from IE, ASP.NET wraps the <input> and associated <label> with <span disabled="disabled">. IE will disable all elements inside the span, which is why it disabled the checkbox and label.
However, since a span is not a form element, most other browsers follow the W3C rules and ignore the "disabled" attribute it. Disabling a span around the checkbox will only work in IE.
The easiest solution I can think of is to replicate this behavior manually. Wrap the checkbox with a span then, when enabling/disabling the checkbox use CSS to style the span and get the desired effect to work on all browsers.
var objItem = document.getElementById("<%= resCBL.ClientID %>");
var checkBoxes = objItem.getElementsByTagName("input");
if (form1.secTB.value == 0) {
checkBoxes[0].disabled = true;
checkBoxes[0].parentNode.class = "disabled";
}
P.S. Sorry if I sound snarky - IE always annoys me with it's endless "intricacies"

How can I toggle a panel's visibility using a CheckBox?

I have an <asp:CheckBox>, and I need to apply a JavaScript call upon it. The JavaScript function should set the visibilty of an <asp:Panel> to be true if the CheckBox is checked. The visibility of the panel should be false if the CheckBox is not checked.
I wasn't able to reach the JavaScript function using an <asp:CheckBox> with a normal input:type = checkbox it worked. But I need it to be an <asp:CheckBox>!
If i understand you correctly I would personally use jquery then you can do something like this
$("#yourCheckBoxId").change(function(){
if($(this).attr('checked')){
$(".yourDivClass").show();
}
});
Assuming that your CheckBox has a runat="server" attribute, you need to do something like:
$("<%= MyCheckBox.ClientID %>").change(function () {
$("<%= MyPanel.ClientID %>").toggle();
});
The code above assumes that your CheckBox and Panel will always have the same state. That is, a checked CheckBox equals a visible Panel. If you need to modify this code (change the conditions under which the Panel is visible, etc.), and want to reference the current checked state of your CheckBox, simply do this inside your change() function:
var checked = $(this).prop("checked");
Note: For future compatibility, it's important to use the prop() function instead of attr(). The difference here is subtle, but attr() will return the state of the CheckBox when it was first loaded on the page. prop() will return the current state of the CheckBox.
function toggle_panel(chkbox)
{
var panel=document.getElementById('<%=panle1.ClientID %>');
chkbox.checked ? panel.style.display='inline':panel.style.display='none';
}
Just make a call to the javascript function,inorder to access a asp.net control from javascript it should be made invisible using style attribute , because javascript will return undefined if Visible="false" is used.
<asp:CheckBox ID="chkboxPanel" runat="server" onclick="toggle_panel(this);" Text="Show" />
<br />
<br />
<asp:Panel ID="panle1" runat="server" Style="display: none">
Iam Text Inside the Panel
</asp:Panel>

Categories