Easiest/Best Hide/Show Client Side Hide/Show for ASP.NET - asp.net

I have a DropDownList and a TextBox on a Page. When the user chooses the "other" option in the DropDownList I want to display a TextBox just to the right of it. I do not want to use the traditional PostBack technique. I want this interaction to be client side.
I am aware that I can get a get a reference to the DOM element and set its style to "display:none" or "display:". What I am looking for is something that is built into the ASP.NET framework for handling something like this. I mean, in jQuery this is as simple as $('controlID').hide. Is there a Control Extender that can do this? Is jQuery part of the ASP.NET framework yet?

jQuery will be/is distributed with VisualStudio/ASP.NET MVC, though I wouldn't call it part of the framework. I think that you can feel free to use it and trust that it will be supported.
Note that Microsoft has said that they will be using the main line of development for jQuery so the code itself won't be any different than you can download from jQuery.com, except perhaps for built-in Intellisense.
EDIT: To set up your functionality download the code from jquery.com. Put it in your scripts folder, or wherever you store javascript stuff. Add a script reference for it to your page. Use jquery to add an onchange handler to your dropdown list and when the value of the dropdown list is other show the textbox, otherwise hide it. The example below assumes that other isn't the default selection. If you are using runat="server" controls with MasterPages or inside UserControls, you'll need to adjust the names in the javascript functions to account for the name mangling that ASP.NET does. Probably simpler to give them unique CSS classes and reference them using the ".class" notation rather than "#id" notation.
<script type="text/javascript" src="...pathtoscript../jquery.1.2.6.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$("#DropDownListID").bind('change', function() {
if (this.options[this.selectedIndex].value == 'other')
{
$("#TextBoxID").show();
}
else
{
$("#TextBoxID").hide();
}
});
});
</script>
...
<select id="DropDownList">
<option value='first'>First</option>
...
<option value='other'>Other</option>
</select>
<input type='text' id='TextBox' style='display: none;' />

You could also use the asp.net client side framework(via the scriptmanager) to get a reference to the element. But then you still have to use the normal DOM manipulation.
$get('<%= myDropDown.ClientID %>').style.display = 'none';
Just make sure you have the script manager referenced.
For something so simple, I wouldn't think it is worth referencing jquery, but maybe you've got bigger plans ;-)

Related

JQuery validation not working for checkbox group

I'm having trouble getting JQuery validation to work with a set of checkboxes. I'm generating the checkboxes using an ASP.NET checkboxlist, and I've used JQuery to set the 'name' attribute to the same thing for each checkbox in the list. Here's the code that gets written to the browser. I'm setting the 'validate' attribute on the 1st checkbox to set the rule that at least one checkbox must be selected. The JQuery validation works for all other elements on the form, but not for the checkbox list. I'm also using a JQuery form wizard on the page which triggers validation for each 'page' of the form, so I don't have control over how the validation is called.
<input id="ContentPlaceHolder1_MainContent_AreaOfInterest_0" class="ui-wizard-content ui-helper-reset ui-state-default" type="checkbox" value="Famine" name="hello[]" validate="required:true, minlength:1">
<label for="ContentPlaceHolder1_MainContent_AreaOfInterest_0">Famine</label>
<br>
<input id="ContentPlaceHolder1_MainContent_AreaOfInterest_1" class="ui-wizard-content ui-helper-reset ui-state-default" type="checkbox" value="Events Volunteer" name="hello[]">
<label for="ContentPlaceHolder1_MainContent_AreaOfInterest_1">Events Volunteer</label>
Any ideas on what's going wrong? There are lots of examples of JQuery scripts that will do the validation, however I'm trying to avoid this as I'm generating the checkboxlist server side by a custom control so that it can be re-used across different pages that may or may not have JQuery enabled. I'm trying to enable the JQuery validation whilst being as unobtrusive as possible, so that pages will still work even if JQuery is disabled.
Here are the relevant JQuery inclusions and JQuery initialisation script for the form wizard. I'm not using any initialisation code for JQuery validation:
<script type="text/javascript" src="../js/formwizard/js/bbq.js"></script>
<script type="text/javascript" src="../js/formwizard/js/jquery.form.js"></script>
<script type="text/javascript" src="../js/formwizard/js/jquery.form.wizard.js"></script>
<script type="text/javascript" src="../js/formwizard/js/jquery.validate.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#form1").formwizard({
validationEnabled: true,
focusFirstInput: true
});
});
</script>
Using JQuery to set the 'name' of each checkbox to a consistent value 'breaks' the checkbox list in .NET (I thought this would happen). Basically it's too complex to use the JQuery forms wizard and JQuery validate with a customised .NET checkboxlist. They aren't really compatible. .NET needs to have different names for each of the checkboxlist inputs, which doesn't play well with JQuery validate (certainly not when also using the form wizard). I'm going to try switching off JQuery validation in the forms wizard (it has this option) to see if the form wizard will work OK with the validation (including client-side validation), of the .NET validators. I'll post back my results! Think I tried doing this originally and the form wizard wasn't working correctly, which is why I started using JQuery validation with the form wizard, so my current solution is just to just remove the multi-page form (the form's not too too long without this), to simplify things, and just rely on .NET validation (client and server side). Someone made the point that a multi-page form can leave the user wondering exactly how many field are left to fill, while at least a single page form allows them to see the fullness of what they need to complete!
This is the form wizard I am/was using:
http://thecodemine.org/

Add an Editor control dynamically inside of a repeater using AJAX

I'm looking for a way to add an Editor control (from the ASP.NET AJAX Control Toolkit) to each element of a repeater. It's working fine if I just include it in the ItemTemplate of the repeater, but my problem is that the markup it produces is massive, which slows down the page considerably (even with compression on).
I haven't had any luck adding the control inside the repeater item using an Update Panel - I think this is probably the preferred method, but dynamically adding a control inside an Update Panel inside of a Repeater Item isn't something I've had any success doing, and there don't seem to be any good examples of this that I can find.
The other alternative I considered was using PageMethods to render the control and send the HTML back to the page to let the javascript put it in the appropriate place, then deal with it, but it won't let me render the control - I get an InvalidOperationException of "Page cannot be null. Please ensure that this operation is being performed in the context of an ASP.NET request.". My guess is that all the javascript that's generated makes it so that I can't just render an Editor control on the fly.
Can you point me in the right direction for accomplishing this?
Thanks
EDIT: Another alternative, if it is possible, would be to put a normal Editor control in the markup of the page, then move it around inside of the repeater as needed, using javascript. I can do this with normal controls, but when I do it with an editor, it is not behaving nicely - the textbox appears, but won't let me click inside it. If you have any ideas on this one, I'd appreciate that as well. Here's the code for this:
<span id="spanHiddenEditor" style="display: block;">
<cc1:Editor ID="ed1" runat="server" Height="200" Width="400" />
</span>
<script type="text/javascript">
function createTextBox(idx) {
var span = $get("span1_" + idx); // this gets me the target location
var hiddenEditorSpan = $get("spanHiddenEditor")
var editorHtml = hiddenEditorSpan.innerHTML;
hiddenEditorSpan.innerHTML = "";
span.innerHTML = editorHtml;
}
</script>
identify the location within the repeater with a class then use jquery to inser the html on page ready
$(function() {
$(".myclass").Append("<htmlz>");
});
Then if you need to identify each text box you can do it using the parent container ID eg.
$("#myID div.class input").value
I'm a total jquery newb so none its likely none of it will work, but i believe the idea is a good one!

jQuery and ASP.NET Control issue

If I have a custom ASP.NET control that renders as an html control with an ID, I'm trying to add an attribute to the input control with jQuery.
However, I'm running into some issues:
First, my jQuery is not able to select it.
I have so far:
$(document).ready(function() {
$(client id of the input control).attr('onclick', function () { alert('hey!'); });
});
It seems as if the jQuery is trying to find the input control but cannot.
Any ideas?
UPDATE:
Normally, the solutions presented would work but since this is a SharePoint Publishing .aspx page, Code blocks are not allowed... Trying other work arounds.
Just wire up the click event in jQuery.
$(document).ready(function() {
$(id of the input control)click(function() {
alert('hey!');
});
});
Also, make sure you aren't just putting the ID you typed in to the control in the jQuery. ASP.Net renders the control with a much different ID than you had given the control. On one of the sites I run, I have the following button:
<asp:Button ID="btnSignup" runat="server" Text="Sign Up" />
The ID in the rendered HTML is not btnSignup, it actually renders as ctl00_cpLeft_btnSignup. To select that control with jQuery, you can do this:
$("input[id$='btnSignup'").click(function() { ... });
Edit:
$("input[id$='btnSignup'}").click(function() { ... });
You can also select using:
$("#<%= btnSignup.ClientID %>").click(function() { ... });
Edit:
I looked into using the <%= ... %> method and you would have to have your javascript IN the ASPX/ASCX file itself for it to work. Because of this, I'd stick with the regex method.
What do you use as the ID of the input control?
You have to use the ClientID of the control, not it's ID.
You need to use its ClientID. If your ASP.NET markup looks like this:
<uc:MyControl runat="server" ID="myControl1" />
Your jQuery selector should look like this:
$(document).ready(function() {
$("<%=myControl1.ClientID%>").attr('onclick', function () { alert('hey!'); });
});
Selecting a ASP.NET generated ID with jQuery
Is your ASP.NET control in a master page or a user control? ASP.NET will prepend a bunch of identifiers to your ID to make sure it is unique.
What is the ID of the control coming out as in HTML?
If you're setting the ID of the rendered HTML control to the ID given to the ASP.NET control, you need to be aware of how ASP.NET handles control ID namespaces. Essentially, each control nested within a control needs to always guarantee a unique identifier. ASP.NET maintains this by taking the ID assigned to a control and prepending it with the ID of every control that contains the control. Thus, a control on a page will contain a string of ids going up to the form on the page itself.
You do not want to have to re-construct this client-side. Instead, Control defines ClientID, which will return the ID of the control as rendered on the client. Embed this into your jQuery, or into a javascript variable that your jQuery can see if you are putting the jQuery in a separate script file) and you should be fine.
just to inform you, the document.ready part is not needed, using asp.net control the id is changed to something different then what is expect, a ct100.... is thrown on the beginning of it, so this way will look for the actual id name even though asp.net throws the mangled code on the beginning,because it looks for all elements (*) that have an ID that ends with the specified text.
$(function() {
$("*[id$='idofcontrol']".click(function() { alert('hey!'); });
});
or go to the view source and copy the id name and paste it in your code or just use the css class selector as so:
$(function() {
$('.myclassname').click(function() { alert('hey!'); });
});
Since you mentioned Sharepoint you might be interested in this series on EndUserSharepoint that focuses on integrating jQuery with Sharepoint. The author discusses getting jQuery to manipulate the webparts.

JQuery output a dynamic control in a div

How do I handle the click of a checkbox to show another control preferrably a user conrtrol (ASP.NET ) dynamically.
I don't know anything about the system you're using but the low down dirty way I'd do this is...
Stick the user control on a blank page of it's own.
When the checkbox is clicked, have JQuery go get the HTML content of the page the user control is on and stick it in the div.
This will result in not-so-neat html in the calling page though.
And is this an asp:CheckBox or an html input?
If you want to create a new object, you can do this:
var checkbox = $("<input type='checkbox' ... />");
$('div#someID').append(checkbox);
Though it sounds like you perhaps want to get the data to append from an AJAX call. I can't quite tell from the question.
Assuming you hide the control with CSS by default you could shorten TStamper's code to something like:
$(function() {
$('#checkbox').click(function() {
$('#control').toggle();
});
});
<mycontrol:UC id="control" runat="server" />
I'm partial to using jquery's taconite plugin. It enables you to return multiple controls from a single ajax call.
For a simple show/hide control scenario rendering a hidden control on a page is good enough. If your control is big or changes due to user actions then your best bet is rendering control on the server and using js to update DOM.
If you're using jquery for your DOM updates and wish to find control by id use:
$("[id$=controlId]")
This will locate your control even with asp.net prefixes to the id.
I'm working on a simple c# wrapper for the taconite plugin which should enable you to use the plugin more easily (sample web site coming soon).
Are you looking for something like this:
$(function(){
$('#Control').hide(); //initially hide the control
$('#checkbox').click(function(){ // bind the checkbox click event
if ($('#checkbox').attr('checked')) {
$('#Control').show();
}
});
});
<mycontrol:UC id="Control" runat="server" />

Using Javascript With ASP.Net controls

Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls? Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control. Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.
Are these the only two choices? Is there a right way to do this that I'm missing?
Thanks!
Eric Sipple
**just a pre-note on the answer: HTML validation in VS is often BS. It complains about stuff that works IRL, even if that stuff is bad practice. But sometimes you gotta bend the rules to get stuff done.
Every ASP.NET page (2.0 and greater) comes with a ClientScriptManager. You use this to register javascript from server side code. You can pass in javascript that registers events on controls after the page has loaded, when the HTML controls on the page are all present in the DOM.
It presents a single, unified place on pages to dynamically add javascript, which isn't a bad thing. It is, however, awfully ugly.
In this time of the death of the ASP.NET server control model, you might want to set events the way they will be in the future of ASP.NET MVC. Grab a copy of jQuery and add it to your website. You can then easily register your events thusly:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("controlId").bind("click", function(e) { /* do your best here! */ });
});
</script>
</head>
<!-- etc -->
</html>
You can add the events through Javascript to the HTML elements that you want. This is the cleanest way, since it doesn't mix the server&client technologies. Furthermore, this way many handlers can be registered to the same event (in contrast to the onclick attribute).
Basically, the code would be
document.getElementById('myLovelyButtonId').attachEvent('onclick',doSomething)
for Internet Explorer and
document.getElementById('myLovelyButtonId').addEventListener('click',doSomething,false)
for other browsers. (doSomething is an event handler - JavaScript function). These calls should be made in the window load event handler
Consider reading the advanced event registration article on Quirksmode for further info.
Also, consider using a library like jQuery. This way, the statement will become
$('#myLovelyButtonId').click(
function doSomething () {
alert('my lovely code here');
});
Setting the value for WebControl.Attributes["onclick"] is okay. If ASP.NET needs a client-side click handler, it will concatenate the values, delimited by semi-colon.
Fix grammatical or spelling errors.
Clarify meaning without changing it.
Correct minor mistakes.
Add related resources or links.
Always respect the original author.

Resources