jQuery event on change()

2019-03-01 06:40发布

问题:

I have a simple form:

    <div class="class_a">
      <fieldset>
        <label><input type="radio" id="radio10" name="color" value="1" />Red</label><br />
        <label><input type="radio" name="color" value="2" />Yellow</label><br />    
        <label><input type="radio" name="color" value="3" />Blue</label><br />
        <label><input type="radio" name="color" value="4" />Purple</label><br />
      </fieldset>
     </div>
 <div class="block-cms">
       <fieldset>
        <label><input type="radio" name="time" value="6" />12</label><br />
        <label><input type="radio" name="time" value="7" />11</label><br />    
        <label><input type="radio" name="time" value="8" />10</label><br />
        <label><input type="radio" name="time" value="9" />9</label><br />
      </fieldset>
 </div>

What im trying to do here is by using jQuery change() hide off second fieldset.

$("input#radio10").change(function () {
        var checked = true;
        checked = checked && $(this).is(':checked');
        if ($('input#radio10:checked') ) {
            $('.block-cms').show()
            } 
        else {
            $('.block-cms').hide();
        }
    }); 

Not sure what con be wrong here. Can anyone suggest me what should be done different please?

回答1:

Your id shouldn't have the #, that's for the selector, it should just be id="radio10".

Change that, and this is what you should be after:

$(".class_a :radio").change(function () {
  $(".block-cms").toggle($("#radio10:checked").length > 0);
}); 

You can test it out here.



回答2:

First of all the id on the element should be radio10 and not #radio10.

Then use this code

$("input[name='color']").change(function () {
    if ($('input#radio10').is(':checked') ) {
            $('.block-cms').show()
            }
        else {
            $('.block-cms').hide();
        }
    }); 


回答3:

Here's another solution (IMO having an id on an <input type="radio"> seems a bit wrong to me):

$("input[name='color']").change(function () {
        if ($(this).val() == 1) {
            $('.block-cms').show()
            } 
        else {
            $('.block-cms').hide();
        }
    });