Pergunta

I have aI need to validate the input by .onblur such that whenever a text input loses focus it gets validated by the same JS function.

My problem is with the JS function. I want to grab the value of the item that loses focus.

function valid(){
if (isNaN("this should be the value of the text item??")){

}

Thankss..

Foi útil?

Solução

To grab the value of an item as you blur, you should add the onBlur trigger to the DOM element as follows:

<input type="text" name="validate_me" onBlur="valid(this);" />

That way you have access to the DOM element that triggered the onBlur event and can access its properties (such as value or innerHTML in the case of textarea elements.

Your valid function can then be something like:

function valid(element) {
  if (element.value != '' && isNaN(element.value))
    alert('This field is not valid!');
};

Outras dicas

This javascript should do what you are asking for:

(function(){
    var after = function(existing,after) {
        if ( existing == null || typeof existing !== 'function' ) {
            return after;
        }
        else {
            return function() { existing(arguments); after(arguments); }
        }
    }

    var validate = function(input) {
        alert('validating ' + input.name);
    }

    window.onload = after(window.onload, function() {
        var inputs = document.getElementsByTagName('input');
        for (var i = 0; i < inputs.length; i++) {
            if ( inputs[i].type === 'text' ) {
                inputs[i].onblur = after(inputs[i].onblur, function() {
                    validate(this);
                });
            }
        }
    });
}());

Clearly you will have to replace the alert in the validate function with your validation logic, but this should do what you ask.

A couple notes, the immediately invoked function is to ensure you don't clobber any globals, and the after function is to ensure that if you there is already an attached listener that your new validate listener will be called after the existing one.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top