简体   繁体   中英

Radio Button Control in jquery

I'm new to Web development and jQuery.
I'm trying to build an ASPX page with two RadioButton controls that must perform the following actions:

On page load, one of the two must be selected depending on a flag from an object on the ASPX page. Lets call it customer.Id. If the Id is true, select RadioButton one must be set else select RadioButton 2 must be set.

At any point after page load the user selects a RadioButton , the other must be deselected.

When RadioButton two is clicked, hide a Table named "employee table" and when RadioButton one is clicked, show that Table .

Can anyone please tell me how I can get this functionality in jQuery functions?

Not sure about .NET but in Classic ASP you would write a variable like this <%=customerID%>.

In jQuery, I think you can do something like this:

<input type="radio" id="radio1"> Yes
<input type="radio" id="radio2"> No

<table border="1" id="employeeTable">
    <tr><td>This is the table</td></tr>
</table>

... and then some jQuery:

$(document).ready(function() {
    var customerID = <%=customerID%> // asp variable

    if (customerID != "") {
        $('#radio1').prop('checked', 'checked');
    } else {
        $('#radio2').prop('checked', 'checked');
    }

    $('#radio1').click(function() {
        $('#employeeTable').fadeIn('fast');
    })

    $('#radio2').click(function() {
        $('#employeeTable').fadeOut('fast');
    })
})

You can have a look/play here: http://jsfiddle.net/qcLtX/7/

Try changing the customerID value to nothing, like var customerID = "" .

Good luck

UPDATE

Where I have used .prop : If you are using jQuery version 1.6 or greater, you should use .prop , otherwise, use .attr .

Radio buttons are grouped by their name attribute, like so ( source ).

<form>
<input type="radio" name="sex" value="male" /> Male<br />
<input type="radio" name="sex" value="female" /> Female
</form>

If the radio buttons are grouped, then selecting any one of them automatically delselects all the others in that group.

So the buttons cannot have a distinct name. If you want to distinguish between radio buttons (without referring the their value), you should add an id.

<input type="radio" name="sex" id="m" value="male" />

You can set the selected radio button on page load declaratively in markup, or using jquery.

Declarative version:

<input type="radio" checked="checked" name="sex" value="male" />

jQuery:

$(document).ready(function(){
    $("#m").attr("checked", "checked");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM