2017-08-29 94 views
-2

我想在輸入時獲取文本字段值。jQuery:在輸入時獲取文本字段的值

<input type="text" name="noofppl"> 

我想它的價值,同時打字,所以如果有人類型小於20,我給一個警告,允許的最小數爲20

請幫助我。

這是我已經試過:

$("#people").focusout(function() { 
    if($(this).val()<20){ 
    alert("Minimum number of people should be 20"); 
    } 
}); 
+2

的http:// API .jquery.com/keyup –

+2

我想讓別人想出一個搜索引擎,你可以問這個到 –

回答

-1

使用jQuery功能KEYUP。每次獲取價值都會獲得價值。每次鍵入時每次顯示消息您必須使用鍵入evet。

+1

如果你沒有提供代碼,或者在最少的示例代碼。 – freginold

1

在這裏,你去了一個解決方案

$('input[name="noofppl"]').keyup(function(){ 
 
    console.log($(this).val()); 
 
}); 
 
    
 
$('input[name="noofppl"]').focusout(function(){ 
 
    if($(this).val().length < 20){ 
 
    alert("Minimum character is 20!!!"); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" name="noofppl">

我用jQuerykeyup & focusout方法。

keyup用於在打字時獲得連續值。

focousout用於檢查字符數。

參考文獻:https://api.jquery.com/keyup/

希望這會幫助你。

0

難道是你正在尋找這樣的東西嗎?在輸入後面添加標籤以顯示文本併爲輸入字段指定一個ID「noofppl」。前一段時間做了這個代碼來限制我的textarea。

var textarea = document.getElementById('noofppl'); 

textarea.on("keypress", function() { 
       var char_label = document.getElementById('charcount_text'); 

       var count = textarea.value.length; 
       var max = 20; 

       var remaining = max - count; 
       if (remaining <= 0) { 
       char_label.innerHTML = '20 character limit reached.'; 
       } else { 
       char_label.innerHTML = remaining +"/20 left"; 
       } 
      }); 
0

$('#myInput').on('keyup', function() { 
 
    console.log($('#myInput')[0].value.length); 
 
});
<input id="myInput" type="text" name="noofppl">

+1

OP要求的最小字符驗證在哪裏? – Shiladitya

0

請檢查:

<input type="text" name="noofppl"> 
$('input').keyup(function(){var yourvalue = $(this).val(); }) 

這應該爲你工作

+1

OP要求的最小字符驗證在哪裏? – Shiladitya

0

請參閱下面的示例:

$("#txt").keyup(function(event) { 
 
    text = $(this).val(); 
 
    $("div").text(text); 
 
}); 
 
$('#txt').focusout(function(){ 
 
    if($(this).val().length < 20){ 
 
    \t alert(" Minimum 20 Words required...!! "); 
 
\t } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" name="noofppl" id="txt"> 
 
<div> 
 

 
</div>

+1

OP要求的最小字符驗證在哪裏? – Shiladitya

0

我會使用input事件監聽器或類似的東西,這裏是簡單的例子,你如何能實現它:jsbin

const $input = $('#input'); 
let t; 
$input.on('input', (el) => { 
    clearTimeout(t); 
    t = setTimeout(() => { 
    if ($input.val().length < 20) { 
     alert('shorter than 20 characters');  
    } else { 
     alert('longer or equal than 20 characters'); 
    } 
    }, 400); 
}) 

更多:MDN input reference