Reputation: 758
With jQuery 1.4.2 and many previous version it is possible to select inputs like this:
$('input[value=test]')
But with 1.4.3 and higher this selector doesn't work =( Is there any way to select by value in newer versions of jQuery?
Upvotes: 36
Views: 63999
Reputation: 11
By this code you can select/make checked the input (type radio) by value, which is the same like "for" param in his label.
jQuery('label').click(function() {
labelID = jQuery(this).attr('for'); //find item and save "for" value
jQuery('input[type=radio][value='+labelID+']').trigger('click') ; // find input with value and click
});
Upvotes: 1
Reputation: 3646
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' });
Upvotes: 31
Reputation: 758
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();
}
}
Upvotes: 2
Reputation: 9031
$('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/
Upvotes: 51
Reputation: 249
According to the documentation it should work just fine
http://api.jquery.com/attribute-equals-selector/
you need to use quotes to surround the value
Upvotes: 0