jQuery select: $(input[type='select']) and $('select') type

| 1 Comment | No TrackBacks
I discovered an issue while looking at someone's jQuery code, and the issue seems to be misunderstood elsewhere on the web as well. The issue is using $(input[type=select]) to try to reference a drop-down menu (which uses a <select> HTML tag). Since this seems to be catching developers out, I felt that I needed to write an entry about it. For those who use the Javascript library jQuery, note that a drop-down menu (or list) may involve a different jQuery selector. Normally, a drop-down list would use a <select> object in HTML. It is important to know the structure and the output of the HTML so that the Javascript knows how to understand the DOM (and how this is rendered in jQuery).

An example drop-down menu HTML example is described below:

<select>
   <option value="giraffe">Giraffe</option>
   <option value="zebra">Zebra</option>
   <option value="monkey">Monkey</option>
   <option value="lion">Lion</option>
</select>

The confusion may come out of the fact that many form objects are <input> tags with a defined 'type', such as 'radio' or 'text'. 

The correct way to reference the <select> HTML tag in jQuery is to simply use: $('select').

Note that $(input[type=select]) does not work because the HTML tag is not an <input> tag with a type. It's a <select> tag. Simple.

No TrackBacks

TrackBack URL: http://jenikya.com/cgi-bin/mt5/mt-tb.cgi/714

1 Comment

Note that you can use selector more specified: $('select[name=select-name][id=id-name]').val();

this will return value of choosen option :) ps. if u like to make this more elastic use smth like this:

$('select[name=selectname][id=idname]').change(function() { var value = $('select[name=select-name][id=id-name]').val(); if(value==='0'){ // when option value is equal 0 }else{ // when option value is diff then 1 } });

Leave a comment

Archives

Recent Comments

  • rpicheta: Note that you can use selector more specified: $('select[name=select-name][id=id-name]').val(); this read more
OpenID accepted here Learn more about OpenID