复选框上的Onclick函数仍然起作用,即使它已被javascript的其他函数取代

时间:2019-04-09 23:12:44

标签: javascript jquery html

我打算让用户单击单选按钮A和B中的一个:

A-允许用户用javascript代替复选onclick函数checkRequired()来检查复选框,该函数一旦选中,就会从输入中删除“必需”。

B-仅允许用户使用checkOne()函数选中1个复选框,替换为checkRequired()函数

问题是我不理解为什么javascript继续使用checkOne()函数,即使我已经检查了全部代码和语法,甚至Google Chrome浏览器中的开发人员工具都已替换了DID SHOW的功能一次检查无线电按钮A后,通过checkRequired()进行检查。从逻辑上讲,它应该运行良好,但是由于某种原因它根本无法正常工作。

function checkRequired() {
        var n = $( "input:checkbox:checked" ).length;
        var requiredCheckboxes = $(':checkbox[required]');
        var chkboxes = $(':checkbox');
        if(n < 1) {
            chkboxes.attr('required', 'required');
        } else {
            requiredCheckboxes.removeAttr('required');
        }
    }


function checkOne() {
        $('.regid-chkbox').on('change', function() {
           $('.regid-chkbox').not(this).prop('checked', false);
        });
    }


function editMeal() {
        var editBrand = document.getElementById("radio-edit-meal-brand");
        var editInfo = document.getElementById("radio-edit-meal-info");

        if (editBrand.checked){
            $('.regid-chkbox').removeAttr('onclick');
            $('.regid-chkbox').attr('onclick', 'checkRequired();');
        } else if (editInfo.checked) {
            /* Making the checkbox only one can be checked */
            $('.regid-chkbox').removeAttr('onclick');
            $('.regid-chkbox').attr('onclick', 'checkOne();');
        }
    }

HTML代码:

<div class="logmod__tab lgm-2" id="ver-form-res">
      <form method="POST" action="">
        <div class="logmod__heading">
          <span class="logmod__heading-subtitle">Enter your information to verify and <strong>edit the meal.</strong></span>
        </div>
        <div class="logmod__form">
        <!-- Upload Image Section -->
         <center>
           <div id="wrapper" class="img-container">
            <img id="output_image" src="image/e2.png" class="preview-img"/>
            <div class="upload-text-container">
              <div class="upload-text"><i class="fa fa-camera" aria-hidden="true"></i><br> Click here to Upload </div>
            </div>
            <input type="file" onchange="preview_image(event)" style="display: none;" name="bran-img" id="bran-image-reg">
           </div>
         </center>
            <div class="sminputs">
              <div class="input full" style="height:auto!important;">
                <label class="string optional" for="user-account-code-dis">Edit Categories*</label>
                <label class="radio-container"> EDIT MEAL\'S BRAND
                  <input required type="radio" checked="checked" value="0" id="radio-edit-meal-brand" name="meal-edit" onclick="editMeal()">
                  <span class="checkmark-radio"></span>
                </label>
                <label class="radio-container"> EDIT MEAL\'S INFO
                  <input required type="radio" value="1" id="radio-edit-meal-info" name="meal-edit" onclick="editMeal()">
                  <span class="checkmark-radio"></span>
                </label>
              </div>
            </div>
            <div class="sminputs">
              <div class="input full">
                <label class="string optional" for="user-account-code-res">Account Code*</label>
                <input class="string optional" name="enable-acccode" maxlength="8" minlength="8" id="user-account-code-res" placeholder="Account Code" type="password" size="8" />
              </div>
            </div>
            <div class="sminputs">
              <div class="input string optional">
                <label class="string optional" for="user-pw-res">Password *</label>
                <input class="string optional first-pw" name="enable-pw" maxlength="255" id="user-pw-res" onkeyup="check_verlist_res();" placeholder="Password" type="password" size="50" />
              </div>
              <div class="input string optional">
                <label class="string optional" for="user-pw-repeat-res">Repeat password *</label>
                <input class="string optional" name="enable-pw-repeat" maxlength="255" id="user-pw-repeat-res" onkeyup="check_verlist_res();" placeholder="Repeat password" type="password" size="50" />
                <span class="hide-password" id="toggle-pw-res" onclick="togglePassResA();">SHOW</span>
              </div>
            </div>
            <div class="sminputs" id="edit-brand-meal">
              <div class="input full" style="height:80px!important">
                <label class="string optional" for="vercode-role">BRAND *</label>
                <select class="role-select" id="brand-type-meal" name="meal-edit-brand" style="width:30vw; height:4vh;">
                  <option value="" selected disabled>BRAND</option>
                  <!-- call out the brand value -->
                  ';
                    $BRANDTYPE = "SELECT * FROM meal_brand WHERE active = 1";
                    $result = $con->query($BRANDTYPE);
                    if ($result->num_rows > 0) {
                      while ($row = $result->fetch_assoc()) {
                        echo '
                        <option value="'.$row["brand_id"].'">' .$row["brand_name"]. '</option>
                        ';
                      }
                    }
                echo
                '</select>
              </div>
            </div>
            <div class="sminputs" id="edit-info-meal-1">
              <div class="input input string optional">
                <label class="string optional" for="meal-name-edit">Meal Name *</label>
                <input class="string optional meal-name" name="meal-name-edit" maxlength="255" id="meal-name-edit" placeholder="Meal Name"/>
              </div>
              <div class="input input string optional">
                <label class="string optional" for="meal-quantity-edit">Meal Default Quantity *</label>
                <input class="string optional meal-quantity" type="number" min="1" step="1" onkeypress="validate(event)" name="meal-quantity-edit" id="meal-quantity-edit" placeholder="00"/>
              </div>
            </div>
            <div class="sminputs" id="edit-info-meal-2">
              <div class="input input string optional" style="height:80px!important">
                <label class="string optional" for="meal-edit-info-brand">BRAND *</label>
                <select class="role-select" id="brand-type-meal-info" name="meal-edit-info-brand" style="width:30vw; height:4vh;">
                  <option value="" selected disabled>BRAND</option>
                  <!-- call out the brand value -->
                  ';
                    $BRANDTYPE = "SELECT * FROM meal_brand WHERE active = 1";
                    $result = $con->query($BRANDTYPE);
                    if ($result->num_rows > 0) {
                      while ($row = $result->fetch_assoc()) {
                        echo '
                        <option value="'.$row["brand_id"].'">' .$row["brand_name"]. '</option>
                        ';
                      }
                    }
                echo
                '</select>
              </div>
              <div class="input input string optional" style="height:80px!important">
                <label class="string optional" for="meal-price-edit">Meal Price *</label>
                <input class="string optional meal-price" type="number" step="0.25" min="1" onkeypress="validate(event)" name="meal-price-edit" id="meal-price-edit" placeholder="RM 0.00"/>
              </div>
            </div>
            <div class="sminputs" id="edit-info-meal-3">
              <div class="input full" style="height:30vh!important;">
                <label class="string optional" for="meal-details-edit">Meal Details*</label>
                <textarea style="height:20vh!important;width:68vw!important" class="string optional meal-details" type="textarea" name="meal-details-edit" id="meal-details-edit" placeholder="Meal Details" /></textarea>
              </div>
            </div>
            <div class="simform__actions">
              <input disabled class="sumbit" name="submit-list-edit-meal" style="font-family:oswald!important;" type="submit" id="submit-res" value="Confirm Edit" />
              <div id="error-message-res" style="font-size:17px;"></div>
              <span class="simform__actions-sidetext">By editing the brand, you are here and agree our <a class="special" onclick="return false;" role="link">Terms & Conditions</a></span>
            </div>
        </div>
       </div>

在这种情况下,预期结果应该可以正常工作,但是由于某些原因,即使Chrome的开发人员工具显示该功能已被替换,该结果也无法正常工作。

3 个答案:

答案 0 :(得分:3)

编辑2:

我发现了问题。在checkOne中,您设置了onChange事件,而我们从未取消设置它。这就是为什么即使您切换单选按钮也会保留支票的原因。

尝试:

function editMeal() {
    var editBrand = document.getElementById("radio-edit-meal-brand");
    var editInfo = document.getElementById("radio-edit-meal-info");

    if (editBrand.checked){
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').off('change');
        $('.regid-chkbox').on('click', checkRequired);
    } else if (editInfo.checked) {
        /* Making the checkbox only one can be checked */
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').off('change');
        $('.regid-chkbox').on('click', checkOne);
    }
}

编辑:

我做了一个快速的模拟代码片段,这似乎可以按照您想要的方式工作。您是否还有其他地方要修改可能导致问题的事件处理程序?

function checkRequired() {
    console.log('Check required');
}

function checkOne() {
    console.log('check one');
}

function editMeal() {
      var editBrand = document.getElementById("radio-edit-meal-brand");
      var editInfo = document.getElementById("radio-edit-meal-info");
      if (editBrand.checked){
          $('.regid-checkbox').off('click');
          $('.regid-checkbox').on('click', checkRequired);
      } else if (editInfo.checked) {
          /* Making the checkbox only one can be checked */
          $('.regid-checkbox').off('click');
          $('.regid-checkbox').on('click', checkOne);
      }
}

$(document).ready(() => {
  $('input[type="radio"]').on('change', editMeal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="radio" id="radio-edit-meal-brand" name="edit-meal"><label for="radio-edit-meal-brand">Check Required</label>
  <input type="radio" id="radio-edit-meal-info" name="edit-meal"><label for="radio-edit-meal-info">Check One</label>

  <input type="checkbox" class="regid-checkbox">
</form>


原始

也许使用事件处理程序语法而不是设置attr onclick

function editMeal() {
    var editBrand = document.getElementById("radio-edit-meal-brand");
    var editInfo = document.getElementById("radio-edit-meal-info");

    if (editBrand.checked){
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').on('click', checkRequired);
    } else if (editInfo.checked) {
        /* Making the checkbox only one can be checked */
        $('.regid-chkbox').off('click');
        $('.regid-chkbox').on('click', checkOne);
    }
}

答案 1 :(得分:0)

如果将属性更正为.attr('onClick')而不是.attr('onclick'),则您的代码应该可以工作。这是区分大小写的。

尽管,如kht所指出的,仅使用on('click')函数可能更有意义。

答案 2 :(得分:0)

与发布的答案类似,即使发布的原始未经修改的Javascript OP也可以正常工作。

function checkRequired() {
  console.log('checkRequired');
  var n = $("input:checkbox:checked").length;
  var requiredCheckboxes = $(':checkbox[required]');
  var chkboxes = $(':checkbox');
  if (n < 1) {
    chkboxes.attr('required', 'required');
  } else {
    requiredCheckboxes.removeAttr('required');
  }
}


function checkOne() {
  console.log('checkOne');
  $('.regid-chkbox').on('change', function() {
    $('.regid-chkbox').not(this).prop('checked', false);
  });
}


function editMeal() {
  var editBrand = document.getElementById("radio-edit-meal-brand");
  var editInfo = document.getElementById("radio-edit-meal-info");

  if (editBrand.checked) {
    $('.regid-chkbox').removeAttr('onclick');
    $('.regid-chkbox').attr('onclick', 'checkRequired();');
  } else if (editInfo.checked) {
    /* Making the checkbox only one can be checked */
    $('.regid-chkbox').removeAttr('onclick');
    $('.regid-chkbox').attr('onclick', 'checkOne();');
  }
}

$(document).ready(() => {
  $('input[type="radio"]').on('change', editMeal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="radio" id="radio-edit-meal-brand" name="edit-meal"><label for="radio-edit-meal-brand">Check Required</label>
  <input type="radio" id="radio-edit-meal-info" name="edit-meal"><label for="radio-edit-meal-info">Check One</label>

  <input type="checkbox" class="regid-chkbox" />
</form>