View Full Version : jQuery $(':selected') doesn't have 'name' property?

08-20-2010, 05:34 PM
I have a function to create a string of parameters using jquerys serialize() method.

First I get all the text inputs, add radio elements and select elements. Then I run through them and sanitize them (the document.write is just for testing). Then at the end I serialize them.

function getQueryString(){

var fields = $('input[type=text]').add('input:checked').add(':selected').clone();
size = fields.length;
for (i=0 ; i< size ; i++){
document.write(fields[i].value, fields[i].name, '<br/>');

fields[i].value = sanitize(fields[i].value);

query = fields.serialize();

return query;

For some reason though, when I document.write the name of the select fields, it doesn't seem to have one (undefined). Even though it does have a name in the html.

<select name="month">
<option value="1" selected="selected" >January</option>
<option value="2">Febuary</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>

The process works fine for all the other elements. Any idea how I can fix this?

08-20-2010, 05:40 PM
If memory serves, the $(":selected") selector only grabs the <option> element, not the <select>. As such, it can't get the name of the element due to that name being on a parent of the element you are working with.

08-20-2010, 05:50 PM
you know you're dead right!

I changed it to .add('select') and now I can access the name property.

Thank you!

08-21-2010, 02:37 PM
Just to tie up some loose ends in this tread, after a bit more head scratching I realised that while using .add('select') allows me to get the name of the drop down list, it doesn't allow me to get the currently selected option, only the default one. For simplicities sake I ended up just using .val() to get that.