I have the following problem:
I have a form I need to serialize but I am using javascript to change the look of the select fields. This means, the real select fields are hidden using display:none.
My Problem is now, that jQuery does recognize the hidden selects, but only serializes the first value and not the selected one.
<select name="publish">
<option value="1">yes</option>
<option value="2" selected="selected">no</option>
</select>
jQuery.serialzie: publish=1
so it gives me the first and not the correct value.
Any ideas for a workaround?
Solutions
Okay, as mentioned by RobW, the best solution is probably to just let the JavaScript select the option you want by setting the selectElement.selectedIndex = 5
My solution however is a little different, because I do not want to change the plugin used to change the appearance of my selects, due to maintenance problems (as in, needing to change the script every time they release a new version).
I did just use a custom function for serialization.
(function($) {
$.fn.serializer = function() {
var toReturn = [];
var elements = $(this).find(':input').get();
$.each(elements, function() {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type)))
{
var val = $(this).val();
// if is select, check selected
if(this.nodeName == "SELECT")
{
val = $(this).find('option:selected').val();
}
toReturn.push( encodeURIComponent(this.name) + "=" + encodeURIComponent( val ) );
}
});
return toReturn.join("&").replace(/%20/g, "+");
}
})(jQuery);
If the issue is caused by hidden elements, temporary show them before serializing:
Edit: It seems that you’re trying to select an option by setting the
selected=selectedattribute. You should useselectedIndexto change the selected option: