Find the default selected selected in the HTML select tag?

I found the code online to clear the form, but it had nothing to choose from. With jquery, I tried adding code to select the default option in the selection box when I reset the form. I decided that the only way to find the default was to look for where the SELECTED option was. Then I found that when the user selects something else, jquery does not see the selected one by default, but as for the new option that the user has selected.

How do I find the default option on a form so that I can clear it properly?

//http://www.learningjquery.com/2007/08/clearing-form-data $.fn.clearForm = function () { return this.each(function () { var type = this.type, tag = this.tagName.toLowerCase(); if (tag == 'form') return $(':input', this).clearForm(); if (type == 'text' || type == 'password' || tag == 'textarea') this.value = ''; else if (type == 'checkbox' || type == 'radio') this.checked = false; else if (tag == 'select') { //alert($('option', this).size()); alert($('option[selected]', this).val()); } }); }; 
+6
jquery html html-form
source share
4 answers

Usually, the first <option> in <select> used by default, so you can do this:

 $(this).find("option:first").attr("selected", true); 

However, if you reset the entire form, you can reset to execute what was on the page load with a call to .reset() , for example:

 if (tag == 'form') this.reset(); 

I'm not sure that you really are, but you just throw it there. Often your own DOM methods are already very convenient, do not ignore them!

+2
source share

For this, I used the following snippet:

 $(this).val($(this).find('option[selected]').val()); 

option[selected] will get the "hard-coded" selected option (default). option:selected , in contrast, will receive the currently selected options.

This will work for individual samples; for multiple ones, a different approach is chosen:

 $(this).find('option').each(function(i, opt) { opt.selected = opt.defaultSelected; }); 

This also works for individual samples.

+11
source share

I found that Koraktor answer does not work in IE8 and below. I solved this by iterating the options until the default one was found:

 var defaultValue; $(this).find('option').each(function (i, o) { if (o.defaultSelected) { defaultValue = o.value; return; } }); 

Less elegant but works in IE.

+2
source share

Koraktor's answer didn't work for me in Chrome either, and I couldn't use form.reset () because I wanted to reset a subset of the form. I found that the easiest way was to make a default choice when loading the page, and then the reset function works with the same line on all elements returned by the selector :.

  $("#top1 select").each(function() { this.defaultValue = $(this).val(); }); $(".reset").click(function() { $('#top1 :input').each(function() { $(this).val(this.defaultValue); }); }); 
+2
source share

All Articles