在JQuery中未检测到单选按钮更改

时间:2016-06-11 04:05:27

标签: javascript jquery radio

有人可以帮助我,为什么没有检测到更改

这是我的单选按钮表单 -

<form style = "padding:10px; margin:5px;" id="AskMethod">
    Select Option:
    <input type="radio" name="method" value ="TextMethod" checked = "checked">Type text
    <input type="radio" name="method" value ="ImageMethod">Upload Image
</form>

这是我的jquery例程 -

$(document).ready(function() {
    $('input [type=radio][name=method]').on('change', function() {
        switch ($(this).val()) {
            case 'TextMethod':
                alert("Text");
                break;
            case 'ImageMethod':
                alert("Image");
                break;
        }
    });
});

4 个答案:

答案 0 :(得分:0)

请使用下面的change

$('form#AskMethod [type=radio][name=method]').change(function() {
 switch($(this).val()) {
     case 'TextMethod':
         alert("Text");
         break;
     case 'ImageMethod':
         alert("Image");
         break;

});

答案 1 :(得分:0)

需要简单的改变

$('input[type="radio"][name="method"]').on('change', function () {           
        switch ($(this).val()) {
            case 'TextMethod':
                alert("Text");
                break;
            case 'ImageMethod':
                alert("Image");
                break;
        }
    });

答案 2 :(得分:0)

像这样使用

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('label').on('click', function() {
        switch ($(this).find('input[type="radio"][name="method"]').val()) {
            case 'TextMethod':
                alert("Text");
                break;
            case 'ImageMethod':
                alert("Image");
                break;
        }
    });
});
</script>
</head>
<body>

<form style = "padding:10px; margin:5px;" id="AskMethod">
    Select Option:
    <label><input type="radio" name="method" value ="TextMethod" checked = "checked">Type text</label>
    <label><input type="radio" name="method" value ="ImageMethod">Upload Image</label>
</form>

</body>
</html>

答案 3 :(得分:-1)

&#13;
&#13;
$(document).ready(function() {
  $('form#AskMethod [type=radio][name=method]').on('change', function() {

    if ($(this).is(':checked')) {//add condition for checked radio button only

      switch ($(this).val()) {
        case 'TextMethod':
          alert("Text");
          break;
        case 'ImageMethod':
          alert("Image");
          break;
      }

    }

  }).change();//add manually calling change event to call the change event on load
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form style="padding:10px; margin:5px;" id="AskMethod">
  Select Option:
  <input type="radio" name="method" value="TextMethod" checked="checked">Type text
  <input type="radio" name="method" value="ImageMethod">Upload Image
</form>
&#13;
&#13;
&#13;