Webpage to not delete form data after refresh - javascript

I have a form on a website that requires two text inputs and two radio inputs (one radio input currently not working because I can't figure out how to get them both to print instead of one overwriting the other). Upon hitting submit, the information posts underneath the form. I am trying to make it so that when the page is refreshed, the previously entered information will not disappear. Is there a simple way to achieve this?
I have heard about setting return onsubmit=false but have had no success so far.
<!--COMMENTING FORM-->
<div>
<div id="getdata">
<form id="form1" onsubmit="return confirmdata(false)">
<!--Input (text) asking for input of name-->
<p><b>Name:</b><br><input type="text" name="nameValue" value="" id="nameValue"></p>
<!--Input (radio) asking for type of output:
<p><b>Type of Event:</b></p>
<input type="radio" name="eventType" value="Food"> Food</br>
<input type="radio" name="eventType" value="Study"> Study</br>
<input type="radio" name="eventType" value="Event"> Event</br>
<input type="radio" name="eventType" value="Danger"> Danger</br>
TO DO FIX LATER -->
<!--Input (radio) asking for location: -->
<br>
<p><b>Location:</b></p>
<input type="radio" name="locationType" value="Library West"> Library West</br>
<input type="radio" name="locationType" value="Smathers Library"> Smathers Library</br>
<input type="radio" name="locationType" value="Marston Library"> Marston Library</br>
<input type="radio" name="locationType" value="Turlington Plaza"> Turlington Plaza</br>
<!--Input (text) asking for input of description-->
<br>
<p><b>Description:</b><br><input type="text" style="width:200px; height:50px;" name="desValue" value="" id="desValue"></p>
<!--submit button-->
<p><input type="submit" name="myButton" value="Submit!">
<input type="reset" value="Reset Form"></p>
</form>
</div>
<div id="confirm">
</div>
</div>
</body>
<!--COMMENTING FORM END-->
<!-- COMMENTING FORM SCRIPT -->
<script type="text/javascript">
var txt1 = document.getElementById('nameValue');
var types = document.getElementsByName('eventType');
var types = document.getElementsByName('locationType');
var txt2 = document.getElementById('desValue');
document.getElementById("form1").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var nameValue = txt1.value;
var selected = 'none';
var desValue = txt2.value;
for (var i = 0; i < types.length; i++) {
if (types[i].checked === true) {
selected = types[i].value;
}
}
if (selected !== 'none' && nameValue !== '') {
//document.getElementById("confirm").innerHTML += '<p><b>Name:</b> ' + nameValue + '</p>';
//document.getElementById("confirm").innerHTML += '<p><b>Event Type:</b> ' + selected + '</p>';
//document.getElementById("confirm").innerHTML += '<p><b>Additional Details: </b>' + desValue + '</p>';
document.getElementById("confirm").innerHTML += '<p> User <b>' + nameValue + '</b> has an event located at <b>' + selected + '</b>. <br><b> Additional details: </b>' + desValue + '</p>';
document.getElementById("confirm").innerHTML += '<p><b>--------------------</b> ' + '</p>';
} else {
alert('Invalid input');
}
return false;
}
</script>
<!-- COMMENTING FORM SCRIPT END -->
</form>
</div>
</div>

either store the information on local storage or intercept the onsubmit event (edit: as a result, form submission triggers js function, but not page reload).
<form onsubmit="return myFunction()">
<!-- put form elements here -->
</form>
<script>
function myFunction(){
//do stuff here
return false
}
</script>
You could always use ajax for form submission without reloading.

you can store the data in browser local storage and on page load take the data from local storage and place in required fields. Always clear the locally stored data once form submitted successfully. Be sure not to store personal data there are high chances of data leak if it is a shared PC.

Related

How do I create a link on form submission in another page and get the contents of the text submitted on the linked page?

I've been recently trying to create a query (Ask a question) page in HTML. I have a form that uses the get method and I know that is one way to send data across pages and use it with JavaScript. Is it possible to create a link with the form's data inside the linked page?
// Get the contents of //
var inputBox = document.getElementById('QueryTitle');
// Use the onkeyup to get the values of user input //
inputBox.onkeyup = function(){
// MAKE NO BAD TAGS APPEAR IN QUESTIONS //
const goodTags = ['<b>' , '</b>' , '<i>' , '</i>' , '<br>' , '</br>']
var tag = inputBox.value.match(/<.+>/)
if (tag && !goodTags.includes(tag[0])) { inputBox.value = inputBox.value.replace(tag[0], '') };
document.getElementById('QueryTitleOutput').innerHTML = inputBox.value;
}
// Get the questions contents, normally in the textarea of the page //
var textarea = document.getElementById('QueryInput');
// Use the onkeyup to get the values of user input //
textarea.onkeyup = function(){
// MAKE NO BAD TAGS APPEAR IN QUESTIONS //
const goodTags = ['<b>' , '</b>' , '<i>' , '</i>' , '<br>' , '</br>']
var tag = textarea.value.match(/<.+>/)
if (tag && !goodTags.includes(tag[0])) { textarea.value = textarea.value.replace(tag[0], '') };
document.getElementById('QueryOutputFrame').innerHTML = textarea.value;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This the form that uses the get method to show data in the URL -->
<form action="Get Text As A Link.html" method="get">
<input type="text" id="QueryTitle" name="QueryTitle" placeholder="Ask Something">
<br>
<br>
<!-- this is the main query textarea !-->
<textarea id="QueryInput" name="QueryInput" style="width: 780px; height: 200px;">
</textarea>
<!-- Widgets for the textarea !-->
<br>
<div id="QueryTitleOutput">
</div>
<br>
<br>
<div id="QueryOutputFrame" style="width: 90%; height: 10em;">
</div>
</center>
<br>
<br>
<br>
<br>
<br>
<center>
<input type="submit" id="final" value="Submit Question" class="unhidden" class="btn btn-submit" onclick="location.href = 'Get Text As A Link.html';" onSubmit="">
</center>
</form>

Dynamically Added Input Value disappear on next addition

I am creating a webpage with ability to add input box dynamically , everything works fine. But whenever I add a new input box the value from all the input box added above that field get cleared automatically.
Here is the html which is generated on addition of the element
<div class="main_text_area" id="got_id_from_server">
<p>Add Delay For :</p>
<div class="remove_bg button btn" name="some_id_from_server"></div>
<p>
<div contenteditable class="text_im" placeholder="Enter Delay" id="some_id_from_server" onchange="post_delay(this)"></div>
</p>
<p>
<input class="text_im" placeholder="Select" type="text" id="some_id_from_server" list="some_id_from_server" onchange="post_delay(this)">
<datalist id="some_id_from_server">
<option value="Minutes"></option>
<option value="Hours"></option>
<option value="Days"></option>
</datalist>
</p>
</div>
This behavior occurs because adding new elements to your Dom will cause the Website to kind of render the view again & again so the (in this case) not stored values of a "input field given no ID attribute" you have inputted into your input-element will just reset.
So have a look at this two code snippets:
var count = 0;
function createInput(event) {
count++;
document.body.innerHTML += "<input value='Input #"+ count + "' / >"
event.preventDefault();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="createInput()">Create Input</button>
Edit: Using jQuery will be the better solution so have a look at this code (To prevent the reset of the input fields you have to use "append()". Try it on your own!:
var count = 0;
$(function() {
$("#createInput").click(function(event) {
count++;
$('form').append('<input type="text" value="Input #' + count + '" />');
event.preventDefault();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" name="myForm" accept-charset="utf-8">
<button id="createInput">Create Input</button>
</form>

Javascript Splitting URL twice

Hi I've found a Javascript function I'm quite fond of which send the user to a page which depends on what they've entered into the text fields and want to implement into my new website. Only issue is this code only places one input fields text and I want 2!
Being quite new at this I could do with a little help understanding how to achieve this.
http://www.example.com/input1/*input2*.php
is what I want it to output.
Here is the code I' working with.
<script type="text/javascript">
function getURL(val){
base = 'http://www.example.com/';
exten = '.php';
var split = val.split(" ")
valup = split[0].toUpperCase();
valup2 = valup.replace(/ /, "");
location = base + valup2 + exten;
return false;}
</script>
<form id="form1" name="form1" method="post" action="" onsubmit="return getURL(this.url.value)">
<label>
<input type="text" id="suggest1" maxlength=4 size="4" style="color: #fff;" name="url" />
</label>
<label>
<input type="submit" class="button" name="Submit" value="GO" />
</label>
</form>
You would need to get the value of both input, and it's best done before the submit button.
var formElem = document.getElementById('form1');
var input1 = document.getElementById('suggest1');
var input2 = document.getElementById('suggest2');
formElem.onsubmit = function() {
location = 'http://example.com/' + input1.value + '/' + input2.value + '.php';
};

How to display user entered information using JavaScript?

I have a form code tat will allow the user to enter information. I'm trying to display certain parts of that information onto a new page using javascript. Basically, the page is meant to have the user enter information and have the name, date, time, and email display in a new tab or page. But I can't seem to have it displayed. Can anyone help me?
<html lang="en" >
<head>
<title>Shy Music Booking Confirmation</title>
<link rel="stylesheet" href="music.css" type="text/css" />
<body>
<div id="wrapper">
<div id="form">
<header><h1>Shy Music Private Lessons</h1></header>
<script type="text/javascript">
function addtext()
{
var userName = document.booking.userName.value;
var userDate = document.booking.userDate.value;
var userTime = document.booking.userTime.value;
var userEmail = document.booking.userEmail.value;
document.writeln("Thank you! You have just entered the following:");
document.writeln("<pre>");
document.writeln("Name: " + userName);
document.writeln("Date: " + userDate);
document.writeln("Time: " + userTime);
}
</script>
</head>
<hr>
<form name="booking">
<h1>Book a Slot Here!</h1>
<label for="userName">Name: <br><input type = "text" name = "userName"></label> <br><br>
<label for="userEmail">E-mail Address: <br><input type = "email" name = "userEmail"></label><br><br>
<label for="userPhone">Phone Number: <br><input type = "tel" name = "userPhone"> </label><br><br>
<label for="userInstrument">Instrument:
<select>
<option>Guitar</option>
<option>Drums</option>
<option>Piano</option>
</select>
</label>
<br><br>
<label for="userTime">
Preffered Time:
<select>
<option>9:00</option>
<option>9:30</option>
<option>10:00</option>
<option>10:30</option>
<option>11:00</option>
<option>11:30</option>
<option>12:00</option>
<option>12:30</option>
<option>1:00</option>
<option>1:30</option>
<option>2:00</option>
<option>2:30</option>
<option>3:00</option>
<option>3:30</option>
<option>4:00</option>
<option>4:30</option>
</select>
</label>
<select>
<option>AM</option>
<option>PM</option>
</select>
<br>
<br>
<label for="userDate">Date: <br><input type = "date" name = "userDate"></label><br><br>
<input type="submit" value="Submit" >
<form action="#">
<input type="button" value = "Back" onclick="javascript:history.go(-1)" />
</form>
</form>
</div>
</div>
</body>
</html>
I was working on this for a lot of time, but it wasn't working. But, I tried it recently and it worked! I hope this was helpful.
<html>
<head>
<h1> Welcome</h1>
</head>
<body>
<p> Enter name: </p>
<input id="name" name="name"class="Name" type="text" placeholder="Enter Full name" required>`
<input type="Submit" onclick="submitted()"> <br> <br>
<a id="new" href="www.google.com"> </a>
<script>
function submitted()
{
var a = document.getElementById("name").value;
if (a=="")
{
document.getElementById("new").innerHTML="";
alert("Please Enter a valid name!");
}
else if (a==" ") {
document.getElementById("new").innerHTML=""
alert("Please Enter a valid name!");
}
else
{
document.getElementById("new").innerHTML="Thank you, " + a + ". " + "Click here to continue.";
}
}
</script>
</body>
</html>
Or, slightly tightened, as a working snippet:
function submitted()
{
var a = document.getElementById("name").value.trim();
document.getElementById("new").innerHTML=
a===""?"":"Thank you, " + a + ". " + "Click here to continue.";
}
<p> Enter name: </p>
<input id="name" name="name"class="Name" type="text" placeholder="Enter Full name" required>
<input type="Submit" onclick="submitted()"> <br> <br>
<a id="new" href="www.google.com"> </a>
The problem with your code was that you were using document.write in a dynamic setting. When using it in this context, document.write will erase the content of the current document and replace it with the text specified by its parameters. For this reason, document.write is commonly regarded as poor way to represent and insert text/data. And it typically affects the plethora of beginners learning JavaScript. Here are some alternatives you should keep in mind:
element.innerHTML: Like I said in the comments. Use .innerHTML to insert the formatted HTML into document through an element on the page. It doesn't necessarily have to be specified by an id attribute. It can very well be given by any other form of element obtainment.
node.appendChild: This method is more DOM-friendly than the first. It allows you to insert a node at the end of the body of the element specified by node. For example:
var form = document.myForm,
new_element = document.createElement('input');
new_element.type = "button";
new_element.value = "Submit";
form.appendChild( new_element );
I hope this helped.

Radio button with an "other" text box not inputting value properly using javascript

I'm creating a form using html form controls and javascript to help streamline some processes at work. I've temporarily put the form online here.
In one section of the form, I have a text box associated with a radio button. The other radio buttons in the section display their values properly when the "Display" button is hit at the bottom of the page, but the radio button with the text box does not. It seems that I'm not correctly assigning the value of the text box to the value of the radio button. What am I doing wrong?
Here's the javascript:
<script LANGUAGE="JavaScript" type="text/javascript">
function display() {
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
var radio_paymenttype_val = document.form2.paymenttype[i].value;
}
}
for (var i=0; i < document.form2.contracts.length; i++)
{
if (document.form2.contracts[i].checked)
{
var radio_contracts_val = document.form2.contracts[i].value;
}
}
DispWin = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600')
message = "<h2>Royalty Advance Payment Letter</h2>";
message += "<hr />";
message += "<span STYLE=\'font-family: Garamond\'>";
message += "<p>" + document.form2.agentfirstname.value + " " + document.form2.agentlastname.value + "<br />";
message += document.form2.agencyname.value + "<br />";
message += document.form2.agentaddress1.value + "<br />";
message += document.form2.agentaddress2.value + "<br />";
message += document.form2.agentcity.value + ", " + document.form2.agentstate.value + " " + document.form2.agentzip.value + "<br />";
message += document.form2.agentcountry.value + "<br />";
message += "</p>";
message += "<p>Dear " + document.form2.agentfirstname.value + ",</p>";
message += "<p>Please find enclosed a check in the amount of $";
message += document.form2.paymentamount.value + " representing the amount due upon ";
message += radio_paymenttype_val + " ";
message += document.form2.authorfirstname.value + " ";
message += document.form2.authorlastname.value + "'s <em>";
message += document.form2.booktitle.value + "</em>.";
message += radio_contracts_val + "</p>";
message += "<p>Regards,<br /><br /><br /><br />My Name<br />Associate Editor</p>";
message += "</span>";
DispWin.document.write(message);
}
</script>
And here's the HTML for that section:
<div class="required">
<fieldset>
<legend>Payment Type:</legend>
<label for="payment_sig" class="labelRadio"><input type="radio" name="paymenttype" id="payment_sig" class="inputRadio" value="signature for" /> Signature</label>
<label for="payment_danda" class="labelRadio"><input type="radio" name="paymenttype" id="payment_danda" class="inputRadio" value="delivery and acceptance of" /> Delivery & Acceptance</label>
<label for="payment_pub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pub" class="inputRadio" value="publication of" /> Publication</label>
<label for="payment_pbpub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pbpub" class="inputRadio" value="paperback publication of" /> Paperback Publication</label>
<label for="payment_otherlabel" class="labelRadio"><input type="radio" name="paymenttype" id="payment_otherlabel" class="inputRadio" onclick="this.form.payment_other.focus()" onfocus="this.form.payment_other.focus()" value="" checked="checked" /> Other:</label>
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" />
<small>Remember, this text will be in the middle of a sentence. This text should always end in "of" or "for."</small>
</fieldset>
</div>
Your first for loop goes through and finds the value of the correct radio selected, but in the case of "other" you're not going to have a value assigned. You need to determine when other is selected, then assign radio_paymenttype_val the value of the text box instead. Something to the effect of:
for (var i=0; i < document.form2.paymenttype.length; i++)
{
if (document.form2.paymenttype[i].checked)
{
// assuming "other" is the only case where this radio's value property would be empty.
var radio_paymenttype_val = (document.form2.paymenttype[i].value != ''
? document.form2.paymenttype[i].value
: document.form2.payment_other.value);
}
}
Update
So excuse the delay (took your form field and ran with it). This is (I believe) what you're looking for. Some things to note:
I don't do any form validation. This is something you probably want to tinker with, and can be pretty simple. In the .click() event, just check something like the following (or you can get more elaborate):
if($('#agentfirstname').val()==''){
alert('Missing First Name');
return;
}
Also, I use something fairly new to jQuery, templates. This makes it easier than var+='html html'+var+'html'; (as you can witness in the <script> tag with the ID 'FormTemplate`).
Finally, I tested this on FF4, Chrome4 and IE8 and it should work, but let me know if it doesn't on whatever environment you use.
Anyways, here's the code, hope this helps!
Place inside <head> element of your document
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<Script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<script type="text/javascript">
$(function(){
// bind to the "display" button ('.' means this is a class name reference)
$('.inputSubmit').click(function(e){
// build up the template values
var tmplData = [{
agentFirstName: $('#agentfirstname').val(),
agentLastName: $('#agentlastname').val(),
agencyName: $('#agencyname').val(),
agentAddr1: $('#agentaddress1').val(),
agentAddr2: $('#agentaddress2').val(),
agentCity: $('#agentcity').val(),
agentState: $('#agentstate').val(),
agentZip: $('#agentzip').val(),
paymentAmount: '$'+$('#paymentamount').val(),
paymentType: $('input[name="paymenttype"]:checked').val() != '' ? $('input[name="paymenttype"]:checked').val() : $('#payment_other').val(),
authorFirstName: $('#authorfirstname').val(),
authorLastName: $('#authorlastname').val(),
bookTitle: $('#booktitle').val(),
contracts: $('input[name="contracts"]:checked').val()
}];
// create the template
var template = $('#FormTemplate').template('letter');
// Create a fake div we can push the template to and pass off to popup
var tmplDiv = document.createElement('div');
$(tmplDiv).attr('id','TemplateDiv').css('display','none');
// Write the template and push it off
$.tmpl('letter', tmplData).appendTo(tmplDiv);
// create the window and populate it with the template
var hWindow = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600');
hWindow.document.write(tmplDiv.innerHTML);
// stop any further action
e.preventDefault();
});
});
</script>
Place inside <body> element of your document:
<script id="FormTemplate" type="text/x-jquery-tmpl">
<html>
<head>
<title>Letter</title>
</head>
<body>
<h2>Royalty Advance Payment Letter</h2>
<hr />
<span type="font-family:Garamond;">
<p>
${agentFirstName} ${agentLastName}<br />
${agencyName}<br />
${agentAddr1}<br />
${agentAddr2}<br />
${agentCity}, ${agentState} ${agentZip}<br />
</p>
<p>
Dear ${agentFirstName},
</p>
<p>
Please find enclosed a check in the amount of ${paymentAmount} representing the amount due upon ${paymentType}
${authorFirstName} ${authorLastName}'s <em>${bookTitle}</em>.
${contracts}
</p>
<p>
Regards,<br />
<br />
<br />
<br />
Margaret Maloney<br />
Associate Editor
</p>
</span>
</body>
</html>
</script>
Could you simply set a onblur() for the payment_other to set the radio option's value?
<input type="text" name="payment_other" id="payment_other" class="inputText" value="" onblur="document.getElementById('payment_otherlabel').value=this.value;" />
Then if it is ever set, it will automatically copy the value into the radio option. Then when your Display() function is called, I would think the value would be set.
(Realized I missed the semi-colon at the end of the onblur="" statement.)
Have you tried this yet?

Categories

Resources