How to reset a form using jQuery with .reset() method - javascript

I had working code that could reset my form when I click on a reset button. However after my code is getting longer, I realize that it doesn't work anymore.
<div id="labels">
<table class="config">
<thead>
<tr>
<th colspan="4"; style= "padding-bottom: 20px; color:#6666FF; text-align:left; font-size: 1.5em">Control Buttons Configuration</th>
</tr>
<tr>
<th>Index</th>
<th>Switch</th>
<th>Response Number</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<form id="configform" name= "input" action="#" method="get">
<tr>
<td style="text-align: center">1</td>
<td><img src= "static/switch.png" height="100px" width="108px"></td>
<td id="small"><input style="background: white; color: black;" type="text" value="" id="number_one"></td>
<td><input style="background: white; color: black;" type="text" id="label_one"></td>
</tr>
<tr>
<td style="text-align: center">2</td>
<td><img src= "static/switch.png" height="100px" width="108px"></td>
<td id="small"><input style="background: white; color: black;" type="text" id = "number_two" value=""></td>
<td><input style="background: white; color: black;" type="text" id = "label_two"></td>
</tr>
<tr>
<td style="text-align: center">3</td>
<td><img src= "static/switch.png" height="100px" width="108px"></td>
<td id="small"><input style="background: white; color: black;" type="text" id="number_three" value=""></td>
<td><input style="background: white; color: black;" type="text" id="label_three"></td>
</tr>
<tr>
<td style="text-align: center">4</td>
<td><img src= "static/switch.png" height="100px" width="108px"></td>
<td id="small"><input style="background: white; color: black;" type="text" id="number_four" value=""></td>
<td><input style="background: white; color: black;" type="text" id="label_three"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="configsubmit" value="Submit"></td>
</tr>
<tr>
<td><input type="reset" id="configreset" value="Reset"></td>
</tr>
</form>
</tbody>
</table>
</div>
And my jQuery:
$('#configreset').click(function(){
$('#configform')[0].reset();
});
Is there some source that I should include in my code in order for the .reset() method to work? Previously I was using:
<script src="static/jquery.min.js"></script>
<script src="static/jquery.mobile-1.2.0.min.js"></script>
and the .reset() method was working.
Currently I'm using
<script src="static/jquery-1.9.1.min.js"></script>
<script src="static/jquery-migrate-1.1.1.min.js"></script>
<script src="static/jquery.mobile-1.3.1.min.js"></script>
Could it possibly be one of the reason?

you may try using trigger() Reference Link
$('#form_id').trigger("reset");

http://jsfiddle.net/8zLLn/
$('#configreset').click(function(){
$('#configform')[0].reset();
});
Put it in JS fiddle. Worked as intended.
So, none of the aforementioned issues are at fault here. Maybe you're having a conflicting ID issue? Is the click actually executing?
Edit: (because I'm a sad sack without proper commenting ability) It's not an issue directly with your code. It works fine when you take it out of the context of the page that you're currently using, so, instead of it being something with the particular jQuery/javascript & attributed form data, it has to be something else. I'd start bisecting the code around it out and try to find where it's going on. I mean, just to 'make sure', i suppose you could...
console.log($('#configform')[0]);
in the click function and make sure it's targeting the right form...
and if it is, it has to be something that's not listed here.
edit part 2: One thing you could try (if it's not targeting it correctly) is use "input:reset" instead of what you are using... also, i'd suggest because it's not the target that's incorrectly working to find out what the actual click is targeting. Just open up firebug/developer tools, whathave you, toss in
console.log($('#configreset'))
and see what pops up. and then we can go from there.

According to this post here, jQuery has no reset() method; but native JavaScript does. So, convert the jQuery element to a JavaScript object by either using :
$("#formId")[0].reset()
// or
$("#formId").get(0).reset()

This is one of those things that's actually easier done in vanilla Javascript than jQuery. jQuery doesn't have a reset method, but the HTML Form Element does, so you can reset all the fields in a form like this:
document.getElementById('configform').reset();
If you do this via jQuery (as seen in other answers here: $('#configform')[0].reset()), the [0] is fetching the same form DOM element that you would get directly via document.getElementById. The latter approach is both more efficient and simpler though (since with the jQuery approach you first get a collection and then have to fetch an element from it, whereas with the vanilla Javascript you just get the element directly).

First line will reset form inputs
$('form#myform').trigger("reset"); //Line1
$('form#myform select').trigger("change"); //Line2
Second one will reset select2
Optional: You can use this if you have different types registered with different events
$('form#myform select, form input[type=checkbox]').trigger("change"); //Line2

A reset button doesn't need any script at all (or name or id):
<input type="reset">
and you're done. But if you really must use script, note that every form control has a form property that references the form it's in, so you could do:
<input type="button" onclick="this.form.reset();">
But a reset button is a far better choice.

jQuery does not have reset() method; but native JavaScript does. So, convert the jQuery element to a JavaScript object by either using :
$("#formId")[0].reset();
$("#formId").get(0).reset();
We may simply use Javascript code
document.getElementById("formid").reset();

I've finally solve the problem!!
#RobG was right about the form tag and table tag. the form tag should be placed outside the table. with that,
<td><input type="reset" id="configreset" value="Reset"></td>
works without the need of jquery or anything else. simple click on the button and tadaa~ the whole form is reset ;) brilliant!

I use this simple code:
//reset form
$("#mybutton").click(function(){
$("#myform").find('input:text, input:password, input:file, select, textarea').val('');
$("#myform").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
});

By using jquery function .closest(element) and .find(...).
Getting the parent element and looking for the child.
Finally, do the function needed.
$("#form").closest('form').find("input[type=text], textarea").val("");

A quick reset of the form fields is possible with this jQuery reset function.
when you got success response then fire below code.
$(selector)[0].reset();

You can just add an input type = reset with an id = resetform like this
<html>
<form>
<input type = 'reset' id = 'resetform' value = 'reset'/>
<!--Other items in the form can be placed here-->
</form>
</html>
then with jquery you simply use the .click() function on the element with the id = resetform as follows
<script>
$('#resetform').click();
</script>
and the form resets
Note: You can also hide the reset button with id = resetform using your css
<style>
#resetform
{
display:none;
}
</style>

Here is simple solution with Jquery. It works globally. Have a look on the code.
$('document').on("click", ".clear", function(){
$(this).closest('form').trigger("reset");
})
Add a clear class to a button in every form you need to reset it. For example:
<button class="button clear" type="reset">Clear</button>

<button type="reset">Reset</reset>
Simplest way I can think off that is robust. Place within the form tag.

Your code should work. Make sure static/jquery-1.9.1.min.js exists. Also, you can try reverting to static/jquery.min.js. If that fixes the problem then you've pinpointed the problem.

You can use the following.
#using (Html.BeginForm("MyAction", "MyController", new { area = "MyArea" }, FormMethod.Post, new { #class = "" }))
{
<div class="col-md-6">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
#Html.LabelFor(m => m.MyData, new { #class = "col-form-label" })
</div>
<div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
#Html.TextBoxFor(m => m.MyData, new { #class = "form-control" })
</div>
</div>
<div class="col-md-6">
<div class="">
<button class="btn btn-primary" type="submit">Send</button>
<button class="btn btn-danger" type="reset"> Clear</button>
</div>
</div>
}
Then clear the form:
$('.btn:reset').click(function (ev) {
ev.preventDefault();
$(this).closest('form').find("input").each(function(i, v) {
$(this).val("");
});
});

Related

Simplify the JS that forces IE11 to open a link in google chrome

I did have a short cut to a post here that explained how to combine the code below to make it easier for me to use it on muliple links.
Our company (for the time being is forcing us to use IE11) and I need to be able to add a link to a webpage that opens it in google chrome. The code I have is:
<script type="text/javascript">
function openURL1()
{
var shell = new ActiveXObject("WScript.Shell");
shell.run("Chrome https://hotmail.com/");
}
function openURL2()
{
var shell = new ActiveXObject("WScript.Shell");
shell.run("Chrome https://google.com/");
}
</script>
<TD COLSPAN="2" STYLE= WIDTH="100"> <input type="button" style ="background-color:grey" onclick="openURL1()" value="Support Net"></TD>
<TD COLSPAN="2" STYLE= WIDTH="100"> <input type="button" style ="background-color:grey" onclick="openURL2()" value="Communities"></TD>
Just want to display link to click on thats all. 1 I don't need to do anything but i have several links that I need to add. HTML code I can work my way round but I am still a newbie when it comes to JS and struggle still. cheers
If i read your request correct, you're looking for something like:
function openURL(url) {
let shell = new ActiveXObject("WScript.Shell");
shell.run("Chrome " + url);
}
a single function with the url as a parameter, so you can reuse it?
Html body portion following your current example:
<TD COLSPAN="2" STYLE="WIDTH: 100;"> <input type="button" style ="background-color:grey;" onclick="openURL('https://hotmail.com/')" value="Support Net"></TD>
<TD COLSPAN="2" STYLE="WIDTH: 100;"> <input type="button" style ="background-color:grey;" onclick="openURL('https://google.com/')" value="Communities"></TD>
<TD COLSPAN="2" STYLE="WIDTH: 100;"> <input type="button" style ="background-color:grey;" onclick="openURL('https://stackoverflow.com/')" value="Helpful People"></TD>

js how to change id inside cloned form with its own new id

I have a section called duplicator1. I want to clone that section and it works but my issue is when section is cloned id of elements are same, so how can I change id when section is cloned.
My js functions
var countCopies1;
var clone ;
function duplicate() {
var original = document.getElementById('duplicater1');
clone = original.cloneNode(true);
var countCopies = $('body').html().split('duplicater').length;
clone.id = "duplicater"+countCopies;
original.parentNode.appendChild(clone);
countCopies1 = countCopies;
}
My table with id duplicater1. When I duplicate it id changes to duplicater2, duplicater3 and so on, but my id customer, project, post, hours stay the same in new duplicated table. How can I change them & I need in duplicater2 id customer1, project1, post1, hours1.
I will be thankful if u help me!
<div id="duplicater1">
<br></br>
<table class="table table-bordered">
<thead>
<tr>
<th style="width:16%;text-align:center">{Customer}</th>
<th style="width:16%;text-align:center">{Project}</th>
<th style="width:16%;text-align:center">{Activity}</th>
<th style="width:16%;text-align:center">{Hours}</th>
<th style="width:16%;text-align:center">{Comment}</th>
<th style="width:5%"> </th>
</tr>
</thead>
<tbody>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="customer" class="form-control" onchange="getCustomerAddWork(this)">{CUSTOMERS}</select></div>
</td>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="project" class="form-control" onchange="getProjectAddWork(this)"></select></div>
</td>
<td>
<div class="form-inline" style="text-align:center"><select style="width:200px" id="post" class="form-control"></select></div>
</td>
<td>
<div class="form-inline" style="text-align:center">
<div class="form-group">
<input type="number" class="form-control" id="hours" placeholder="{Hours}">
</div>
</div>
</td>
<td>
<div class="form-inline" style="margin-bottom:1em;text-align:center">
<div class="form-group">
<textarea class="form-control" id="comment" placeholder="{Comment}"></textarea>
</div>
</div>
</td>
<td>
<button type="button" class="btn btn-danger" style="width:70px"
onclick="Remove()">{Delete}</button>
</td>
</tbody>
</table>
</div>
</div>
<div class="container-fluid bg-2 text-center" style="margin-top:5em;margin-bottom:3em;">
<button type="button" class="btn btn-success" onclick="duplicate()">{Add}</button>
<button type="button" class="btn btn-info" onclick="AddWork()">{Submit}</button>
<button type="button" class="btn btn-primary" onclick="Redirect()">{Cancel}</button>
</div>
</form>
Since you have jQuery, I would do something like this:
var original = $("#duplicater1");
function duplicate() {
var countCopies = $("[id^='duplicater']").length + 1;
var cloned = original.clone();
var cloned.attr("id", "duplicater" + countCopies);
$(cloned).find("[id]").each(function(){
var current = $(this);
var currentId = current.attr("id");
var ids = $("[id='" + currentId + "']");
if(ids.length > 1 && ids[0]==this){
var newId = currentId.substring(0, currentId - 1);
current.attr("id", newId + countCopies);
}
});
original.parent().append(cloned);
}
My table with id duplicater1. When I duplicate it id changes to
duplicater2, duplicater3 and so on, but my id customer, project, post,
hours stay the same in new duplicated table. How can I change them & I
need in duplicater2 id customer1, project1, post1, hours1.
Yes, as duplicate identifiers are not good markup you should indeed change them.
However, duplicate identifiers within unique identifiable containers are functionally not an issue (Though still should be changed).
To address your actual question, yes you can write a loop that goes through each element within the duplicator container and append a number to it and I'm sure there are answers showing you how to and they are perfectly fine.
I would however try to address the duplicate identifier issue in another way that doesn't require maintaining code to do this.
An approach I have been using in numerous web projects in those type of scenarios is to use data-id as an attribute to identify the containers and to allow you to group them as well as the elements inside.
Note, you can use classes or data-xxx or what ever takes your fancy, I personally just prefer data-id for these cases
Instead of using <div id="duplicater1/2/3"> just use <div data-id="duplicater"> to identify the "type" of component/form you are working with.
Inside, do the same with each element, such as <select data-id="customer"> or <select data-id="project">
This solves the cloning problem all together as you can now clone each
duplicator without the need to rename anything at all and you don't
need to maintain custom code renaming element identifiers
In regards to the bound events, you don't have to worry about them either as each element when it raises an event such as getProjectAddWork(this) is already within context.
Say you trigger the getProjectAddWork(this) event and need to get to your duplicator container your are in, you can simple do something similar to $(this).closest('[data-id="duplicator"]'); or to get to the outer form $(this).closest('form'); etc..
Sure, you can achieve the same by only renaming the duplicator id as you already do and then do $(this).closest('#duplicator'); but in my humble opinion I rather prevent duplicate identifiers and not having to maintain code to rename identifiers as well as base selectors on contextual awareness within their respective "component"
I use jQuery as you tagged your question with it but you can do the same with just plain JavaScript

jQuery, javascript: several forms same submit button text - how to determine value of closest hidden value box

I have several forms in HTML, each with a submit button and a hidden field. The same javascript function is called when any of the submit buttons are pushed. I want to know which submit button has been pushed. I think I can do this by finding out what the hidden field value is of the corresponding form - but I'm having difficulty with this. My HTML is:
<div id="existingPhotosList">
<table><tbody><tr><td>
<img src="./userPictures/IMG0001.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0001.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
<tr>
<td>
<img src="./userPictures/IMG0002.jpg">
</td>
<td>
<form class="deleteFiles">
<input type="hidden" name="picture" value="IMG0002.jpg">
<input type="submit" name="deleteFile" value="Delete File">
</form>
</td>
</tr>
</tbody>
</table>
</div>
There may be more or less table rows with images and forms on them - depending on how many images are found on the server.
The javascript I have right now is:
$('.deleteFiles').submit(deleteFile);
function deleteFile() {
var myValue = $(this).parent().closest(".picture").val();
alert(myValue);
return false;
}
I'm currently getting undefined as the result of the alert.
I want to know which submit button has been pushed.
As each of your forms only has one submit, you don't have to change your code much.
this in your submit handler will refer to the form, and the element is within the form, so:
var myValue = $(this).find("input[name=picture]").val();
No need to go up to the parent, and closest goes up the ancestry (through ancestors), not down. find goes down (descendants).
the simplest way I think will be:
var myValue = $('input[name=picture]', this).val();
should be:
var myValue = $(this).closest(".deleteFiles").find("input[type=hidden]").val();
here is the demo http://jsfiddle.net/symonsarwar/963aV/
$('.deleteFiles').click(deleteFile);
function deleteFile() {
var me=$(this).closest('tr').find('td:eq(1) input').val();
alert(me)
}

document.getElementById("test").style.display="hidden" not working

I want to hide my form when I click on the submit button. My code is as follows:
<script type="text/javascript">
function hide() {
document.getElementById("test").style.display = "hidden";
}
</script>
<form method="post" id="test">
<table width="60%" border="0" cellspacing="2" cellpadding="2">
<tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold"
align="center">
<td>Ample Id</td>
<td>Find</td>
</tr>
<tr align="center" bgcolor="#E8F8FF" style="color:#006">
<td>
<input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>"
/>
</td>
<td>
<input type="image" src="../images/btnFind.png" id="find" name="find"
onclick="javascript:hide();" />
</td>
</tr>
</table>
</form>
But when I click on the "Find" button, that particular form is not being hidden.
It should be either
document.getElementById("test").style.display = "none";
or
document.getElementById("test").style.visibility = "hidden";
Second option will display some blank space where the form was initially present , where as the first option doesn't
Set CSS display property to none.
document.getElementById("test").style.display = "none";
Also, you do not need javascript: for the onclick attribute.
<input type="image" src="../images/btnFind.png" id="find" name="find"
onclick="hide();" />
Finally, make sure you do not have multiple elements with the same ID.
If your form goes nowhere, Phil suggested that you should prevent submission of the form. Simply return false in the onsubmit handler.
<form method="post" id="test" onsubmit="return false;">
If you want the form to post, but hide the div on subsequent page load, you will have to use server-side code to hide the element:
<script type="text/javascript">
function hide() {
document.getElementById("test").style.display = "none";
}
window.onload = function() {
// if form was submitted, PHP will print the below,
// which runs function hide() on page load
<?= ($_POST['ampid'] != '') ? 'hide();' : '' ?>
}
</script>
Using jQuery:
$('#test').hide();
Using Javascript:
document.getElementById("test").style.display="none";
Threw an error "Cannot set property 'display' of undefined"
So, fix for this would be:
document.getElementById("test").style="display:none";
where your html code will look like this:
<div style="display:inline-block" id="test"></div>
Replace hidden with none. See MDN reference.
There are two ways of doing this.
Most of the answers have correctly pointed out that style.display has no value called "hidden". It should be none.
If you want to use "hidden" the syntax should be as follows.
object.style.visibility="hidden"
The difference between the two is the visibility="hidden" property will only hide the contents of you element but retain it position on the page. Whereas the display ="none" will hide your complete element and the rest of the elements on the page will fill that void created by it.
Check this illustration
its a block element, and you need to use none
document.getElementById("test").style.display="none"
hidden is used for visibility
Maybe you can add a class like 'hide'.
Follow the example here : https://developer.mozilla.org/fr/docs/Web/API/Element/classList.
document.getElementById("test").classList.add("anotherclass");
you need to use display = none
value hidden is connected with attributet called visibility
so your code should look like this
<script type="text/javascript">
function hide(){
document.getElementById("test").style.display="none";
}
</script>
you can use something like this....div container
<script type="text/javascript">
function hide(){
document.getElementById("test").innerHTML.style.display="none";
}
</script>
<div id="test">
<form method="post" >
<table width="60%" border="0" cellspacing="2" cellpadding="2" >
<tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
<td>Ample Id</td>
<td>Find</td>
</tr>
<tr align="center" bgcolor="#E8F8FF" style="color:#006" >
<td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
<td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>
</tr>
</table>
</form>
</div>
Through JavaScript
document.getElementById("test").style.display="none";
Through Jquery
$('#test').hide();
this should be it try it.
document.getElementById("test").style.display="none";

JQuery mobile not styling user input check item to same as the rest of list

I have finally succeeded in being able to add user input items to a check list. However, when they are added they are not taking on Jquery Mobiles style.
This is a screen shot of what is happening
This is the HTML:
<h3>My items</h3>
<table id="myTable">
<tr>
<td>
<label for="checkbox65">
<input name="checkbox65" class="checkbox65" type="checkbox" />
My stuff
</label>
</td>
</tr>
<tr>
<td>
<fieldset data-role="controlgroup">
<label for="textinput4">
Add new item
<input name="new_item" id="textinput4" placeholder="" value="" type="text" />
</label>
</fieldset>
<button id="add">Add</button>
/td>
</tr>
</table>​
This is the script for adding the user input item to the check list:
<script type="text/javascript">
$(document).on('click', '#add', function(e) {
var $this = $(this);
var $firstRow = $this.closest('table').find('tr:first');
var $newRow = $firstRow.clone();
var input = $newRow.find(':input').remove();
input.prop('checked', false);
$newRow.empty().append(input).append(' ' + $('#textinput4').val());
$newRow.insertAfter($firstRow);
});
</script>
I read on a different question that perhaps I could include
$('[type='submit']').button();
in order to style the user input items. However, I am unsure if this is right for me or where I would put this in my script?
Thanks.
This should be used:
$('[type="checkbox"]').checkboxradio();
If you want to find out more about this and how dynamically added content can be correctly styled take a look at my blog ARTICLE, there you will find everything about enhancing dynamically added jQuery Mobile content. Or you can find it HERE.
At first sight you code has a jQuery syntax bug, it should look like this:
$('[type="submit"]').button();

Categories