How to select an input by value with jQuery 1.4.3 and higher

So, the solution is to add this to js:

$('input').bind('keyup change',function() {
    $(this).attr('value',this.value)
});

Demo - http://jsfiddle.net/VwVhD/28/

UPDATE (21.02.2013)

After years I came up with this actually:

jQuery('input,textarea').live('keyup change', function(e) {
    var ignore_codes = [16,9,33,34,36,35,45,38,40,37,39];//arrows and others
    if (e.keyCode && jQuery.inArray(e.keyCode, ignore_codes) < 0)//ignore this keyUps to let this keys work as expected
    {
        var cp = getCP(this);
        jQuery(this).attr('value', this.value);
        setCP(this,cp);
    }
    });
    function setCP(ctrl, pos){
        if(ctrl.setSelectionRange) {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        } else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }

As far as I can see, in newer jQuery versions, you can select INPUT elements by their "value" attribute, but not by the current .value property.

When a value is changed by calling .val(), changing the native JS .value or also by direct user input, the HTML attribute is not changed. In former versions, selectors referred to the current value, while now they correctly refer to the HTML attribute.

You can select however the current value with this code:

$('input').filter(function() { return this.value == 'test' });

$('input[value="test"]') Should work fine...

EDIT

You could try using if statements, for example:

$("input").keyup(function(e) { 
    if (this.value == 'foo'){
        $(this).css('backgroundColor','red');
    }
    else if (this.value == 'bar'){
        $(this).css('backgroundColor','green');
    }
    else $(this).css('backgroundColor','white');
});

http://jsfiddle.net/ajthomascouk/HrXVS/

Tags:

Jquery