I am developing an ASP.net application that includes several modal popup forms. Each of these contains several textboxes, some hidden fields, some checkboxes and one or two dropdown lists, and before any of these popups are displayed, I need to clear any data that may have been previously entered into these controls.
I have previously had a separate javascript function for clearing each of these popups which accessed each control by name and then set it to the desired default value. This works okay but is quite verbose and unwieldy. I would like to use jQuery to create a single function that would select all controls of each type (textbox, hidden, checkbox and dropdown list) inside the div whose id is passed to the function, and then reset them.
So far, I have succeeded with textboxes and checkboxes, but I'm having no luck with dropdown lists, which need to all be set to selectedIndex = 0. Can somebody show me some code that would effectively reset all dropdown lists within a given div?
Attached is the code from the test site I have been using to develop this function
testing.js:
/// <reference path="jquery-3.2.1.js" />
function PassTest(ThisDivID) {
var DivID = '#' + ThisDivID;
// Set all textboxes to 'Hello!'
$(DivID).find("input[type=text]").val('Hello!');
// Set all checkboxes checked
$(DivID).find('input[type=checkbox]').each(function () {
this.checked = false;
});
// Set selectedIndex of each dropdown list to 0 -- THIS IS THE PART THAT DOESN'T WORK.
$(DivID).find("input[type=select]").each(function () {
this.get(0).selectedIndex = '0';
});
// Make sure function has run all the way to the end
alert('penner');
}
-----------------
jsTest.aspx:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="jsTest.aspx.vb" Inherits="jsTest" %>
<!DOCTYPE html>
<html xmlns="
http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Javascript Test</title>
<script src="Testing.js"></script>
<script src="jquery-3.2.1.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div id="MyDiv" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" Checked="false" Text="Checkbox No. 1"/><br />
<asp:CheckBox ID="CheckBox2" runat="server" Checked ="false" Text="Checkbox No. 2"/><br />
Textbox #1: <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox><br />
Textbox $2: <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
<asp:DropDownList ID="mydropdownlist" runat="server">
<asp:ListItem Text="Item 0" Value="0" />
<asp:ListItem Text="Item 1" Value="1" />
<asp:ListItem Text ="Item 2" Value="2" />
<asp:ListItem Text ="Item 3" Value="3" />
</asp:DropDownList>
<br />
<input type="button" value="ThisButton" id="ThisButton" onclick="PassTest('<%=MyDiv.ClientID %>'); return false;" />
</div>
</form>
</body>
</html>