I’m using the JQuery toggle() function to allow a user to add a new value to a select box dynamically within a form.
If the user clicks “Add”, a DIV is shown with an input box in it and the “Add” text is changed to “Remove”.
In the case where a user clicks “Add”, then enters some text in the new input box, then clicks “Remove”, I want to clear the input box.
Everything here works, but I am unclear how to reset the form value of the newly created input box in the case where the user toggles “remove”
Here’s my code
$(".newName").click(function(){
var frm = $(this).closest("form");
$(".newContainer", frm).toggle(); // toggles the newContainer to show or hide
$(this).text($(this).text() == 'Add' ? 'Remove' : 'Add'); // changes our text
$("#nameList", frm).prop('disabled', $(this).text() != 'Add') // disables the original list if we are adding a new one
});
<div class="names">
<form id="newForm">
<select id="nameList"></select>
<p><a href="#" class="newName">Add</a></p>
<div class="newContainer">
<input type="text" id="theNewName" />
</div>
</form>
</div>
If you are worried about text (“Add”/”Remove”) getting changed + some optimization: