Reputation: 3224
I have the element .tousers
, which is an input text field with the value car
.
if($("#compose-child-container-1").find(".tousers").val()=="car") {
}
I want to addClass
to that .tousers
element but how do i select it?
Upvotes: 0
Views: 58
Reputation: 86525
If you're sure there's at most one .tousers
element:
var $_tousers = $('#compose-child-container-1 .tousers');
if ($_tousers.val() == 'car') $_tousers.addClass('found');
If there's more than one, though, the class will be set on all of them if the first one's value is 'car', regardless of the others' values.
Or, if you feel like getting spiffy about it, you could create a custom selector to test against an element's current value.
$.expr[':'].value = function(obj, index, meta, stack) {
console.log(meta);
var candidateValue = meta[3];
return (candidateValue === $(obj).val());
};
...
$('#compose-child-container-1 .tousers:value(car)').addClass('found');
Though this requires building a new selector to test for a different value.
Or, you could have a plugin.
$.fn.withVal = function(val) {
return this.filter(function() { return this.value == val; });
}
...
$('#compose-child-container-1 .tousers').withVal('car').addClass('found');
Note, extending jQuery (either with custom selectors or plugins) is only really worthwhile if you're going to want to use it a few times.
Upvotes: 0
Reputation: 6612
Try this:
$('#compose-child-container-1 .tousers').each(function() {
var el = $(this);
if (el.val() == 'car') {
el.addClass('found');
}
});
Upvotes: 0
Reputation:
Try this one, it's quick and clean:
$("#compose-child-container-1").find(".tousers").filter(function () {
return this.value === 'car';
}).addClass('your-class');
Upvotes: 0
Reputation: 66663
A straightforward solution would be to look in each .tousers
element
$("#compose-child-container-1 .tousers").each(function() {
if($(this).val() == 'car') $(this).addClass('className');
});
Note: [value="car"]
will not work for user-modified values. Hence the loop is pretty much the only solution.
Upvotes: 3
Reputation: 8726
$("#compose-child-container-1").find(".tousers").each(function(){
if($(this).val()=='car'){
$(this).addClass('className');
}
})
Upvotes: 0
Reputation: 35793
I would use filter:
$("#compose-child-container-1 .tousers").filter(function() {
return this.value == "car";
}).addClass('found');
This separates the logic to find the elements from what you actually want to do with them (addClass in this instance).
Upvotes: 0
Reputation: 388316
Here the attribute selector will not work since once the user modifies the value in the input field the attribute is not updated, only the dom elements property is updated
What I would do is
$("#compose-child-container-1").find(".tousers").filter(function(){
return this.value == 'car'
}).addClass('someclass')
Upvotes: 3
Reputation: 1833
Use $(this)
. In your function, you should use $(selector).each(function() { // code }
Upvotes: 0