3

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

2 Answers 2

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

see example here

Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

this doesn't find if the option is selected though... ?
@fearofawhackplanet: Selected option will give you a length of 1 any way because only one option can be selected. The :selected filter selector can be used though for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.