首页 > 解决方案 > 我如何使用 jQuery 的 each() 来实现我的字符计数和文本区域切换,每个部分都有自己的表单元素?

问题描述

我的页面在这里有多个复选框,每个复选框下面都有自己的文本区域。在页面加载时,文本区域被隐藏。单击文本区域的复选框toggle,然后在下方显示一个字符计数器。

对于所有复选框/文本区域对,这就像我需要的那样工作。我的问题是,为了节省时间并向客户展示功能,我为每一对重复了 jQuery 代码。我知道有一种方法可以使用each或其中一种方法对所有对使用相同的代码,但我努力让它工作。

在 HTML 中,我尽我所能为所有复选框、文本区域、两者的包装器、每个整个部分的包装器使用 ID 和类,以便能够使用 jQuery 和/或 JS 选择器来选择任何东西。

如果这个问题的措辞不好,请帮助我改进(我认为是一个问题,但 StackOverflow 在页面顶部向我发出了关于被阻止危险的警告。)

我只会粘贴三段重复的代码。

那么,我怎样才能不重复代码并拥有与现在完全相同的功能呢?我认为这将使用each并且可能会更改重新使用的选择器,但我需要帮助!

代码片段:

 

/*
     * orderformpage3.php text area show hide and character count  
     * this code needs to use an each method to iterate instead of repeat. For now, it is repeating.
     */
    $(document).ready(function() {

          /*
           * for birthday parties
           */
          // toggle visibility of text area on checkbox click
          $("#birthdayParties").click(function() {
            // $("#birthdayPartiesInput").toggleClass("show");
            $("#birthdayPartiesWrap").toggle(500);
          });

          // Character counter
          $("#birthdayPartiesInput").on('keyup', function(e) {
            var counter, textEntered, countRemaining;
            // get the number of characters in the box
            textEntered = $("#birthdayPartiesInput").val();
            // number left = number of characters - our maximum
            var counter = (500 - (textEntered.length));
            // access the div for characters remaining
            countRemaining = $("#charactersRemainingBirthday");
            // put the number of characters left into that div
            countRemaining.text(counter + ' characters remnaining');
          });

          /*
           * for fun activities
           */
          // toggle visibility of text area on checkbox click
          $("#funActivities").click(function() {
            // $("#birthdayPartiesInput").toggleClass("show");
            $("#funActivitiesWrap").toggle(500);
          });

          // Character counter
          $("#funActivitiesInput").on('keyup', function(e) {
            var counter, textEntered, countRemaining;
            // get the number of characters in the box
            textEntered = $("#funActivitiesInput").val();
            // number left = number of characters - our maximum
            var counter = (500 - (textEntered.length));
            // access the div for characters remaining
            countRemaining = $("#charactersRemainingFunActivities");
            // put the number of characters left into that div
            countRemaining.text(counter + ' characters remnaining');
          });

          /*
           * for Summer Camps
           */
          // toggle visibility of text area on checkbox click
          $("#summerCamps").click(function() {
            // $("#birthdayPartiesInput").toggleClass("show");
            $("#summerCampsWrap").toggle(500);
          });

          // Character counter
          $("#summerCampsInput").on('keyup', function(e) {
            var counter, textEntered, countRemaining;
            // get the number of characters in the box
            textEntered = $("#summerCampsInput").val();
            // number left = number of characters - our maximum
            var counter = (500 - (textEntered.length));
            // access the div for characters remaining
            countRemaining = $("#charactersRemainingSummerCamps");
            // put the number of characters left into that div
            countRemaining.text(counter + ' characters remnaining');
          });
       });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
    <div class="category-row">
      <div class="form-group row align-items-center">
        <div class="col-xs-1 ml-3">
          <input type="checkbox" name="birthdayparties" class="col-form-label form-control category-checkbox" id="birthdayParties" />
        </div>
        <label for="birthdayParties" class="col-xs-3 ml-2 col-form-label">Birthday Parties</label>
        <div class="col-sm-12 description-wrap hide" id="birthdayPartiesWrap">
          <textarea name="birthdaypartiesdescription" type="text" class="form-control col-form-label category-text" id="birthdayPartiesInput">Lorem Ipsum</textarea>
          <div class="charactersRemaining" id="charactersRemainingBirthday">500 characters remnaining</div>
        </div>
      </div>
    </div>



   <div class="category-row">
          <div class="form-group row align-items-center">
            <div class="col-xs-1 ml-3">
            <?php if ($birthdayparties == true) {$birthdaypartieschecked = 'checked';} else { $birthdaypartieschecked = '';}?>


             <input type="checkbox" name="birthdayparties" class="col-form-label form-control category-checkbox" id="birthdayParties" <?php echo $birthdaypartieschecked; ?>/>
           </div>
            <label for="birthdayParties" class="col-xs-3 ml-2 col-form-label">Birthday Parties</label>
            <div class="col-sm-12 description-wrap hide" id="birthdayPartiesWrap" >
              <textarea name="birthdaypartiesdescription" type="text" class="form-control col-form-label category-text" id="birthdayPartiesInput"><?php echo $_SESSION['birthdaypartiesdescription']; ?></textarea>
              <div class="charactersRemaining" id="charactersRemainingBirthday">500 characters remnaining</div>
            </div>
          </div>
        </div>



        <div class="category-row">
          <div class="form-group row align-items-center">
           <div class="col-xs-1 ml-3">
           <?php if ($funactivities == true) {$funactivitieschecked = 'checked';} else { $funactivitieschecked = '';}?>
             <input type="checkbox" name="funactivities" class="col-form-label form-control category-checkbox" id="funActivities" <?php echo $funactivitieschecked; ?>/>
           </div>
            <label for="funActivities" class="col-xs-3 ml-2 col-form-label">Fun Activities</label>
            <div class="col-sm-12 description-wrap hide" id="funActivitiesWrap">
              <textarea name="funactivitiesdescription" type="text" class="form-control col-form-label category-text" id="funActivitiesInput"><?php echo $_SESSION['sessfunactivitiesdescription']; ?></textarea>
              <div class="charactersRemaining" id="charactersRemainingFunActivities">500 characters remnaining</div>
            </div>
          </div>
        </div>

        <div class="category-row">
          <div class="form-group row align-items-center">
           <div class="col-xs-1 ml-3">
           <?php if ($summercamps == true) {
    $summercampschecked = 'checked';
    echo '<script>';
    echo '$("#summerCampsWrap").toggle(100);';
    echo '</script>';
} else {
    $summercampschecked = '';
    echo '<script>';
    echo '$("#summerCampsWrap").toggle(100);';
    echo '</script>';
}
?>




  <input type="checkbox" name="summercamps" class="col-form-label
form-control category-checkbox" id="summerCamps" <?php echo
    $summercampschecked; ?>/>
           </div>
            <label for="summerCamps" class="col-xs-3 ml-2 col-form-label">Summer Camps</label>
            <div class="col-sm-12 description-wrap hide" id="summerCampsWrap">
              <textarea name="summercampsdescription" type="text"  class="form-control col-form-label category-text" id="summerCampsInput"><?php echo $_SESSION['sesssummercampsdescription']; ?></textarea>
              <div class="charactersRemaining" id="charactersRemainingSummerCamps">500 characters remnaining</div>
            </div>
          </div>
        </div>

标签: javascriptjqueryhtmldry

解决方案


您不需要依赖,id因此您可以使您的代码更加抽象。
您可以将this其用作对当前元素的引用,然后使用nextclosestparent等遍历 DOM find

给你:

/*
 * orderformpage3.php text area show hide and character count  
 * this code needs to use an each method to iterate instead of repeat. For now, it is repeating.
 */
$(document).ready(function() {

  // toggle visibility of text area on checkbox click
  $(".category-checkbox").click(function() {
    $(this).closest(".category-row")
      .find('.description-wrap').toggle(500)
      .find('textarea').keyup();
  });

  // Character counter
  $(".category-text").on('keyup', function(e) {
    var counter, textEntered, countRemaining;
    textEntered = $(this).val();
    var counter = (500 - (textEntered.length));
    $(this).next(".charactersRemaining")
      .text(counter + ' characters remnaining');
  });

});
.hide {
  display: none
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

<div class="category-row">
  <div class="form-group row align-items-center">
    <div class="col-xs-1 ml-3">
      <input type="checkbox" name="birthdayparties" class="col-form-label form-control category-checkbox" id="birthdayParties" />
    </div>
    <label for="birthdayParties" class="col-xs-3 ml-2 col-form-label">Birthday Parties</label>
    <div class="col-sm-12 description-wrap hide" id="birthdayPartiesWrap">
      <textarea name="birthdaypartiesdescription" type="text" class="form-control col-form-label category-text" id="birthdayPartiesInput">birthday parties description</textarea>
      <div class="charactersRemaining" id="charactersRemainingBirthday">500 characters remnaining</div>
    </div>
  </div>
</div>



<div class="category-row">
  <div class="form-group row align-items-center">
    <div class="col-xs-1 ml-3">
      <input type="checkbox" name="funactivities" class="col-form-label form-control category-checkbox" id="funActivities" />
    </div>
    <label for="funActivities" class="col-xs-3 ml-2 col-form-label">Fun Activities</label>
    <div class="col-sm-12 description-wrap hide" id="funActivitiesWrap">
      <textarea name="funactivitiesdescription" type="text" class="form-control col-form-label category-text" id="funActivitiesInput">sess fun activities description</textarea>
      <div class="charactersRemaining" id="charactersRemainingFunActivities">500 characters remnaining</div>
    </div>
  </div>
</div>

<div class="category-row">
  <div class="form-group row align-items-center">
    <div class="col-xs-1 ml-3">
      <input type="checkbox" name="summercamps" class="col-form-label form-control category-checkbox" id="summerCamps" />
    </div>
    <label for="summerCamps" class="col-xs-3 ml-2 col-form-label">Summer Camps</label>
    <div class="col-sm-12 description-wrap hide" id="summerCampsWrap">
      <textarea name="summercampsdescription" type="text" class="form-control col-form-label category-text" id="summerCampsInput"> sess summer camps description</textarea>
      <div class="charactersRemaining" id="charactersRemainingSummerCamps">500 characters remnaining</div>
    </div>
  </div>
</div>

更新

选中复选框时,您可能会遇到问题,但 textarea 是隐藏的。要解决它,您需要更新代码以设置类.hide,如下所示:

<div class="category-row">
  <div class="form-group row align-items-center">
    <div class="col-xs-1 ml-3">
      <?php if ($birthdayparties == true) {$birthdaypartieschecked = 'checked';} else {$birthdaypartieschecked = '';} ?>
      <input type="checkbox" name="birthdayparties" class="col-form-label form-control category-checkbox" id="birthdayParties" <?php echo $birthdaypartieschecked; ?>/>
    </div>
    <label for="birthdayParties" class="col-xs-3 ml-2 col-form-label">Birthday Parties</label>
    <div class="col-sm-12 description-wrap <?php echo ($birthdayparties ? '' : 'hide'); ?>" id="birthdayPartiesWrap">
      <textarea name="birthdaypartiesdescription" type="text" class="form-control col-form-label category-text" id="birthdayPartiesInput"><?php echo $_SESSION['birthdaypartiesdescription']; ?></textarea>
      <div class="charactersRemaining" id="charactersRemainingBirthday">500 characters remnaining</div>
    </div>
  </div>
</div>

推荐阅读