最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery Radio Button Change - Stack Overflow

programmeradmin3浏览0评论

So I've looked here and elsewhere on how to execute a function using jQuery when I click a radio button. I'm able to make the example code work isolated, like in CodePen, but it won't work when integrated into my project.

I'm not using straight radio buttons, but bootstrap-ified buttons. Relevant part of the form ends up looking like this:

<div class="btn-group" data-toggle="buttons" role="group" id="floors-div">
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="1" value="1" autocomplete="off">1</label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="2" value="2" autocomplete="off">2</label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="3" value="3" autocomplete="off">3</label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="4" value="4" autocomplete="off">4</label>
</div>

I'm able to get an action when the buttons are clicked by using:

$("input[name='floors']").parent().click(function() {
...snip...
var buttonVal = $("input[type='radio'][name='floors']:checked").val();

But the value is wrong. It returns the value of the previously selected button instead of the current one. If I just do something like:

$("input[name='floors']").change(function() {
...snip...

Nothing happens upon clicking the buttons.

Any suggestions?

Edit: I've narrowed down what's causing the problem with your help. Turns out the main difference between the CodePen that I did and production is the inclusion of Bootstrap's JS. Apparently they're overriding something that's messing with the .change method. Issue reproduced in CodePen here.

Edit 2: If it matters, all of my JS is inside $(document).ready(function(){ as well.

So I've looked here and elsewhere on how to execute a function using jQuery when I click a radio button. I'm able to make the example code work isolated, like in CodePen, but it won't work when integrated into my project.

I'm not using straight radio buttons, but bootstrap-ified buttons. Relevant part of the form ends up looking like this:

<div class="btn-group" data-toggle="buttons" role="group" id="floors-div">
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="1" value="1" autocomplete="off">1</label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="2" value="2" autocomplete="off">2</label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="3" value="3" autocomplete="off">3</label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="4" value="4" autocomplete="off">4</label>
</div>

I'm able to get an action when the buttons are clicked by using:

$("input[name='floors']").parent().click(function() {
...snip...
var buttonVal = $("input[type='radio'][name='floors']:checked").val();

But the value is wrong. It returns the value of the previously selected button instead of the current one. If I just do something like:

$("input[name='floors']").change(function() {
...snip...

Nothing happens upon clicking the buttons.

Any suggestions?

Edit: I've narrowed down what's causing the problem with your help. Turns out the main difference between the CodePen that I did and production is the inclusion of Bootstrap's JS. Apparently they're overriding something that's messing with the .change method. Issue reproduced in CodePen here.

Edit 2: If it matters, all of my JS is inside $(document).ready(function(){ as well.

Share Improve this question edited Aug 11, 2015 at 6:09 Ross asked Aug 11, 2015 at 5:27 RossRoss 1731 gold badge2 silver badges12 bronze badges 12
  • Your listener is attached to parent .click(), prob an issue of timing, and poor form in my mind - try attaching to radios themselves instead stackoverflow.com/questions/10167395/… – Daniel Brose Commented Aug 11, 2015 at 5:29
  • jQuery change event works fine for me: jsfiddle.net/tyu294vt/2 – Yeldar Kurmangaliyev Commented Aug 11, 2015 at 5:30
  • have you loaded jquery? change event is working perfectly. – Domain Commented Aug 11, 2015 at 5:32
  • @DanielBrose Just tried that - doesn't work. Nothing happens when I click the buttons. – Ross Commented Aug 11, 2015 at 5:34
  • @WisdmLabs Yep - I have loaded it. I have other jQuery working on the page just fine. – Ross Commented Aug 11, 2015 at 5:35
 |  Show 7 more comments

7 Answers 7

Reset to default 5

Try like this using event delegation.

 $("#floors-div").on("change", "input[name='floors']", function () {
        //code snippets
 });

Or

$(document).on("change", "input[name='floors']", function () {
        //code snippets
 });

Use .change method instead of .click

$("input[name='floors']").change(function() {
    var buttonVal = $("input[type='radio'][name='floors']:checked").val();
    alert(buttonVal);
})

OR

$("input[name='floors']").change(function() {
    var buttonVal = $(this).val();
    alert(buttonVal);
})

Fiddle: http://jsfiddle.net/hxe9ue97/

After viewing your code on codepen ,I sorted out your problem & found that your code is correct, actually the problem was whenever you click on the button,you don't actually clicks on the radio button rather you click on the 'label'. Whenever I remove the label tag your code perfectly works. here is the image.

.

But I solved your problem by this code :) You can check demo. Also edited your codepen -> http://codepen.io/anon/pen/mJozaQ

$(document).ready(function(){
 
  $("label.floorNum").on("click",function()
  { 

          alert($(this).find('input').val());
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<div class="row">
    <div class="form-inline">
        <div class="form-group col-sm-3">
            <label for="housingArea">Area</label>
            <select id="housingArea" class="form-control">
                <option value="" style="display:none" selected></option>
                <option value="north">North</option>
                <option value="south">South</option>
                <option value="east">East</option>
                <option value="west">West</option>
            </select>
        </div>
        <div class="form-group col-sm-4">
            <label for="building">Building</label>
            <select id="building" class="form-control">
                <option value="" style="display:none" selected></option>
                <option value="AAA">AAA</option>
                <option value="BBB">BBB</option>
            </select>
        </div>
        <div class="form-group col-sm-5">
            <!--Fill with info from DB -->
            <label for="floorNum">Floor</label>
            <div class="btn-group" data-toggle="buttons" role="group">
                <label class="btn btn-default floorNum">
                    <input type="radio" name="floorNum" value="1" autocomplete="off">1
                </label>
                <label class="btn btn-default floorNum">
                    <input type="radio" name="floorNum" value="2" autocomplete="off">2
                </label>
                <label class="btn btn-default floorNum">
                    <input type="radio" name="floorNum" value="3" autocomplete="off">3
                </label>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="form">
        <div class="form-group">
            <label for="roomNum">Room Number</label>
            <br>
            <div class="btn-group" data-toggle="buttons" role="group">
                <label class="btn btn-default">
                    <input type="radio" name="roomNum" id="101" autocomplete="off">101
                </label>
                <label class="btn btn-danger">
                    <input type="radio" name="roomNum" id="102" autocomplete="off">102
                </label>
                <label class="btn btn-default">
                    <input type="radio" name="roomNum" id="103" autocomplete="off">103
                </label>
                <label class="btn btn-success">
                    <input type="radio" name="roomNum" id="104" autocomplete="off">104
                </label>
                <label class="btn btn-warning">
                    <input type="radio" name="roomNum" id="105" autocomplete="off">105
                </label>
                <label class="btn btn-info">
                    <input type="radio" name="roomNum" id="106" autocomplete="off">106
                </label>
                <label class="btn btn-primary">
                    <input type="radio" name="roomNum" id="107" autocomplete="off">107
                </label>
                <label class="btn btn-default">
                    <input type="radio" name="roomNum" id="108" autocomplete="off">108
                </label>
            </div>
        </div>
    </div>
</div>

jQuery change() event works fine for me with your code:

$("input[name='floors']").change(function() {
    var val = $("input[type='radio'][name='floors']:checked").val();
    alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

<div class="btn-group" data-toggle="buttons" role="group" id="floors-div">
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="1" value="1" autocomplete="off">1
    </label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="2" value="2" autocomplete="off">2
    </label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="3" value="3" autocomplete="off">3 
    </label>
    <label class="btn btn-default" name="floors-label">
        <input type="radio" name="floors" id="4" value="4" autocomplete="off">4
    </label>
</div>

Probably, the problem is somewhere else but not at this part of code.

By the way, it is definitely better to use this.value instead of such a big selector.
It is easier, it is DOM property (vanilla JS), it is faster and readable:

$("input[name='floors']").change(function() {
    var val = this.value;
    alert(val);
});

Try binding your on click event after the document has loaded with this call:

$("input[name='floors']").on("click",function(e)
{
        console.log($(this).val());
});

Just tested this and clicking the various button returns the correct values.

Hi you can just try this hope this will work for you

$("#floors-div input:radio[name='floors']").on('change',function(){
    console.log($(this));
});

for getting value you need to just use $(this).val(); in my code.

Use change() event. this point to current element

$("input[name='floors']").change(function() {
    var val = $(this).val();// this
    alert(val);
});

DEMO

发布评论

评论列表(0)

  1. 暂无评论