meepmeep
meepmeep

Reputation: 3118

jquery count select inputs matching required value

I have a (django-generated) form with the following content:

<form action="./" id="my_form" method="post">
...
<select name="object_0_status" id="id_object_0_status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>
<select name="object_1_status" id="id_object_1_status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>
<select name="object_2_status" id="id_object_2_status">
<option value="">---------</option>
<option value="1">Online</option>
<option value="2">Offline</option>
<option value="3">Unknown</option>
</select>
    ...
</form>

I am writing a custom validation method (using the JQuery Validations plugin http://docs.jquery.com/Plugins/validation) that is cross-checking different entries on the form. In order to do this, I need to retrieve the number of select boxes which have their selected value set to '1' (e.g. online).

The select boxes are generated by a form factory, so there will be a variable number of them. There are also other select options on the form which should not be counted - just the ones ending '_status'.

What's the cleanest way of doing this?

Thanks

Upvotes: 3

Views: 3827

Answers (2)

fearofawhackplanet
fearofawhackplanet

Reputation: 53378

$('select[id$=_status] option:selected[value="1"]').length;

see example here

Upvotes: 8

Sarfraz
Sarfraz

Reputation: 382666

You can use ends with selector:

alert($('select[id$=_status]').find('option[value=1]').length);

That will go through all select boxes that end with _status in their ids and then find is used to find option in them whose value is set to 1.

Upvotes: 2

Related Questions