6

I have a set of radio buttons. When primary is selected, the Primary Company field is hidden. I would also like to at this time clear the drop down selection. How can I do this?

<p>
        <label>Company Type:</label>
        <label for="primary"><input onclick="javascript: $('#sec').hide('slow');" type="radio" runat="server" name="companyType" id="primary" checked />Primary</label>
        <label for="secondary"><input onclick="javascript: $('#sec').show('slow');" type="radio" runat="server" name="companyType" id="secondary" />Secondary</label>
        <div id="sec">
        <label for="primary_company">Primary Company:</label>
            <%= Html.DropDownList("primary_company", Model.SelectPrimaryCompanies, "** Select Primary Company **") %>
        </div>

    </p>
RememberME
  • 2,092
  • 4
  • 37
  • 62

5 Answers5

8

You can clear the selection (that is, select the first option) like so:

$("#primary_company").find('option:first')
                     .attr('selected','selected');
karim79
  • 339,989
  • 67
  • 413
  • 406
  • +1. but why the `.parent('select');` part? You could just use `.end()`, right? – David Murdoch Apr 21 '10 at 15:09
  • @David - that was part of a longer chain to serve an evil purpose. (I pasted too much code from one of my test pages), but now that you point that out, `end` is better than `parent('select')`. Thanks. – karim79 Apr 21 '10 at 15:15
4

You can pass null to the jQuery val() method as a nice way to clear a dropdown.

$('#primary_company').val(null);
Blake Taylor
  • 9,217
  • 5
  • 38
  • 41
0

To clear the selection completely (so that not even the first element is selected) you could use:

$('#primary_company').attr('selectedIndex', '-1'); 

If #primary_company is a multiple select box you could use:

$('#primary_company option').attr('selected', false);
prendio2
  • 1,885
  • 17
  • 25
0
$("#primary_company").find('[selected]').removeAttr("selected");
David Murdoch
  • 87,823
  • 39
  • 148
  • 191
0

This is the best short way that works for me:

$("#selectNetBankNameId")[0].selectedIndex = 0;
$("#selectNetBankNameId").trigger("change");
ikos23
  • 4,879
  • 10
  • 41
  • 60
  • Looks strange to me - this question is seven years old, there are multiple answers that look much nicer than yours, and this should be the "best short way"? – Nico Haase Mar 12 '18 at 08:34