SalmanShariati
SalmanShariati

Reputation: 3893

Radiobutton in asp with jQuery

this works:

<script>
    $("input:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

the result is : ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup

but this not work:

<script>
    $("input[name=ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup]:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

could anyone help me?

Upvotes: 0

Views: 93

Answers (2)

markegli
markegli

Reputation: 398

The jQuery API says the attribute equals selector takes an unquoted single word or a quoted string. Unfortunately it considers the $ character as a non-word character so you have to put your name attribute value in quotes:

<script>
    $("input[name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup']:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

However, I recommend actually using the attribute ends with selector since the first part of your name is generated by .NET and could potentially change if you adjust your layout:

<script>
    $("input[name$='$RS_rbtItemGroup']:radio").change(function () {
        alert($(this).attr("name"));
    });
</script>

Upvotes: 1

zwiebelspaetzle
zwiebelspaetzle

Reputation: 260

Because you have "$" in the name, you need to add single quotes to you name query. Try this:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $(document).ready(function() {
        $("input[name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup']:radio").change(function () {
            alert($(this).attr("name"));
        });
    });
</script>
</head>
<body>
    <input type='radio' name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup' value='yes'>Yes</input>
    <input type='radio' name='ctl00$ctl00$cphBody$cphBody$RS_rbtItemGroup' value='no'>No</input>
</body>
</html>

Upvotes: 1

Related Questions