How to clear a form? - html

For example I have a form like this:
<form method='post' action='someaction.php' name='myform'>
<input type='text' name='text1'>
<input type='text' name='text2'>
<input type='checkbox' name="check1">Check Me
<textarea rows="2" cols="20" name='textarea1'></textarea>
<select name='select1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type='reset' value='Reset' name='reset'>
<input type='submit' value='Submit' name='submit'>
</form>
When I press Reset it empties all fields. But if I populate some fields using URL params and then press Reset, it only empties fields which I enter after form reload.
How can I empty all fields whether some fields are already populated at the time of form load.

As others pointed out, I think you should reconsider the need to blank the form.
But, if you really need that functionality, this is one way to do it:
Plain Javascript:
function resetForm(form) {
// clearing inputs
var inputs = form.getElementsByTagName('input');
for (var i = 0; i<inputs.length; i++) {
switch (inputs[i].type) {
// case 'hidden':
case 'text':
inputs[i].value = '';
break;
case 'radio':
case 'checkbox':
inputs[i].checked = false;
}
}
// clearing selects
var selects = form.getElementsByTagName('select');
for (var i = 0; i<selects.length; i++)
selects[i].selectedIndex = 0;
// clearing textarea
var text= form.getElementsByTagName('textarea');
for (var i = 0; i<text.length; i++)
text[i].innerHTML= '';
return false;
}
Note that I commented out the case in which I clear the hidden inputs. Most of the time, this is not necessary.
For this to work, you need to call the function from the onclick handler of a button (or some other way), e.g. like this:
<input type='reset' value='Reset' name='reset' onclick="return resetForm(this.form);">
You can test it all here on jsFiddle.
If you use jQuery in your project, you can do this with much less code (and no need to change the HTML):
jQuery(function($) { // onDomReady
// reset handler that clears the form
$('form[name="myform"] input:reset').click(function () {
$('form[name="myform"]')
.find(':radio, :checkbox').removeAttr('checked').end()
.find('textarea, :text, select').val('')
return false;
});
});
Also, note that I do not clear the values of hidden inputs, check-boxes and radio buttons.
Play with this here.

In jquery simply you can use,
$("#yourFormId").trigger('reset');

You will have to clear them all through javascript (or clear it out server side).
The reset button will only reset form elements to their initial value - if this was a specific value, that's what it will be reset to.

If you're using jQuery, the code is much simpler:
$('#my-form').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
You can also remove the :hidden from the .not selector if you want to clear hidden fields as well.

The easiest way to clear a form is by using the HTML tag
<input type="reset" value="Reset">
Example:
<form>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Reset</td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>

A simple way to do it with JS:
<form id="myForm">
<!-- inputs -->
</form>
const { myForm } = document.forms;
myForm.reset();

I've summarized some of the suggestions using jQuery to give a more complete solution to the question:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Demo Forms</title>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<form method='post' action='someaction.php' name='myform'>
<input type='text' name='text1'>
<input type='text' name='text2' value='preset value'>
<input type='checkbox' name="check1">Check Me
<textarea rows="2" cols="20" name='textarea1'></textarea>
<select name='select1'>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type='button' value='Reset' name='reset' onclick="return clearForm(this.form);">
<input type='submit' value='Submit' name='submit'>
<script>
function clearForm(form) {
var $f = $(form);
var $f = $f.find(':input').not(':button, :submit, :reset, :hidden');
$f.val('').attr('value','').removeAttr('checked').removeAttr('selected');
}
</script>
</form>
</body>
</html>
Note that I've added the inclusion of the jquery lib in the head section and added an onclick handler to the Reset button. Lastly, I've added the javascript code based on the feedback from some other answers here.
I have also added a preset value to one text field. The val('') function would not clear such a field, that's why I've also added attr('value','') to the last script line to clear such default values as well.

You can do something similar to this in JS and call it from onclick within your button:
function submit() {
$('#fieldIdOne').val('');
$('#fieldIdTwo').val('');
}
And then in your HTML file:
<button id="submit" onclick="submit(); return false">SIGN UP</button>
If you happen to use this solution with Firebase, it actually won't send anything to the database unless you add return false right after the call.

Another way to do that with HTMLFormControlsCollection:
for (let el of form.elements) el.value = null

I just came across this question and have used an <a> to facilitate clearing a form by reloading the page. It is easy to style an <a> element to appear as a button.
e.g.
Clear
By using ? for the href attribute, the <a> will reload the page from the server without submitting it.
I prefer solutions which do not depend on JavaScript so hopefully this is of some use to someone.

Using JavaScript give the form an ID of 'myform':
document.getElementById('myform').reset();

Related

Show only not empty parameters in query string when sumbitting form

First of all I already saw this: Don't include empty parameters when submitting form
But in form you can have not only input but also select for example and what if someone have Javascript disabled? Isn't there a better way to hide empty parameters?
Let's say I have a form like this:
<form asp-controller="Vehicles" asp-action="Index" method="get" >
<p>
<select asp-for="Length" asp-items="Model.Lengths">
<option value="">All</option>
</select>
Brand: <input type="text" asp-for="Search">
<input type="submit" value="Filter" />
</p>
</form>
Now if I picked length from select box and clicked filter, I have this url in the browser window:
https://localhost:44358/Vehicles?Length=15&Search=
but I want this:
https://localhost:44358/Vehicles?Length=15
or if I only searched brand without picking length I want to have this:
https://localhost:44358/Vehicles?Search=Mercedes
Is there some helper tag like adding to form hide-empty="true" or something like that? Any ready to use element or just simple solution for this simple problem?
If you insisit on achieving this requirement, you could try to disable the input which is empty. For disabled field, it will not generate the query string.
Try something like :
<form asp-controller="Vehicles" asp-action="Index" method="get">
<p>
Brand: <input type="text" id="Search" name="Search">
<input type="submit" value="Filter" onclick="return DisableNullFields();"/>
</p>
</form>
#section Scripts{
<script type="text/javascript">
function DisableNullFields() {
$('input').each(function(i) {
var $input = $(this);
if ($input.val() == '')
$input.attr('disabled', 'disabled');
});
}
</script>
}

I'm trying to append an option value to a form action

I'm trying to append an option value to a form action, using method get. Submit sends the form request but isn't attaching the select option to the action?
So when the form is submitted it should use >
https://url.here.com?domain= users search here + selected option?
Thanks in advance.
<form action="https://url.here.com?domain=" method="get">
<div class="just-arrived-search">
www.<input type="search" name="domain" placeholder="Search" />
<select>
<option value="">All</option>
<option value=".bike">.bike</option>
<option value=".clothing">.clothing</option>
<option value=".guru">.guru</option>
<option value=".holding">.holdings</option>
<option value=".plumbing">.plumbing</option>
<option value=".singles">.singles</option>
<option value=".venture">.ventures</option>
</select>
<button class="btn-new" type="submit">Register Domain</button>
</div>
</form>
UPDATE: Since you edited your initial post to more clearly explain what you are attempting to achieve, here is a simple solution to your issue.
Use JavaScript to append the selected value to the domain before it submits. Change the button to have an onclick attribute as oppose to making it submit the form.
Add this JavaScript to your head section (or wherever you want, but convention is typically the HEAD section or bottom of the body):
<script type="text/javascript">
function submitForm() {
var ext = document.getElementById('ext');
var selected_opt = ext.options[ext.selectedIndex].value;
// Add own code to handle "All" here
var domain = document.getElementById('domain');
// Append selected option
domain.value = domain.value + selected_opt;
// Submit form
document.getElementById('myForm').submit();
}
</script>
And this is the updated HTML code to go along with it:
<form action="https://url.here.com" method="get" id="myForm">
<div class="just-arrived-search">
www.<input type="search" id="domain" name="domain" placeholder="Search" />
<select id="ext">
<option>All</option>
<option>.bike</option>
<option>.clothing</option>
<option>.guru</option>
<option>.holdings</option>
<option>.plumbing</option>
<option>.singles</option>
<option>.ventures</option>
</select>
<button class="btn-new" onclick="submitForm();">Register Domain</button>
</div>
</form>

HTML form action on part of form

I'm making a form and want something to happen when just a certain part of the form has been completed. I've got some checkboxes, a dropdown menu, and three read-only text fields. I need something to pop up when the checkboxes and dropdown fields have been populated, but have no idea how to do this. I tried putting a form within a form, but after that failed and I later read up on the matter, I found that to be impractical. Anyhow, here's my code for the form:
<form action="http://siedb1.sys.virginia.edu/~jhr3ct/Code/Reserve%20Confirmation.php">
Facility: <input type="checkbox" name="facility" value="AFC">AFC
<input type="checkbox" name="facility" value="Memorial Gym">Memorial Gym
<input type="checkbox" name="facility" value="Slaughter">Slaughter
<input type="checkbox" name="facility" value="North Grounds">North Grounds<br>
Type of Room/Court:
<select>
<option value="default">Choose room...</option>
<option value="squash">Squash</option>
<option value="handball">Handball</option>
<option value="racquetball">Racquetball</option>
<option value="multipurpose">Multipurpose</option>
</select><br>
Room: <input type="text" name="start" readonly="readonly"><br>
Start Time: <input type="text" name="start" readonly="readonly"><br>
End Time: <input type="text" name="end" readonly="readonly"><br><br>
<input id="submit" type="submit" value="Submit">
</form>
Thanks for the help!
You might be interested in learning basic javascript form events. There is many tutorials on internet. I suggest you this one: http://www.javascriptkit.com/jsref/select.shtml
If you need to show a popup after all check boxes are checked and the dropdown is changed add this kind of a function to the onclick events of all the check boxes and onchange event of the dropdown box.
function func() {
var inputTags = document.getElementsByTagName('input');
var dropdowns = document.getElementsByTagName('SELECT');
for (var i = 0; i < inputTags.length; i++) {
if (inputTags[i].type == 'checkbox') {
var aCheckBox = inputTags[i];
if(!aCheckBox.checked) {
return;
}
}
}
if(dropdowns[0].value == 'default') {
return;
}
alert("All checkboxes and dropdowns are filled.");
}
<form action="../Confirmation.php">
<input onclick="func()" type="checkbox" name="facility" value="AFC">AFC
<input onclick="func()" type="checkbox" name="facility" value="Slaughter">Slaughter
<select onchange="func()" id="ss">
</form>
Just to point you in the right direction: You will have to use javascript to check your form inputs values, and to show a pop-up window.
You could use jQuery to do that easily, and make a listener for the form submit() action, where you could check if your checkboxes and dropdown are selected.
The jQuery doc is here: http://api.jquery.com/submit/

Use Value of Selected Item in List to Redirect Browser Accordingly [HTML]

Suppose I have a list box with different items, each with unique values, and an 'Enter' button below it. I want to be able to get the value of the selected item at the time of click, and then when have the button property:
ONCLICK="window.location.href='http://somewebsite.com/somefile.php?id="thisvalue"'"
So for example, something like----
<SELECT NAME = ParticipantList STYLE = "WIDTH: 187" SIZE = 18>
<OPTION VALUE='hi'> hello </OPTION>
<SELECT>
<INPUT TYPE="submit" VALUE="Info" ONCLICK="window.location.href='http://helloworld.com/this.php?="hi"'"/>
Can anyone help me figure this out? Much appreciated.
HTML forms are designed to do exactly this when their method is GET:
<form action="http://helloworld.com/this.php" method="get">
<select name="ParticipantList">
<option value="hi">Hello</option>
</select>
<input type="submit">
</form>
This will send the user to http://helloworld.com/this.php?ParticipantList=hi. No JavaScript required.
The Javascript
<script type="text/javascript">
function doAction(){
var selected = document.getElementById('ParticipantList').value;
if (selected == 'hello'){
window.location.href = 'http://somewebsite.com/somefile.php?id=1';
} else if (selected == 'bye'){
window.location.href = 'http://somewebsite.com/somefile.php?id=2';
} else {
alert('unknown option selected');
}
}
</script>
The HTML
<select name="ParticipantList" id="ParticipantList">
<option value="hello">hello</option>
<option value="bye">bye</option>
</select>
<input type="button" name="action" id="action" value="Submit" onclick="doAction()" />

Dynamic HTML Form Entry

Is it possible to make an HTML form that responds to the number of things the user wants to send over?
That is, what I have now is:
<form ...>
<select ...>
<option>1</option>
<option>2</option>
...
</select>
***
</form>
When the user selects one of the options, *** should have
<input type="text" ...>
appear the number of times the user selected.
That is, if the user selected 5 from the options, then the user should see 5 input options. If he changes his mind selected 2 instead, then the page should update accordingly to show only 2 input options.
=====[EDIT]=====
I've changed the code to have the input just be text. The code I have does not work. It doesn't update the number of input fields.
<script type="text/javascript">
<!--
function updateOptions(nvars)
{
var n = nvars;
while(n>0) {
var newdiv1 = "<div>Var name: <input type=\"text\" name=\"var-name\"><br></div>";
var newdiv2 = "<div>Var type: <input type=\"text\" name=\"var-type\"><br></div>";
newdiv1.appendTo("#bloo");
newdiv2.appendTo("#bloo");
n--;
}
}
//-->
</script>
<h3>Create a table in the test db!<h3>
<form name="f1" method="POST" action="createTable.php">
Name of Table: <input type="text" name="table-name"><br>
No of vars: <input type="text" name="numvars" onChange="updateOptions(this.value)"><br>
<div id="bloo"></div>
</form>
It worked when I had a document.write instead of an appendTo, but I essentially want the page the remain the same save for the extra input fields after the user changes the value in the numvars field.
That's a good idea when you want the user to be able to upload an arbitrary number of files or something like that. You can do it with Javascript:
Have an empty DIV near the SELECT
Bind a function to the "onchange" event on the select element
In the function, read the value of the SELECT element and:
Empty the DIV
Create an equivalent number of <INPUT type="text"> inside the DIV
Do you need code? If you do, is Prototype OK?
OK, sorry for the delay, lots of work to do lately.
The following should be enough for you to get an idea. You'll have to study JS though, I don't even know what you're doing with the appendTo stuff in your question.
<html>
<head>
</head>
<body>
<form>
<select id="num" value="1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<div id="container">
<p>
<input type="text" name="var-name" />
<input type="text" name="var-type" />
</p>
</div>
</form>
<script type="text/javascript">
var selectElm = document.getElementById('num');
var containerElm = document.getElementById('container');
var update = function () {
containerElm.innerHTML = '';
for (var i = 0, l = selectElm.value; i < l; ++i) {
containerElm.innerHTML += '<p><input type="text" name="var-name" /><br /><input type="text" name="var-type" /></p>';
} // add a number of couples of <input> equal to selectElm.value
}
//the following stuff says that when <select> changes the function called "update" must fire. Most of the code is for compatibility across browsers.
var listen, evt;
if (document.attachEvent) {
listen = 'attachEvent';
evt = 'onchange' ;
} else {
listen = 'addEventListener';
evt = 'change';
}
try {
selectElm[listen](evt, update);
} catch (e) {
selectElm[listen](evt, update, false);
}
// You do the same in Prototype with a single line:
// selectElm.observe('change', update);
// jQuery also requires only a single line of code.
</script>
</body>
</html>
Yes use onChange event of your dropdown input field and show/hide your input fields.