Is it possible to see what the index is of a Select combobox selection?

I have website with a select box which has a few hundred options.

<select name="breed" id="breed">
<option value="">Please select</option>
<option value="Abyssinian" >Cat: Abyssinian</option>
<option value="American Bobtail" >Cat: American Bobtail</option>
<option value="Mixed (Unknown)" >Cat: Mixed (Unknown)</option>

....

<option value="Mioritic Sheepdog" >Dog: Mioritic Sheepdog</option>
<option value="Mixed (Unknown)" >Dog: Mixed (Unknown)</option>

....

</select>

My problem is that the "Cat: Mixed (Unknown)" and the "Dog: Mixed (Unknown)" both return the same option value.

Is it possible to get the index number of the selected item?

Cheers,

Dave

Dani AI

Generated

As noted, browsers expose a numeric position for the chosen option. That position is zero-based (first option is index 0) and is -1 when nothing is selected; for a multi-select it reports the first selected option. That index is what disambiguates two options that share the same value.

Changing option values to a unique identifier is the cleanest fix (as suggested), but when editing the markup is not possible the least-invasive approach is client-side: add a hidden form field and populate it with the selected option’s index (or a small composite like index+value) before submit. Minimal jQuery example:

<input type="hidden" name="breed_index" id="breed_index" value="">

$('#breed').on('change submit', function(){
  $('#breed_index').val($('#breed option:selected').index());
});

Other practical options, ordered by quality: 1) store stable IDs as option values (best for backend robustness); 2) use <optgroup> to group species so users scan more easily; 3) maintain a server-side index->ID mapping that mirrors the page order and require the client to post an index; 4) if no client or server changes are allowed, there is no reliable way for the server to tell identical values apart because standard form submission only sends the option value.

Cautions: do not rely on visible text for program logic (labels change or are localized). For long lists, use numeric primary keys as values and keep display labels user-friendly — that gives an unambiguous, future-proof mapping between selection and database record.

Recommended Answers

All 4 Replies

Change the value of the option

<option value="Cat Mixed (Unknown)" >Cat: Mixed (Unknown)</option>
....
<option value="Dog Mixed (Unknown)" >Dog: Mixed (Unknown)</option>

Thanks Jorge, that was exactly what I was after.

@albucurus, yes, that would be the obvious thing. However, it's not my site and I'm reluctant to tinker with it.

You can get the index of the selected option using javascript

var index = document.getElementById("breed").selectedIndex;

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.