I figured I’d share how I’ve dealt with some form elements in jQuery. Sometimes you have to look at the docs a few times before you get what you can do, so I think these examples might help someone out there.
Here is how you can handle a change in a dropdown (SELECT tag with an ID that is “layer_image”):
$("#layer_image").change(function()
{
switch ($(this).val())
{
case '0':
$("#radar_image").hide();
break;
default:
$("#radar_image").show();
}
});
Granted I could of used toggle() to do the same thing I figured it was better to show an example using the switch statement.
Here is an example of handling a checkbox (INPUT tag with an name attribute of “option_linkwindow”):
$("input[@name='option_linkwindow']").click(
function()
{
if ($("input[@name='option_linkwindow']").is(":checked"))
$(".feed/ul>li/a").attr("target","_blank");
else
$(".feed/ul>li/a").attr("target","_self");
$(this).blur();
}
);
Here is another example of handling a checkbox (INPUT tag with a name attribute of “option_summary”):
$("#option_summary").change(
function()
{
$("//li/p").toggle();
$("li[p:hidden]").removeClass("expanded");
$("li[p:visible]").addClass("expanded");
$(this).blur();
}
);
And now an example of handling the following radio buttons:
<input type="radio" name="option_layout" value="0" checked="checked" />
<input type="radio" name="option_layout" value="1" />
And now the jQuery code for handling them:
$("input[@name='option_layout']").change(
function()
{
if ($("input[@name='option_layout']:checked").val())
$(".group").toggleClass("group_vert");
else
$(".group").toggleClass("group_vert");
$(this).blur();
}
);
Thanks for the examples, but I did just have some problems with using the “change” event with radio buttons in IE. I changed it to “click” and it seems to work better.
Aug 7, 2007 at 12:17 pmHow do you SET a radio button using jQuery?
Aug 20, 2007 at 1:58 pmSample Form
<form id="myform" name="myform" method="post" action="#">
<label><input type="radio" name="myradios" value="1" />alpha</label>
<label><input type="radio" name="myradios" value="2" />beta</label>
<label><input type="radio" name="myradios" value="3" />gamma</label>
</form>
jQuery to maniuplate them
Aug 21, 2007 at 3:05 pm$("input[@name='myradios']").val("nothing");//changes all to nothing
$("input[@name='myradios']:nth(2)").val("trident");//change 3rd one
$("input[@name='myradios']:nth(1)").attr("checked","checked");//make the 2nd one checked
@chief:
Jan 8, 2008 at 8:56 amthanks for your hint with the “click-event”. I had the same problems with “change” in IE. It’s a shame that this bug isn’t fixed in IE7 yet.
How do you use JQuery to set a selected index of a select box?
Feb 4, 2008 at 2:48 pm@Cory
Here is the HTML
<form id="myform" name="myform" method="post" action="">
<select name="list" size="3">
<option value="1" selected="selected">Alpha</option>
<option value="2">Beta</option>
<option value="3">Delta</option>
</select>
</form>
Here is the jQuery
Feb 4, 2008 at 4:25 pm$(document).ready(function() {
$("#myform select[@name='list'] option[@selected='selected']").removeAttr("selected");//remove any selected items
$("#myform select[@name='list'] option[@value='2']").attr("selected","selected");//select beta
$("#myform select[@name='list'] option").removeAttr("selected");//remove any selected items (alternative method)
$("#myform select[@name='list'] option:eq(3)").attr("selected","selected");//select delta (it finds the third child)
});
thanks so much for the examples, they are really helpful as I’m totally new to jquery.
One thing I havent been able to figure out is how to enable a set of radio buttons if a checkbox is checked.
I have a big array (in php) that I use to generate a whole list of checkboxes and associated radio buttons (disabled by default). When i check the checkbox I’d like the enable the radio buttons.
I’m sure its easy with jquery but I havent been able to figure it out now.
Chisler
Mar 12, 2008 at 1:27 pmYou could make jQuery create the radio buttons when the checkmark is checked and remove it when it is not.
Here is the HTML
<form id="myform" name="myform" method="post" action="">
<label for="name">Name</label>
<input name="name" id="name" type="text" />
<fieldset id="newsletters">
<label><input type="checkbox" name="want_nl" id="want_nl" value="newsletters" />Want newsletters?</label>
</fieldset>
</form>
Here is the jQuery code
Mar 12, 2008 at 8:41 pm$(document).ready(function(){
$("input[@name=want_nl]").click(function(){
if ($(this).is(":checked"))
{
$('#newsletters').append('<fieldset id="newsletter_types"></fieldset>');//create fieldset first
$('#newsletter_types').append('<label><input type="radio" name="nl_type" value="1" />Cars</label>');
$('#newsletter_types').append('<label><input type="radio" name="nl_type" value="2" />Houses</label>');
$('#newsletter_types').append('<label><input type="radio" name="nl_type" value="3" />Jobs</label>');
}
else
$("#newsletter_types").remove();
});
});
Thank you, this has helped me a lot, x
Apr 23, 2008 at 7:09 amI got a comment from Jagadeesh that submitted some code through my comment form asking why his dropdown select wasn’t firing on the change event and he had a alert() debug in it. What I realized the switch wasn’t testing for string values.
Here is code for a html page showing a dropdown select that will change divs
Apr 23, 2008 at 9:41 pm<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="jquery-1.2.3.pack.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".propstatus_div").hide();//hide all
$("#propStatusCd").change(function()
{
alert($(this).val());//debug
$(".propstatus_div").hide();//hide all
switch ($(this).val())
{
case '0':
$("#inactive").show();
break;
case '1':
$("#active").show();
break;
default:
$("#other").show();
}
});
});
</script>
</head>
<body>
<form action="" method="get">
<label>Property Status
<select name="propStatusCd" id="propStatusCd">
<option>Select Something</option>
<option value="0">Inactive</option>
<option value="1">Active</option>
<option value="2">Suspended</option>
<option value="3">Closed</option>
<option value="4">Pre-Deactive</option>
<option value="5">Deactive</option>
<option value="6">Non-Stay</option>
<option value="7">Test</option>
<option value="8">Non-Starwood</option>
</select>
</label>
</form>
<div id="inactive" class="propstatus_div" style="background:#f00;">This div is #inactive</div>
<div id="active" class="propstatus_div" style="background:#0f0;">This div is #active</div>
<div id="other" class="propstatus_div" style="background:#00f;">This div is #other</div>
</body>
</html>
Thank you so much. I have a problem with radio button and it resolved by your entry ^^
Thanks again & best wish for you
Apr 28, 2008 at 8:00 amGreat reference, thanks!
May 7, 2008 at 10:44 pmThanks a lot for the method of getting selected radio button value:
$(”input[@name='option_layout']:checked”).val()
May 20, 2008 at 3:24 pmThanks your your entry, it very very good, it resolved my prolem.thanks you.
May 21, 2008 at 4:01 amThanks for this article however does anyone know how to do this through .net? The group name for example is unaccessible as it dynamically changes to an elongated variable at run-time.
I.E. My previously named ‘LiveOptions’ radio button group name will change to:
ctl00$ContentPlaceHolder1$TabContainer1$tabLiveOptions$liveDateManagementView$LiveOptions
~ Lacuna
Jun 11, 2008 at 6:40 am@Lacuna:
I’ve found the best way to work with RadioButtons and jQuery in .NET (especially if the radiobuttons are embedded in datagrids, repeaters, etc that mangle the client ID’s as per your example) is by using unique class names instead of ID’s. The css class names do not have to occur in your css stylesheet (in fact, they shouldn’t).
If you’re already using a CSS class for your radiobutton control, then add this new unique class to the existing one. E.g. two rbn’s in the same group:
Just be aware that as another poster mentioned, .NET renders the asp:RadioButton control as a SPAN with two controls inside it: a radio input and a label. The CssClass property will be applied to the containing SPAN and NOT to the embedded Radio input control.
So you can have a jQuery click event handler like this:
$(”.rbnStyle”).click(function() {
//”this” will point to the SPAN
var rbnId = $(’#'+this.firstChild.id).attr(’id’);
alert(”radiobutton id=”+rbnId);
});
Note: .change() won’t work because the “.rbnStyle” selector will actually return the SPAN elements (cos they are given the style) and they don’t support a change event.
Jun 14, 2008 at 6:13 pmFor .NET you can grab it this way, which will get an ID that END WITH your original ID, meaning .NET can prepend whatever it wants on the front and you can get your control by ID.
$(”span[id*='spnBaleTxt']“)
Jul 16, 2008 at 11:57 amThank you so much. I have a problem with radio button and it resolved by your entry ^^
Thanks again & best wish for you
Aug 3, 2008 at 4:12 amthanks for the tips, some really usefull techniques here
Sep 18, 2008 at 9:33 amHi All,
I’m trying to manually change the value of a select menu to a certain
option by referencing it’s value.
I’ve got the three instances I’ve tried (below) which aren’t changing
the select menu option correctly, in which am having trouble getting
the correct syntax as to how to SET the value on an “onClick” event.
+ one
+
+
Can someone help me find the correct syntax?
Thanks!
Oct 21, 2008 at 7:56 amcheck radio by name:
Nov 20, 2008 at 5:12 amif($(”input[@name='your_radio_group_name']“).attr(”checked”)==false) alert(”Please check radio!”)
We need more tut like this.
Dec 7, 2008 at 2:28 pmthanks.
Hey,
Thanks for sharing this.
I actually reached this page by searching for something similar, only I am looking to capture a change on an input text field.
The .change() function is only invoked when I alt tab away from the window and then back.
Can anyone spare a hint?
Jan 16, 2009 at 7:47 am(to the blogger – may I suggest adding a “Subscribe to comments” WP plugin?)
@Danny
Jan 17, 2009 at 9:06 amI would use keypress() and click() and test the input field to see if it did change or not. The reason for the click() is incase someone does a copy and paste with their mouse or if they drag text into the text field.
Thanks.
I used keydown() – thought that the change() event should work, but I guess not.
Jan 17, 2009 at 1:44 pmThanks for the click() tip – didnt think of that.
In jQuery 1.3 [@attr] style selectors were removed (they were previously deprecated in jQuery 1.2). Simply remove the ‘@’ symbol from your selectors in order to make them work again.
Feb 13, 2009 at 5:31 amHelp!
I’m new to jquery and need help. I have a best image voting page that has a couple of different categories that submits a form. I want the user to be able to click on the picture instead of the the radio button (might hide the radio button), and just highlight the selected picture, and dim the unselected ones. Please advise. thanks!
Feb 18, 2009 at 3:17 pmBrent, take a look at Digg’s submit form (you’ll have to be logged in to see it). You can then test to see when one of the selections is checked or changed and then change the classes of those not checked. Then have the non-selected icons’ alpha set to a lower value or replace with a grayscale image or overlay a white png on top of them to get a dimmed effect.
Feb 18, 2009 at 8:48 pmhi blogger, that is kind of what i need. I was able to figure out the script.
Feb 20, 2009 at 11:44 am$('input').hide();
//$('li').bind('click change', function() {
$('li').click( function(){
$('li').removeClass('selected');
$(this).addClass('selected');
$(this).children('input:radio').click();
});
That is real nice. Yet another reason to love jQuery. I mean dang that is great. Thanks for droppin this knowledge.
Mar 11, 2009 at 4:00 pmFor .net, you can use , with ‘name’ being the ID you specified in . Yes, it makes your code uglier.
Mar 24, 2009 at 11:02 amwhat about changing type of the input on the fly, have tried few ideas – but firebug trowing me error:type property can’t be changed.
simple login form where user can switch input type from ‘password’ to text and back using checbox
thx
Apr 1, 2009 at 4:56 pmHi, i’m trying to use your code to read the selected value of two sets of radio buttons… With just one set everything works perfectly. But if there are two sets then one of them “takes charge” and all the radio buttons return the same value…
You can see a test case here:
http://www.kikentai.org/jquery/test.html
Do you have any idea on why it happens?
Thanks!
Apr 2, 2009 at 9:30 amAnd thanks for sharing this!
Marcello
this is extremely helpful. thank you! thinking of this from a different angle is there a way to hide/show input types. for instance, if i have a select with options: text, radio, checkbox and the user selects radio the radio option will appear. similarly, if i they select text, they’ll be able to enter text in the field?
Apr 14, 2009 at 12:01 am@Cory & blogger
you can set an option in a select by assigning to the .val()
One
Two
Three
Jquery
$(’#myselect’).val(”2″);
Apr 21, 2009 at 7:52 am@Marcello
Try to change @name= to name=
May 10, 2009 at 1:40 amWhen using a selector like $(”input[@name='option_linkwindow']“), I get a message in Firefox in the Error console that says
Error: [Exception... "'Syntax error, unrecognized expression: [@name='option_linkwindow']‘ when calling method: [nsIDOMEventListener::handleEvent]” nsresult: “0×8057001e (NS_ERROR_XPC_JS_THREW_STRING)” location: “” data: no]
I have the latest version of JQuery, any ideas why I am getting this message?
May 22, 2009 at 6:04 pmI believe starting with jQuery 1.3 they got rid of requiring the @ in the attributes. So now you just do it like this
May 23, 2009 at 8:14 am$(”input[name='option_linkwindow']“)
thanks man!!!
Jun 1, 2009 at 1:42 amyou saved my day once again
this acticle is good
thanks alot
Jun 2, 2009 at 1:10 amAfter numerous tutorials, and studying two books on jquery, your article put it together for me. Thanks!
Jun 27, 2009 at 10:53 pm