Clear dropdown selection on radio button click
Asked Answered
D

5

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>
Distant answered 21/4, 2010 at 14:57 Comment(0)
A
8

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

$("#primary_company").find('option:first')
                     .attr('selected','selected');
Altigraph answered 21/4, 2010 at 15:2 Comment(2)
+1. but why the .parent('select'); part? You could just use .end(), right?Kendrickkendricks
@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.Altigraph
L
4

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

$('#primary_company').val(null);
Livraison answered 9/9, 2011 at 5:44 Comment(0)
A
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);
Arnoldarnoldo answered 21/4, 2010 at 15:6 Comment(0)
K
0
$("#primary_company").find('[selected]').removeAttr("selected");
Kendrickkendricks answered 21/4, 2010 at 15:8 Comment(0)
G
0

This is the best short way that works for me:

$("#selectNetBankNameId")[0].selectedIndex = 0;
$("#selectNetBankNameId").trigger("change");
Ghastly answered 12/3, 2018 at 8:14 Comment(1)
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"?Shantel

© 2022 - 2024 — McMap. All rights reserved.