删除数据中的空间而不显示它

时间:2016-04-22 10:57:15

标签: javascript jquery css

我有这些输入框,我使用jQuery对它们进行了一些控制。如果插入的数字超过3位数,则会在blur上为它们添加空格,并且在重新输入输入框(focus)后,它将删除空格。这两个功能工作正常!

问题在于,当我想发送这些数据时(点击“检查我”按钮),由于在blur上我向他们添加了空格,这些条目不被视为数字{{1} }。

Problem

我想要一个解决方案来检查这些数据(不在页面上更改它们),在(isNaN)上使用相同的功能(包括在我的代码中),以便正确检查它们并且不会因为空间。



focus

   $(function() {
     $('.ndInbox').blur(function() {
       try {
         // Get your formatted number
         var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
         if (isNaN(formatted) || $(this).val() == "") {
           return;
         }
         // Split off any decimal value (there should be one)
         var sections = formatted.split('.');
         // Replace every third digit with a space
         sections[0] = sections[0].replace(/\B(?=(\d{3})+\b)/g, " ");
         // Output the updated and rejoined sections
         $(this).val(sections.join('.'));
       } catch (err) {
         alert(err);
       }
     });
     $('.ndInbox').focus(function() {
       if ($(this).val() != "") {
         var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
         if (isNaN(formatted)) {
           return;
         }
         $(this).val(formatted);
       }
     });
   });

   $(document).ready(function() {
     $('#btn').click(function() {
       /*
              //it should happen here !!!
              $('.ndInbox').DontKnowWhat(function() {
                if ($(this).val() != "") {
                  var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
                  if (isNaN(formatted)) {
                    return;
                  }
                  $(this).val(formatted); // this one should not be displayed in page
                }
              });
              // till here
       */

       $("#avPurchase01").removeClass("ndLabelRed");
       $("#avPurchase02").removeClass("ndLabelRed");
       $("#avPurchase03").removeClass("ndLabelRed");

       if (isNaN($('#lpcfIn02Id').val())) {
         $("#avPurchase01").addClass("ndLabelRed");
       }
       if (isNaN($('#lpcfIn0sd').val())) {
         $("#avPurchase02").addClass("ndLabelRed");
       }
       if (isNaN($('#lpcfIn0232').val())) {
         $("#avPurchase03").addClass("ndLabelRed");
       }
     });
   });

.ndInbox {
  background-color: white;
  width: 390px;
  height: 42px;
  box-shadow: 0 2px 2px 0 #C2C2C2;
  border: none;
  outline: none;
  font-size: 18px;
  margin-bottom: 10px;
  font-family: 'PT Sans', sans-serif;
  padding-left: 10px;
}
.ndLabel {
  color: #999;
  font-size: 17px;
  font-family: 'PT Sans', sans-serif;
}
.ndLabelRed {
  color: red;
}




jsFiddle Link

4 个答案:

答案 0 :(得分:2)

您可以创建将返回数字的插件:

  $.fn.number = function() {
    if ($(this).val() != "") {
      return Number($(this).val().replace(/\s/g, '')).toFixed(2);
    }
  };

并像这样使用它:

   if (isNaN($('#lpcfIn02Id').number())) {
     $("#avPurchase01").addClass("ndLabelRed");
   }
   if (isNaN($('#lpcfIn0sd').number())) {
     $("#avPurchase02").addClass("ndLabelRed");
   }
   if (isNaN($('#lpcfIn0232').number())) {
     $("#avPurchase03").addClass("ndLabelRed");
   }

答案 1 :(得分:1)

您可以检查isNaN条件,如:

if (isNaN($('#lpcfIn0sd').val().split(" ").join(""))) {
         $("#avPurchase02").addClass("ndLabelRed");
       }

JSFiddle



   $(function() {
     $('.ndInbox').blur(function() {
       try {
         // Get your formatted number
         var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
         if (isNaN(formatted) || $(this).val() == "") {
           return;
         }
         // Split off any decimal value (there should be one)
         var sections = formatted.split('.');
         // Replace every third digit with a space
         sections[0] = sections[0].replace(/\B(?=(\d{3})+\b)/g, " ");
         // Output the updated and rejoined sections
         $(this).val(sections.join('.'));
       } catch (err) {
         alert(err);
       }
     });
     $('.ndInbox').focus(function() {
       if ($(this).val() != "") {
         var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
         if (isNaN(formatted)) {
           return;
         }
         $(this).val(formatted);
       }
     });
   });

   $(document).ready(function() {
     $('#btn').click(function() {
       /*
              //it should happen here !!!
              $('.ndInbox').DontKnowWhat(function() {
                if ($(this).val() != "") {
                  var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
                  if (isNaN(formatted)) {
                    return;
                  }
                  $(this).val(formatted); // this one should not be displayed in page
                }
              });
              // till here
       */

       $("#avPurchase01").removeClass("ndLabelRed");
       $("#avPurchase02").removeClass("ndLabelRed");
       $("#avPurchase03").removeClass("ndLabelRed");

       if (isNaN($('#lpcfIn02Id').val().split(" ").join(""))) {
         $("#avPurchase01").addClass("ndLabelRed");
       }
       if (isNaN($('#lpcfIn0sd').val().split(" ").join(""))) {
         $("#avPurchase02").addClass("ndLabelRed");
       }
       if (isNaN($('#lpcfIn0232').val().split(" ").join(""))) {
         $("#avPurchase03").addClass("ndLabelRed");
       }
     });
   });

.ndInbox {
  background-color: white;
  width: 390px;
  height: 42px;
  box-shadow: 0 2px 2px 0 #C2C2C2;
  border: none;
  outline: none;
  font-size: 18px;
  margin-bottom: 10px;
  font-family: 'PT Sans', sans-serif;
  padding-left: 10px;
}
.ndLabel {
  color: #999;
  font-size: 17px;
  font-family: 'PT Sans', sans-serif;
}
.ndLabelRed {
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<table>
  <tr>
    <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase01">Average, &euro;:</td>
    <td colspan="2">
      <input id="lpcfIn02Id" class="ndInbox" type="text" value="" />
    </td>
  </tr>
  <tr>
    <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase02">Budget, &euro;:</td>
    <td colspan="2">
      <input id="lpcfIn0sd" class="ndInbox" type="text" value="" />
    </td>
  </tr>
  <tr>
    <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase03">Salary, &euro;:</td>
    <td colspan="2">
      <input id="lpcfIn0232" class="ndInbox" type="text" value="" />
    </td>
  </tr>
</table>
<button id="btn">
  Check ME
</button>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

首先$(function(){})$(document).ready()的简写,所以你应该只有1。

其次,根据我的理解,最好创建一个返回Form数据的函数,而不是每次都创建。

我有权更新您的代码。希望它有所帮助!

的变化:

  1. 创建了2个变量idss_idsids是所有ID的父数组。 s_ids是一个包含id的子集数组,需要特殊处理。
  2. 创建了函数getData()cleanData()validateAndUpdateUI()registerEvents()getData()将返回ids中所有ID的值。 cleanData()会删除s_ids中所有ID的空格。 validateAndUpdateUI()将遍历所有ID并验证它们。 registerEvents()只是所有事件绑定的包装函数。这将有助于您的代码清洁和可维护。
  3. Updated JSFiddle

    &#13;
    &#13;
    var ids = ["lpcfIn02Id", "lpcfIn0sd", "lpcfIn0232"];
    var s_ids = ["lpcfIn02Id", "lpcfIn0sd", "lpcfIn0232"];
    
    function getData() {
      return ids.map(function(id) {
        return {
          id: id,
          value: $("#" + id).val()
        };
      });
    }
    
    function cleanData(data) {
      data.forEach(function(o) {
        if (s_ids.indexOf(o.id) > -1)
          o.value = o.value.replace(/\s/g, "");
      });
    }
    
    function initUIState() {
      ids.forEach(function(id) {
        $("#" + id).parent().prev().removeClass("ndLabelRed");
      });
    }
    
    function validateAndUpdateUI(data) {
      data.forEach(function(o) {
        if (isNaN(o.value))
          $("#" + o.id).parent().prev().addClass("ndLabelRed");
      });
    }
    
    function registerEvents() {
      $('.ndInbox').blur(function() {
        try {
          // Get your formatted number
          var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
          if (isNaN(formatted) || $(this).val() == "") {
            return;
          }
          // Split off any decimal value (there should be one)
          var sections = formatted.split('.');
          // Replace every third digit with a space
          sections[0] = sections[0].replace(/\B(?=(\d{3})+\b)/g, " ");
          // Output the updated and rejoined sections
          $(this).val(sections.join('.'));
        } catch (err) {
          alert(err);
        }
      });
      $('.ndInbox').focus(function() {
        if ($(this).val() != "") {
          var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
          if (isNaN(formatted)) {
            return;
          }
          $(this).val(formatted);
        }
      });
      $('#btn').click(function() {
        initUIState();
        var data = getData();
        cleanData(data);
        console.log(data);
        validateAndUpdateUI(data);
      });
    }
    
    $(document).ready(function() {
      registerEvents();
    });
    &#13;
    .ndInbox {
      background-color: white;
      width: 390px;
      height: 42px;
      box-shadow: 0 2px 2px 0 #C2C2C2;
      border: none;
      outline: none;
      font-size: 18px;
      margin-bottom: 10px;
      font-family: 'PT Sans', sans-serif;
      padding-left: 10px;
    }
    .ndLabel {
      color: #999;
      font-size: 17px;
      font-family: 'PT Sans', sans-serif;
    }
    .ndLabelRed {
      color: red;
    }
    &#13;
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
    <table>
      <tr>
        <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase01">Average, &euro;:</td>
        <td colspan="2">
          <input id="lpcfIn02Id" class="ndInbox" type="text" value="" />
        </td>
      </tr>
      <tr>
        <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase02">Budget, &euro;:</td>
        <td colspan="2">
          <input id="lpcfIn0sd" class="ndInbox" type="text" value="" />
        </td>
      </tr>
      <tr>
        <td class="ndLabel" style="position: relative; width: 470px; top:-4px" id="avPurchase03">Salary, &euro;:</td>
        <td colspan="2">
          <input id="lpcfIn0232" class="ndInbox" type="text" value="" />
        </td>
      </tr>
    </table>
    <button id="btn">
      Check ME
    </button>
    &#13;
    &#13;
    &#13;

答案 3 :(得分:0)

为什么不在计算之前使用一些变量来存储数据?

$('#btn').click(function() {
   var average = parseFloat($('#lpcfIn02Id').val().replace(/\s/g,''));
   var budget = parseFloat($('#lpcfIn0sd').val().replace(/\s/g,''));
   var salary = parseFloat($('#lpcfIn0232').val().replace(/\s/g,''));
   /*
          //it should happen here !!!
          $('.ndInbox').DontKnowWhat(function() {
            if ($(this).val() != "") {
              var formatted = Number($(this).val().replace(/\s/g, '')).toFixed(2);
              if (isNaN(formatted)) {
                return;
              }
              $(this).val(formatted); // this one should not be displayed in page
            }
          });
          // till here
   */

   $("#avPurchase01").removeClass("ndLabelRed");
   $("#avPurchase02").removeClass("ndLabelRed");
   $("#avPurchase03").removeClass("ndLabelRed");

   if (isNaN($('#lpcfIn02Id').val())) {
     $("#avPurchase01").addClass("ndLabelRed");
   }
   if (isNaN($('#lpcfIn0sd').val())) {
     $("#avPurchase02").addClass("ndLabelRed");
   }
   if (isNaN($('#lpcfIn0232').val())) {
     $("#avPurchase03").addClass("ndLabelRed");
   }
 });