2016-11-12 20 views
-1

我建有一個輸入字段一個JavaScript應用程序啓動,我要檢查,如果輸入的是X寫Y,但它不工作:的JavaScript如果輸入有「X」

<input type="text" id="inputField" style="color:#cccccc;background-color:#000000" name="inputFeld" size="90" onchange="input()" autofocus> 

這是HTMl an JavaScript:

function input() { 
    var inp = document.getElementById("inputField"); 
    var out = document.getElementById("output"); 
    if (inp.substring(1) == "x") { 
     out.innerHTML = "....."; 
    } 
} 
+0

*,但它不工作* - 幫助任何人。 *什麼*不起作用?它怎麼不起作用? – Li357

+2

你正在HTML元素上調用'substring'?你期望它返回什麼? – Cristy

+0

使用您的瀏覽器控制檯...出現的錯誤是一個很大的線索 – charlietfl

回答

0

您可以使用string[n]在第n個位置(從零開始),以獲得字符。 另外,onchange僅在您突出輸入時觸發,您可能需要使用oninput,而不是每次輸入元素都有輸入時觸發。

<input type="text" id="inputField" style="color:#cccccc;background-color:#000000" name="inputFeld" size="90" onchange="input()" autofocus> 
<p id="output"></p> 
function input() { 
    var input = document.getElementById("inputField").value; 
    var output = document.getElementById("output"); 
    if (input[0] == "x") { 
     output.innerText = "the input starts with x"; 
    } 

} 
1

substring(1)它刪除第一個值。所以請嘗試substring(0,1)並在輸入元素字段中應用value。沒有value沒有gettiing輸入字符串。

function input() { 
 
    var inp = document.getElementById("inputField").value;//value is important 
 
    var out = document.getElementById("output"); 
 
    if (inp.substring(0,1) == "x") { 
 
     console.log('strat with x') 
 
    } 
 
    
 
}
<input type="text" id="inputField" style="color:#cccccc;background-color:#000000" name="inputFeld" size="90" onchange="input()" autofocus>

+0

應該提及使用元素'價值'屬性的重要部分 – charlietfl

+0

我寧願建議'.charAt(0)' – Rajesh