Derek
Derek

Reputation: 5037

jQuery find select where value equals

I am building an invoicing system and I use clone on the line item rows so I have multiple select boxes that share the same class invoice_line_item and each one has a unique ID. The problem is I won't always have access to the ID to target it.

Im looking for a way to search all the selects with the class of invoice_line_item to find the one thats selected option value is set to new so I can change its selected value and fire the change event.

I have tried

if($('select.invoice_line_item').val() === 'new'){
   $(this).val(data.hashId).change();
}

and I know a little about .find() but I dont know if that would help me here?

Upvotes: 0

Views: 719

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Try using filter() or each. Your approach does not deal with individual instances

$('select.invoice_line_item').filter(function(){
   return this.value === 'new';
}).val(data.hashId).change();

Upvotes: 1

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

The simplest way to do this is to use jQuery .each to iterate through your elements and manually filter those which have value === new:

$('select.invoice_line_item').each(function() {
    if ($(this).val() === "new") {
        $(this).val(data.hashId).change();
    }
});

Upvotes: 1

Related Questions