簡體   English   中英

如何使用jquery限制文本框中前導和尾隨空格的使用?

[英]How to restrict use of Leading and Trailing spaces in the textbox using jquery?

我有多個具有不同值的input字段。 我可以編輯它們,但不能為空(如果為空則顯示警報)。 當我在編輯時如果我用空格來編輯它們,我會使用trim來禁止這樣做。但是,我可以在input的開頭和結尾之間input一個空格來編輯input 。我不需要這個。

如何實現以下目標?

a)不應從空間開始。

b)如果我有一個單詞的話,這個單詞后不能有空格。

<input type="text" class="selector" value="new">
<input type="text" class="selector" value="old">
<input type="text" class="selector" value="newest">
<input type="text" class="selector" value="oldest">
<input type="text" class="selector" value="older">

$('.selector').on('blur',function () {
  var current_value = $.trim($(this).val());
  $(this).attr('value',current_value);
  console.log(current_value);
  if ($('.selector[value="' + current_value + '"]').not($(this)).length > 0 || current_value.length == 0 ) {
    $(this).focus();
    alert('You cannot use this');
  }
});

我的小提琴在這里

你應該用這個

$(this).val(current_value);

代替這個

$(this).attr('value', current_value);

檢查空格的第一個索引是0還是最后一個索引是字符串的結尾,然后顯示警報。

添加以下條件:

if($(this).val().indexOf(" ") == 0 || $(this).val().lastIndexOf(" ") == ($(this).val().length -1) ){
       alert('You cannot use this');
    }

檢查更新的小提琴

代碼段

 $('.selector').on('blur', function() { var current_value = $.trim($(this).val()); $(this).attr('value', current_value); console.log(current_value); if ($('.selector[value="' + current_value + '"]').not($(this)).length > 0 || current_value.length == 0) { $(this).focus(); alert('You cannot use this'); } else if ($(this).val().indexOf(" ") == 0 || $(this).val().lastIndexOf(" ") == ($(this).val().length - 1)) { alert('You cannot use this too'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="selector" value="new"> <input type="text" class="selector" value="old"> <input type="text" class="selector" value="newest"> <input type="text" class="selector" value="oldest"> <input type="text" class="selector" value="older"> 

查看更新的小提琴

$('.selector').on('blur',function () {
    $(this).val($.trim($(this).val()));
    if($(this).val() == "") {
      alert("Empty values not allowed!");
      this.focus();
    }
});

說明
首先修整值,然后檢查是否為空。 如果為空,則發出警報並將焦點對准框

我將使用輸入模式屬性:

<input type="text" class="selector" value="new" pattern="^[^\s]+(\s+[^\s]+)*$" />

正則表達式在此答案中找到。

要在開頭刪除空格並獲取值(刪除字符串左右兩側的所有空格。):

var value = $.trim($("input").val());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM