HTML Form: How to remember text values of button click? - javascript

If you have a form, type some text into it, and press the Enter key, whenever revisiting that form you can double-click on the input box and see the past text submissions.
I have a site that when you press Enter OR click a button, it should take whatever is in the text box and use it for data processing.
This works totally fine when not surrounded by a form but when surrounded by a form an you press the Enter key, it does not act as an enter button push, I believe it's being overridden by the form.
My goal is to have the user be able to press the Enter key as well as click the button to submit the data, but to also remember the text values that were in the text box regardless of which way you submitted the data.
What I have:
<input type="text" id="username-field" class="form-control" placeholder="username">
<input class="btn btn-default" type="button" id="get-name" value="Get Name">
Javascript
$("#get-name").click(function() {
var name = $("#username-field").val();
// ... call other function with name ...
});
$("#get-name").keydown(function(e) {
if (e.which == 13) {
var name = $("#username-field").val();
// ... call other function with name ...
}
");
What I would like to use:
<form>
<input type="text" id="username-field" class="form-control" placeholder="username">
</form>
I tried doing e.preventDefault() when the Enter key is pressed, but this does not remember the text in the input field.
I also considered doing a small cache type thing but am unsure of how I'd go about this.
Any help would be much appreciated!
Thanks!

Doesn't use form at all. Just, why you added it, if you don't use it as intended?
You either mistyped provided code copy-paste, or have errors in yours script (the $("#get-name").val() mistake).
If you want to prevent form from submission, you should e.preventDefault()-it in submission handler, and return false from it:
$('#form-id').submit(function (e) {
e.preventDefault();
// do smth. else here
...
return false;
})
Saving/retriving data with localStorage for HTML5-supporting browsers:
$(function () {
$('form input[type=text]').doubleclick(function () {
var id = $(this).attr("id");
value = localStorage.getItem("form_xxx_" + id);
// do smth. with cached value, ie:
if (value != "")
$(this).val(value); // put in textfield
});
});
$('form').submit(function (e) {
$('form input[type=text]').each(function () {
var id = $(this).attr("id");
localStorage.setItem("form_xxx_" + id, $(this).val());
});
...
// all other work
});
Note: make sure you don't put some user's personal data in browser's local storage -_-

Related

Disable AddEventListener On Submit

I am trying to disable the function I pass to addEventListener when the user clicks on submit. I put code in to prevent user from leaving page if they have entered data on any of the fields. This works fine. If the user tries to navigate away they get a warning as expected. However, I can't seem to figure out how to disable this feature once all of the fields are populated and the user clicks submit. As it stands, they are prompted to make sure they want to navigate away when they click on submit and I don't want this to happen when the user clicks submit.
I've tried something like the below, to try to unbind the beforeunload function based on submit, but this isn't working. I feel like this is the right general idea, but I'm struggling to make this work as I want it to.
$('form').submit(function() {
$(window).unbind('beforeunload');
});
$(window).on('beforeunload',function(){
return '';
});
The code below works as expected:
window.addEventListener('beforeunload', function (event) {
console.log('checking form');
let inputValue = document.querySelector('#myInput').value;
if (inputValue.length > 0) {
console.log(inputValue);
event.returnValue = 'Are you sure you wish to leave?';
}
event.preventDefault();
});
If the user clicks submit I want the beforeunload function to be turned off essentially.
Was able to solve this problem using the suggestion that was made by Bipperty via this SO issue...Narrow Down BeforeUnload To Only Fire If Field Is Changed or Updated. Ultimately the code below is what I used to turn off beforeunload when submitting the form....
var submitting = false;
window.addEventListener("beforeunload", function (event) {
console.log('checking form');
let inputValue = document.querySelector('#myInput').value;
if(inputValue.length > 0 && submitting === false) {
console.log(inputValue);
event.returnValue = 'Are you sure you wish to leave?';
}
event.preventDefault();
});
document.addEventListener("submit", function(event) {
submitting = true;
});
If you bind a handler using .on() you can remove the bound event using .off()
$('form').submit(function() {
$(window).off('beforeunload');
});
$(window).on('beforeunload',function(){
return '';
});
However, I feel in your scenario you don't really need the beforeunload at all if you handle your form submit logically.
I've mocked up an example of how you can logically submit the form if a user chooses to submit the form based on a condition (in this case if all fields aren't filled).
$('form').on('submit', function (e) {
var inputs = $(':text', this);
console.log(inputs.length)
var validInputs = inputs.filter(function () {
return $(this).val().length;
}).length;
if (validInputs > 0 && validInputs < inputs.length) {
var r = confirm("Are you sure you want to leave?");
if (!r) e.preventDefault()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://google.com" method="get">
<input name="a" placeholder="Input 1">
<input name="b" placeholder="Input 2">
<input name="c" placeholder="Input 3">
<button type="submit">Submit</button>
</form>
Update
To prompt the user before leaving a form:
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
See this post
Use the required attribute on each field and you won't need to do all of that. The following demo will refuse any attempts to submit it's form if there's a blank field. It will send to a live test server and a response will be displayed verifying a successful submission.
Demo
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
label {
display: inline-block;
width: 75px
}
[type=submit] {
margin-left: 200px
}
<form id='form' action='http://httpbin.org/post' method='post' target='response'>
<label>Name: </label><input name='Name' type='text' required><br>
<label>Cell: </label><input name='Cell' type='tel' required><br>
<label>Date: </label><input name='Date' type='date' required><br>
<input type="submit">
</form>
<iframe src='about:blank' name='response'></iframe>

How to set text box to appear blank after .click function

So I have a simple log in that requires a user to input values from a json file into two different text boxes ,when the user name and (in this case I have used ID as password) matches then an alert appears to say... "welcome"
After the .click function is carried out the users text still remains in the text box, how can I get both text boxes to appear blank after the .click function?
$(document).ready(function() {
//Hide alert when page loads
$("#loginalert").hide();
$("#invalid").hide();
$("#loginbtn").click(function(event){
$.getJSON('result.json', function(jd) {
var id = $('#userName').val();
var name = $('#userName2').val();
var valid = false;
for (var i=0; i<jd.user.length; i++) {
if ((jd.user[i].ID == id) && (jd.user[i].name == name)) {
valid=true;
$('#loginalert').html('<img src="' + jd.user[i].imgpath + '"><br><p> Welcome: ' + jd.user[i].name + '</p><button type="button" id="btnhide" class="btn btn-primary btn-md">Hide</button>');
//show the alert after loading the information
$("#loginalert").stop().fadeIn('slow').animate({ opacity: 1.0 }, 3000)
$('#invalid').hide();
$('#btnhide').on('click', function(e){
//console.log('here');
e.preventDefault();
$('#loginalert').hide();
});
}
}
if (!valid) {
$('#invalid').fadeIn('slow');
$('#loginalert').hide();
}
});
}); });
username 1 and #username 2 are the text boxes - is there any way to get user name 2 to display in stars ****** when the user enters the password - this question is not that necessary but if i could also get that working that would be good.
thanks guys hope someone can help :)
is there any way to get user name 2 to display in stars ****** when
the user enters the password
You can use an input box with text property set as password. But that password masking character will be . instead of *. Not exactly sure, whether it will be a different character in some browsers.
<input type="password" id="txtPassword" />
text box to appear blank after .click function
You can set the .val() property of the jQuery objects of two those two textboxes.
$('#userName, #username2').val('');
Use <input type="password"> to show typing as stars.
Clear inputs by setting their value to be empty: $('#userName').val('');
And perhaps consider breaking your code down into a couple smaller functions so it's easier to follow.
document.getElementById("#myTextbox").value="";
This should get your textbox and set the value of it to "", which is blank.
Edit: JSFiddle
Another Method:
You can also add the script directly inside the button without using/creating a function.
<input id="inputId" type="name" />
<button onclick="document.querySelector('#inputId').value='';"> Clear </button>
Using querySelector:
<input id="inputId" type="name" />
<button onclick="click()"> Clear </button>
<script>
function click() {
document.querySelector('#inputId').value="";
}
</script>

Displaying an image after pressing submit html

I have the following code to display an image after i press submit
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" onclick="$('#image1').show()"/>
Name is retrieved by
var y=document.forms["myForm"]["fname"].value;
Where fname is
<h4>Name: <input type="text" name="fname" size="61" /></h4>
Only problem is this is using Jquery, so I can't seem to pass it through any of my other
validations like checking if the name field is null.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
Is there a Javascript equivalent to this that I can stick in my else statement so it will only show it if the form actually submits properly passing the validation checks beforehand?
Thanks
do all that in jquery.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
else
{
$('#image1').show()
}
You should be using the .submit() event handler of jQuery instead of attaching an onclick property to the submit button. The onclick property will not fire its function in the event that a user submits the form via the enter key; however, the .submit() method will capture it as well.
$("form[name=myForm]").submit(function(e) {
//get value of name here.
var name = this.fname.value; //this refers to the form, because that is what is being submitted.
//Do validation.
if (name == null || name == "") {
//If failed, then prevent the form from submitting.
alert("First name must be filled out.");
e.preventDefault();
return;
}
//If validation passed, show image.
$("#image1").show();
});
First, remove the onclick attribute from the submit button:
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" />
Since you're using jQuery, attaching handlers to click events in JavaScript is a snap (and it's also a good practice).
I almost always use the following pattern for form validation (and on the submit of the form, rather than the click of the submit button because there are other ways to submit forms than clicking the button).
$(document).ready(function () {
var formIsValid = function formIsValid () {
// your validation routines go here
// return a single boolean for pass/fail validations
var name =document.forms.myForm.fname.value;
return !!name; // will convert falsy values (like null and '') to false and truthy values (like 'fred') to true.
};
$('form').submit(function (e) {
var allGood = formIsValid();
if (!allGood) {
e.preventDefault();
}
$('#image1').toggle(allGood); // hide if validation failed, show if passed.
return allGood; // stops propagation and prevents form submission if false.
});
});

Pressing 'enter' on a input type="text", how?

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :
(...)
<script type="text/javascript">
// Autocomplete suggestions
$(function () {
$("#autoCompInput").autocomplete({
source: "/Suggestions",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autoCompInput").val(ui.item.value);
$("form").submit();
}
}
});
});
// Provide search results
$(function () {
$("#autoCompSearch").click(function () {
var searchParameters = $("#autoCompInput").val();
var jsonData = JSON.stringify(searchParameters, null, 2);
window.location = "/Search?criteria=" + searchParameters;
});
});
</script>
(...)
<input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "#ViewBag.SearchInfo"/>
<a id= "autoCompSearch" href = "#" ><img src="#Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>
(...)
With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?
Thank you,
You should bind the keypress event to your input
$("#autoCompInput").bind("keypress", {}, keypressInBox);
function keypressInBox(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) { //Enter keycode
e.preventDefault();
$("yourFormId").submit();
}
};
With similar HTML:
<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />
This script (which uses the latest jQuery 1.7.2) should do it:
$('#mySubmit').click(function() {
alert('Submitted!');
return false;
});
$('#myTxt').on('keyup', function(e) {
if (e.keyCode === 13) {
$('#mySubmit').click();
}
});
Here's a working example.
To assign a keyup event in jquery
$("#autoCompInput").keyup(function(event) {
if (event.keyCode==13) {
alert('enter key');
}
});
I think there is a better and more standard solution to this type of problem.
you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):
<form id="idForJqueryOnly" action="/Search" method="GET">
<input type="text" name="criteria" value="someuserinput"/>
<button type="submit"><img src="...")" alt="Search" /></button>
</form>
This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this:
http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput
What happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form.
Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".
If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:
$("#idForJqueryOnly").submit(function(){
// here you can do stuff like serialize the form, or sanitize the input of tue user.
var data = $("#idForJqueryOnly").serialize();
$("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());
// if you return false, the form will not submit, say, for validation errors:
return customValidator.isFormValid("#idForJqueryOnly");
})

Clear an input field after submission using JavaScript

I am a JavaScript newbie. I have an input text field that I wish to clear after pressing the form submit button. How would I do that?
In your FORM element, you need to override the onsubmit event with a JavaScript function and return true.
<script type="text/javascript">
function onFormSubmit ()
{
document.myform.someInput.value = "";
return true; // allow form submission to continue
}
</script>
<form name="myform" method="post" action="someaction.php" onsubmit="return onFormSubmit()">
<!-- form elements -->
</form>
If a user presses the submitbutton on a form the data will be submitted to the script given in the action attribute of the form. This means that the user navigates away from the site. After a refresh (assuming that the action of the form is the same as the source) the input field will be empty (given that it was empty in the first place).
If you are submitting the data through javascript and are not reloading the page, make sure that you execute Nick's code after you've submitted the data.
Hope this is clear (although I doubt it, my English is quite bad sometimes)..
function testSubmit()
{
var x = document.forms["myForm"]["input1"];
var y = document.forms["myForm"]["input2"];
if (x.value === "")
{
alert('plz fill!!');
return false;
}
if(y.value === "")
{
alert('plz fill the!!');
return false;
}
return true;
}
function submitForm()
{
if (testSubmit())
{
document.forms["myForm"].submit(); //first submit
document.forms["myForm"].reset(); //and then reset the form values
}
}
First Name: <input type="text" name="input1"/>
<br/>
Last Name: <input type="text" name="input2"/>
<br/>
<input type="button" value="Submit" onclick="submitForm()"/>
</form>
After successfully submitting or updating form or password you can put empty value.
CurrentPasswordcontroller.state.confirmPassword = '';

Categories