Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reset input and select form values

Status
Not open for further replies.

axLW

Programmer
Feb 6, 2015
110
GB
Hello, I have some working JS code on my website that shows/hides DIVs.

Code:
function show1() {
   var div_num = $("#choosediv").val();
   if (div_num == 0) {
   $("#div1").hide(); 
   $("#div2").hide(); 
      $(':input', '#div1').each(function () {
   this.value = '';
   });
      $(':input', '#div2').each(function () {
   this.value = '';
   });
	};
   if (div_num == 1) {
   $("#div2").hide(); 
   $("#div1").show(); 
   $(':input', '#div2').each(function () {
   this.value = '';
   });
   	};
	   if (div_num == 2) {
   $("#div2").show(); 
   $("#div1").hide();
   $(':input', '#div1').each(function () {
   this.value = '';
   });
	};
}

The line I'm interested in is:

Code:
$(':input', '#div1').each(function () {
   this.value = '';

What this line does is reset all form values in the shape of <input> fields.
At the same time I would like that line to reset all form values in the shape of <select> fields as well.

I have tried

Code:
$(':input', ':select', '#div2').each(function () {
   this.value = '';

But that doesn't work.
Rather than going in circles (my JS and syntax related knowledge is WEAK) I thought I'd post it here and see if anybody can help.

Thanks
 
2 Things:

1. There is no such thing as a :select pseudo selector for select dropdowns. The :input selector already gets text inputs, textures, and select boxes and buttons.

2. Select fields are a bit more complex than straight text inputs.

You need to actually select a value from their available options to change their value. IE. you can't just assign a blank value to them, you have to make one of their options be the selected option.

So you need change your code and add a bit more logic to it as well, to identify if its a text input or a select.
Code:
$(':input', '#div2').each(function () {
if(this.tagName == "SELECT")
{
   this.options[0].selected="selected";
}
else
{
	this.value="";
}
});

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Why not simply use formname.reset() instead of using jQuery spaghetti hoops.

Chris.

Indifference will be the downfall of mankind, but who cares?
Time flies like an arrow, however, fruit flies like a banana.
Webmaster Forum
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top