I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
JS for reset button:
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
Reset Button:
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
Use type="reset" for your button:
<button type="reset">Cancel</button>
try using reset():
document.getElementById("app_number").reset();
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.
$('#app_number').on('change', function () {
// enter code here
});
Please try to use in js like:
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
So answering my own question, any feedback would be appreciated but this is working.
It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.
So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.
I added onkeyup event ion to the input field
<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
and JS to store and retrieve input
document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input
function saveValue(e) {
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return ""; // You can change this to your defualt value.
}
return localStorage.getItem(v);
}
and then reset the form as usual
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
Your reset button :
<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
In js:
function myFunction(){
document.getElementById("app_number").value = "";
}
Related
How can I reset a HTML form with JavaScript? My form actually contains PHP default value.
I used this to clear:
function reset(){
document.getElementById("moduleform_insert").reset();
}
It works perfectly when there is no <input value="0">.
Is there any method that can clear or I should grab each input value and one by one set to empty?
Hope someone would give some advice. Thanks.
You can use jQuery to do this.
function reset(){
jQuery("#moduleform_insert").val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="moduleform_insert" value="0" />
<input type="button" onClick="reset();" value="Reset" />
And if you have multiple input elements, you can change above reset() function to this one, which will loop through all your input elements and set their value to empty (you can put container id or class in front of input jQuery(".container input") ):
function reset(){
jQuery("input").each(function(){
jQuery(this).val('');
});
}
It works perfectly when there is no .
Is there any method that can clear or I should grab each input value
and one by one set to empty?
This is how reset works
The HTMLFormElement.reset() method restores a form element's default
values. This method does the same thing as clicking the form's reset
button.
If you want to clear the values, then simply fetch them and clear them one by one
var form = document.getElementById("moduleform_insert");
var allNumberAndTextInputs = form.querySelectorAll("input[type='number'], input[type='text'] ");
Array.from( allNumberAndTextInputs ).forEach( function( ele ){
ele.value = ""; //set the value to empty
})
function reset() {
document.getElementById("Form").reset();
}
<form id="Form">
<input type="text">
<input type="button" onClick="reset();" value="Reset" />
</form>
var form = $('#myform');
form.find('input:text,textarea,select').val('');
form.find('input:radio,input:checkbox').each(function(){
this.checked = false;
});
This is the base code. You can add 'input:email', 'input:phone' and so on if you like. Or do something like this:
form.find('input').not(':hidden,:submit').val('');
I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".
I have a form where I am calculating the total amount using jQuery.
The function I created for that is updateTotal();
and the form action is another page and the action page has this button:
<button class="btn btn-success" onclick="history.go(-1);" type="submit" name="edit">EDIT</button>
so when the user clicks on the EDIT button page goes back to the form again (first page) and all the filled up details are there except the repetitve fields created using jQuery.
The sample form is here in js fiddle
I just want to run this function updateTotal(); if the user comes to the form by clicking the EDIT (basically browse go back) button..
Is there any way to do this in jQuery?
UPDATES FOR FUTURE REFERENCE - I SOLVED IT LIKE THIS
html:
<input type="text" id="amount" name="amount[]" placeholder="Amount" required="required" class="form-control inputChangeVal reqF reqFamount" data-js-input-type="number" />
and the jQuery :
jQuery(document).ready(function() {
var hiddenTot = jQuery('.reqFamount').val() ;
jQuery(".totalAmount").val(hiddenTot);
});
Define a hidden field to store the computed value.
<input type="hidden" id="hiddenTotal" />
Then store the calculated value to the hidden field with Id 'hiddenTotal'.
function updateTotal() {
var price = 0;
$(".inputChangeVal").each(function() {
var t = parseFloat(jQuery(this).val(), 10);
price = price + t;
});
var total = price.toFixed(2);
$(".totalAmount").val(total);
$("#hiddenTotal").val(total);
}
Then when the browse back is triggered the hiddenfield is automatically filled by the browser.
Next check when the document is ready, read the value of hiddenTotal and write to totalAmount.
$(document).ready(function (){
// read value and set value of totalAmount to hiddentotal;
var hiddenTotal = $("#hiddenTotal").val() || 0; //use the hiddenTotal value or if not present set 0 as the default value
$(".totalAmount").val(hiddentotal)
}
Now totalAmount is restored. This even works when you leave the page and return using your browsers history.
I'm trying to make something using javascript/jquery that is similar to java.
The way to get input in java:
String x = JOptionPane.showInputDialog("Enter a value: ");
.showInputDialog shows GUI and submits a value after "Submit" is clicked.
This is what I've tried: https://jsfiddle.net/1t5pxhj5/2/
This behavior is not possible with Javascript.
You should use events and callbacks to retrieve the specified value.
Your Java code:
String x = JOptionPane.showInputDialog("Enter a value :");
Your Javascript code:
function showInput(message, callback) {
// display dialog
// ...
callback($("input").val()); // this should be returned to getInput after Submit is clicked
});
showInput("Enter a value:", function(x) {
// do something now
});
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="gettext('txt');"/>
to retrieve data use code below
function gettext(id) {
var entereddata = document.getElementById(id);
var value = entereddata.value;
}
Hope my code works. Keep coding
Supposing you have
<input type="text" class="my-input">
<button>click me!</button>
you can retrieve input value in jQuery/Javascript with this instruction;
$(".my-input").val();
if you want to bind the data retrieval to the "click me!" button there is the complete code:
$(".click-me").click(function() {
alert($(".my-input").val());
});
I am trying to make a simple form and button work. I have linked to a JS Fiddle here View JS Fiddle here
<form>
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button type="submit" id="WFFsearch">Search</button>
</form>
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').text();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
I want to be able to enter "nba" without the quotation marks and click the search button, then have a new window which generates the following link http://espn.go.com/nba/statistics. The first part and the last part of all the urls will be the same, it's just the middle that changes (nba, nfl, mlb). Any help would be greatly appreciated, thanks!
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
});
You need val() property, since input is in question, not text(). https://jsfiddle.net/1c93pqj0/2/
you wanna use the .val() instead of .text() as text gets the value between 2 tags <div>here is some text</div> and val gets the value <input value="some value"/>
EzPz! This is a very simple task. First of all though, since you're using jQ to establish your button's click event, you can either drop the attribute type="submit", OR (recommended), create your event on the form's submit. If it were me, I'd id the form and use the forms submit, so that you don't need any alters to your button type="submit" and enter key can still be used in search box to submit the form.
Also, you're trying to .text on an input. Input's have value. In jQuery you can get or set that value by calling .val() instead.
The code:
$('#frmGetStats').on('submit', function (e) {
e.preventDefault();
var searchInput = $('#search').val(),
url = "http://espn.go.com/" + searchInput + "/statistics",
win = window.open(url);
alert("In this sandbox, new windows don't work. \nHowever you can see the link is \n[" + url + "]");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="frmGetStats">
<input type="text" class="form-control" id="search" placeholder="enter sport">
<button id="WFFsearch" type="submit">Search</button>
</form>
To get the value of an input field, use .val(). .text() is for the text in a DOM element.
Clicking on the submit button submits the form by default, which reloads the page and kills the script. You need to return false from the event handler to prevent this.
$('#WFFsearch').on('click', function () {
var searchInput = $('#search').val();
var url = "http://espn.go.com/" + searchInput + "/statistics";
window.open(url);
return false;
});
DEMO