使用jQuery有条件地启用按钮

时间:2016-11-08 19:22:29

标签: jquery html if-statement conditional-statements

NotificationListener

jQuery的:

<div class="error-message"></div>

 <form id="satisfaction" onsubmit="return validateInput()">
  <input type="radio" name="satisfied"  value="yes" required /> Satisfied
 <input type="checkbox" name="donate" /> Donate<br />
<input type="radio"  name="satisfied" value="no" required /> Not satisfied
    <input type="text" name="reason" /> Reason<br />
   <input type="submit" value="Submit" />
  </form>
  <script>

我是如何在jQuery中编写代码的,当且仅当选中“满意”按钮时,用户才能检查“捐赠”按钮?

2 个答案:

答案 0 :(得分:1)

你需要做这样的事情

$('input[name="donate"]').attr('disabled', true);

$(document).ready(function() {
  $('input[name="satisfied"]').on('change', function() {
    if ($('input[name="satisfied"]:checked').val() == 'yes')
      $('input[name="donate"]').removeAttr("disabled");
    else
      $('input[name="donate"]').attr('disabled', true);
  });
});

这是小提琴:https://jsfiddle.net/6syhqzf9/

答案 1 :(得分:0)

开始禁用捐赠输入

<input type="radio" name="satisfied"  value="yes" required /> Satisfied
<input type="checkbox" name="donate" disabled="disabled"/> Donate<br />
<input type="radio"  name="satisfied" value="no" required /> Not satisfied

使用change事件,如果用户选择“满意”,则可以启用此框,否则禁用它。

$(document).on('ready', function(){
    $('input[name="satisfied"]').on('change', function(){
        var val = $('input[name="satisfied"]:checked').val(); //either 'yes' or 'no'
        var $donate = $('input[name="donate"]');  //this is the donate input
        if(val == 'yes')
            $donate.prop('disabled', false);
        else
            $donate.prop('disabled', true);
    });
});