Web Junkie Web Junkie - 26 days ago 7
Javascript Question

JavaScript if input starts with 'x'

I built a JavaScript application with an input field, I want to check if the input is X write Y, but it doesn't work:

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


This is the HTMl an this the JavaScript:

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

Answer

You can use string[n] to get character at n-th position (starts from zero). Also, onchange only triggered when you out-focus the input, you may want to use oninput instead that triggered everytime there is an input to the input element.

<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";
    }

}