Validating form input for text and changing it

Here I have a problem that I cannot handle. This is the code, and I want the script to change the input color of the form when the input text changes:

function checkName(name)
{
if (name.value == "value1" || name.value == "value2" || name.value == "value3" || name.value == "value4" || name.value == "value5" || name.value == "value6"){
 document.forms['un'].elements['name'].style.color='#ffbb00'
}
else {
 document.forms['un'].elements['name'].style.color='#000000'
}
}

As you can see, when the entered text matches one of the provided ones, it should be orange, and when not, it should be black. (I have an input that toggles this function using the onChange function) I just can't get it to work, so I may have several options when I need to change color, and also change back when the statement becomes invalid. Any help?

+3
source share
4 answers

I have an input toggling this function with an onChange thingtherefore your entry

<input type=text size=20 name='name' onchange="checkName(this)">

and the function may be

function checkName(el)
{
    if (el.value == "value1" || el.value == "value2" || el.value == "value3" || el.value == "value4" || el.value == "value5" || el.value == "value6")
    {
        el.style.color='#ffbb00'
    }
    else
    {
        el.style.color='#000000'
    }
}

Example.

onkeyup .

+2

:

function checkName(element) {
    if (element.value == ...) {
        element.className = "inputError";
    } else {
        element.className = "";
    }
}

CSS:

.inputError {
    background-color: #FF0000;
    background-image: url(exclamation_mark.png);
    background-position: right 50%;
    background-repeat: no-repeat;
    background-size: contain;
    -moz-background-size: contain;
    -webkit-background-size: contain;
    -o-background-size: contain;
}

, CSS , , , CSS.

, , :

<input id="myTextBox" type="text" onkeyup="javascript: checkName(this);" />

, !

+2

, checkName. , .

checkName event.srcElement.value.

+1

: http://jsfiddle.net/QJG5R/1/

:

var input = document.getElementById('blar');
var highlights = {
    'v':'#888888',
    'va':'#666699',
    'val':'#4444aa',
    'valu':'#2222bb',
    'value':'#0000cc',    
    'value1':'#ff0000',
    'value2':'#00ff00'
};
input.addEventListener('keyup', function(){
    var value = input.value;
    if (highlights[value]) {
        input.style.color = highlights[value];
    } else {
        input.style.color = 'black';
    }    
});​

Html : <input id='blar' type='text' />​

+1

All Articles