2014-11-01 136 views
-2

是否可以使用javascript動態檢查表單字段值。 例如,如果我有用於用戶名的表單字段,並且當用戶輸入他們選擇的用戶名,它會檢查此用戶名是否可用,並彈出警告框或根據結果在屏幕上顯示一條消息。動態檢查表單字段值javascript

所有這些都是在不點擊任何按鈕的情況下完成的。數據存儲在一個數組中。

在此先感謝。我試圖通過使用JavaScript來實現這一點。

+0

http://stackoverflow.com/questions/14659098/checking-if-a-textbox-is-empty-在JavaScript的 – Abhi 2014-11-01 13:19:12

回答

0

var username = document.getElementById('username'); 
 
var goBtn = document.getElementById('check'); 
 
var output = document.getElementById('output'); 
 

 
var usernames = ['bob', 'sally', 'alice', 'roy', 'kate', 'phil']; 
 

 
function showResult() { 
 
    output.innerHTML = usernames.join(', '); 
 
} 
 

 
function checkUsername() { 
 
    if (usernames.indexOf(username.value) < 0) { 
 
    usernames.push(username.value); 
 
    username.value = ''; 
 
    } else { 
 
    alert('That username is already taken. Try again.'); 
 
    } 
 
    showResult(); 
 
} 
 

 
goBtn.onclick = checkUsername; 
 
showResult();
<label for="username">Name:</label> 
 
<input id="username" name="username" placeholder="username"> 
 
<button id="check">Go</button> 
 
<div id="output"></div>

0

可能這是你想要的

// usernameArray contains all the usernames that can't be used 
    var usernameArray = ['username1','username2','username3']; 

    // i'm using .kyup() method to get a dynamic result so whenever the user type a letter or 
    // something else (just one caracter) we check that value against our usernameArray list 

    $('#username').keyup(function(){ 
     var value = $(this).val(); 
     if(usernameArray.indexOf(value) >= 0){ 
       alert('sorry, try another username '); 
     }else{ 
      alert('good, you can use this username it is available'); 
     } 

    });