Can I reload current page without losing any form data? I used..
window.location = window.location.href;
and
window.location.reload(true);
But these two things can't get earlier form datas for me. What is wrong ? When refresh browser manually, it is fine (I don't lose any form data). Please guide me how to figure it out.
Here is my full code...
<div class="form-actions">
<form>
<table cellpadding = "5" cellspacing ="10">
<tr class="control-group">
<td style="width: 100px;">
<div>Name: <font color="red">(*)</font></div>
</td>
<td>
<input type="text" id="inputName" placeholder="Name" required>
</td>
</tr>
<tr class="control-group">
<td>
<div>Email: <font color="red">(*)</font></div>
</td>
<td>
<input class="span3" placeholder="user#gmail.com" id= "inputEmail" type="email" required>
</td>
</tr>
<tr class="control-group">
<td>
<div>Phone: </div>
</td>
<td>
<input type="text" id="inputPhone" placeholder="phone number">
</td>
</tr>
<tr class="control-group">
<td>
<div>Subject: <font color="red">(*)</font></div>
</td>
<td>
<input type="text" id="inputSubject" placeholder="Subject" required>
</td>
</tr>
<tr class="control-group">
<td colspan ="2">
<div>
<div>Detail: </div>
<div class="controls">
<textarea id="inputDetail"></textarea>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<label style="font-weight: bold;" class="checkbox"> <input id="confirmCheck" value="" type="checkbox">
I Agree to the Personal information handling policy
</label>
</div>
<div id = "alert_placeholder"></div>
<div class="acceptment">
[Personal information handling policy]<br> <br>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<div align="center">
<button id="btnConfirm" class="btn btn-primary">Confirm</button>
<input type="reset" style="width: 65px; height: 27px;" id="btnReset" class="btn">
</div>
</td>
</tr>
</table>
</form>
</div>
And at my JS file..
function bind() {
$('#btnConfirm').click(function(e) {
if ($('#confirmCheck').is(":checked")) {
getConfirmationForSendFAQ();
}
else {
e.preventDefault();
showalert("You should accept \"Personal Information Policy\" !", "alert-error");
}
});};function getConfirmationForSendFAQ() {
var name = $('#inputName').val();
var email = $('#inputEmail').val();
var phone = $('#inputPhone').val();
var subject = $('#inputSubject').val();
var detail = $('#inputDetail').val();
$('.form-actions').empty();
html = [];
html.push("<table cellpadding ='8' class = 'submitInfo'");
html.push("<tr>");
html.push("<td class = 'title'>Name:</div>");
html.push("<td class = 'value'>"+ name +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td class = 'title'>Email Address:</div>");
html.push("<td class = 'value'>"+ email +"</td>");
html.push("</tr>");
if (phone.trim().length > 0) {
html.push("<tr>");
html.push("<td class = 'title'>Phone No:</div>");
html.push("<td class = 'value'>"+ phone +"</td>");
html.push("</tr>");
}
html.push("<tr>");
html.push("<td class = 'title'>Subject:</div>");
html.push("<td class = 'value'>"+ subject +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td class = 'title'>Detail Info:</div>");
html.push("<td class = 'value'>"+ detail +"</td>");
html.push("</tr>");
html.push("<tr>");
html.push("<td colspan='2'><div align = 'center'>");
html.push("<button id='btnSend' class='btn btn-primary' style='width: 65px;'>Send</button>");
html.push("<button id='btnReturn' class='btn btn-inverse' style='width: 65px; height: 27px; margin-left: 5px;'>Return</button>");
html.push("</div></td></tr>");
html.push("</table>");
$('.form-actions').append(html.join(''));
$('#btnReturn').click(function(e) {
// HERE I WANT TO KNOW HOW TO DO.....
});
$('#btnSend').click(function(e) {
alert("Doom");
});}
You can use various local storage mechanisms to store this data in the browser such as the Web Storage API, IndexedDB and WebSQL (deprecated) (and UserData with IE).
The simplest and most widely supported is Web Storage where you have persistent storage (localStorage) or session based (sessionStorage) which is in memory until you close the browser. Both share the same API.
You can for example (simplified) do something like this when the page is about to reload:
window.onbeforeunload = function() {
localStorage.setItem("name", $('#inputName').val());
localStorage.setItem("email", $('#inputEmail').val());
localStorage.setItem("phone", $('#inputPhone').val());
localStorage.setItem("subject", $('#inputSubject').val());
localStorage.setItem("detail", $('#inputDetail').val());
// ...
}
Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem("name");
if (name !== null) $('#inputName').val("name");
// ...
}
getItem returns null if the data does not exist.
Replace "localStorage" with "sessionStorage" in the code above if you want to store data only temporary.
I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.
<script>
// Run on page load
window.onload = function() {
// If sessionStorage is storing default values (ex. name), exit the function and do not restore data
if (sessionStorage.getItem('name') == "name") {
return;
}
// If values are not blank, restore them to the fields
var name = sessionStorage.getItem('name');
if (name !== null) $('#inputName').val(name);
var email = sessionStorage.getItem('email');
if (email !== null) $('#inputEmail').val(email);
var subject= sessionStorage.getItem('subject');
if (subject!== null) $('#inputSubject').val(subject);
var message= sessionStorage.getItem('message');
if (message!== null) $('#inputMessage').val(message);
}
// Before refreshing the page, save the form data to sessionStorage
window.onbeforeunload = function() {
sessionStorage.setItem("name", $('#inputName').val());
sessionStorage.setItem("email", $('#inputEmail').val());
sessionStorage.setItem("subject", $('#inputSubject').val());
sessionStorage.setItem("message", $('#inputMessage').val());
}
</script>
Find this on GitHub. Specially created for it.
https://gist.github.com/zaus/4717416
This answer was extremely helpful to me, and saves the trouble of going through each field manually:
Using jQuery to store the state of a complicated form
window.location.reload() // without passing true as argument
works for me.
As some answers mention, localStorage is a good option and you can certainly do it yourself, but if you're looking for a polished option, there is already a project on GitHub that does this called garlic.js.
I usually submit automatically my own form to the server and reload the page with filled arguments. Replace the placeholder arguments with the params your server received.
Agree with HTML5 LocaStorage.
This is example code
You have to submit data and reload page (server side render form with data), just reloading will not preserve data. It is just your browser might be caching form data on manual refresh (not same across browsers).
You can use localStorage ( http://www.w3schools.com/html/html5_webstorage.asp ) to save values before refreshing the page.
You can use a library I wrote, FormPersistence.js which handles form (de)serialization by saving values to local/session storage. This approach is similar to that linked in another answer but it does not require jQuery and does not save plaintext passwords to web storage.
let myForm = document.getElementById('my-form')
FormPersistence.persist(myForm, true)
The optional second parameter of each FormPersistence function defines whether to use local storage (false) or session storage (true). In your case, session storage is likely more appropriate.
The form data by default will be cleared from storage upon submission, unless you pass false as the third parameter. If you have special value handling functions (such as inserting an element) then you can pass those as the fourth parameter. See the repository for complete documentation.
A simple and generic (no jquery) solution for all input (type text) fields unsing the local storage.
function save_data(){
let fields = document.querySelectorAll("input[type='text']")
let saved_fields = []
fields.forEach(x => {
saved_fields.push({
key: x.id,
value: x.value
})
})
localStorage.setItem("saved_data", JSON.stringify(saved_fields))
}
function show_saved_data(){
JSON.parse(localStorage.getItem("saved_data")).forEach(x => {
document.getElementById(x.key).value = x.value
})
}
if you want to include "select/checkboxes" fields etc. you would have to add some if else logic in the for loop and change the query....
Use $_POST itself:
<?php
isset($_POST['value']) ? $value= $_POST['value'] : $value= NULL;
echo '<form method="POST">';
echo '<input type="text" name="value" value="'.$value.'"/>';
echo '<input type="submit" name="submit" value="Submit"/>';
echo '</form>';
?>
Register an event listener for keyup event:
document.getElementById("input").addEventListener("keyup", function(e){
var someVarName = input.value;
sessionStorage.setItem("someVarKey", someVarName);
input.value = sessionStorage.getItem("someVarKey");
});
Related
I have a semi-simple problem: I want my landing page to ask the user to enter their name into a input box. Once they have entered their name, the page should switch to another page that says Hello [username]... and present the content as well.
Here is my first html file (name.html) asking for the first name:
<body>
<form id="myForm" name="myForm">
<table class="input">
<tr>
<label>
<h1>Enter your firstname:</h1>
</label>
<td>
<input type="text" id="firstName" class="form-control" autofocus>
</td>
<td>
<input type="button" value="Submit" onclick="menuPage();" class="btn btn-primary btn-lg">
</td>
</tr>
<tr>
<td id="username">
</td>
</tr>
</table>
</form>
<script src="name.js"></script>
<script src="ie10-viewport-bug-workaround.js"></script>
</body>
Here is the accompanying JavaScript file (name.js):
function menuPage() {
var firstName = document.getElementById("firstName").value;
if (firstName.trim() && firstName != "") {
document.getElementById("username").innerHTML = firstName;
window.location.replace("menu.html")
} else {
alert("Please put in your first name.")
}
}
Now, here is the new html page (menu.html) that appears once the user enters their name:
<div class="jumbotron">
<div class="container">
<div>
<h1 class="display-3">Hello!</h1>
<h1 id="username"></h1>
<p>This is your weekly meal to cook! Enjoy!!</p>
</p>
<h2 class="quote"><span class="words"></span></h2>
<button class="btn btn-success btn-sm" value="Press Me to get your Weekly Menu">Change Meal</button>
</div>
</div>
</div>
<script src="name.js"></script>
<script src="menu.js"></script>
Lastly, the accompanying JS file (menu.js):
$(document).ready(function() {
weeklyMenu();
function weeklyMenu() {
var menu = ["meatloaf", "albondigas", "enchiladas", "lasgna", "chicken, mash potatoes, mac & cheese", "turkey burgers, sweet potatoes fries", "stuffed peppers", "french soup"];
var randomMenu = menu[Math.floor(Math.random() * menu.length)];
var splitMenu = randomMenu.split();
$('.words').text(splitMenu[0]);
}
$("button").on("click", function() {
weeklyMenu();
});
});
I modified your menu.html just a bit. You need to make sure that you save the input name in a storage (cookies, local storage or session storage). Here's how it works:
menu.html
<div class="container">
<div>
<h1 class="display-3">Hello, <span id="username"></span>!</h1>
<p>This is your weekly meal to cook! Enjoy!!</p>
</p>
<h2 class="quote"><span class="words"></span></h2>
<button class="btn btn-success btn-sm" value="Press Me to get your Weekly Menu">Change Meal</button>
</div>
name.js
function menuPage() {
var firstName = document.getElementById("firstName").value;
if (firstName.trim() && firstName != "") {
localStorage.setItem("storageName",firstName);
document.getElementById("username").innerHTML = firstName;
window.location.replace("menu.html")
} else {
alert("Please put in your first name.")
}
}
menu.js
$(document).ready(function() {
window.onload = $('#username').html(localStorage.getItem("storageName"));
weeklyMenu();
function weeklyMenu() {
var menu = ["meatloaf", "albondigas", "enchiladas", "lasgna", "chicken, mash potatoes, mac & cheese", "turkey burgers, sweet potatoes fries", "stuffed peppers", "french soup"];
var randomMenu = menu[Math.floor(Math.random() * menu.length)];
var splitMenu = randomMenu.split();
$('.words').text(splitMenu[0]);
}
$("button").on("click", function() {
weeklyMenu();
});
});
Hope this helps!
You have to convey the information from the first page over to the second page somehow. There are at least three ways to do that (one of which is a bad idea):
Using web storage, in this case probably sessionStorage if it's session-specific information. Your first page stores it:
sessionStorage.setItem("name", theUserName);
and your next page gets it and uses it
var name = sessionStorage.getItem("name");
if (name) {
$("#hello").show().find(".name").text(name);
}
There I've assumed an element with the id hello which will by default have display: none, with a descendant element with the class name which we fill in with the name. The code above shows the default-hidden element if there's a name and fills it in.
Pass it in the query string. After getting the name, when switching to the next page, add "?" + encodeURIComponent(theUserName) to the URL. Then use location.search to get the name and use it in much the way you do in #1 above.
Store it in a cookie, which you sould use . I mention this only to say: While it's possible to do it like this, don't. Cookies aren't meant for client-side-only information.
How to conditionally enable or disable to editable field (edit/read only)? I used session role from database to make condition on the text field. However, I don't know how to proceed it...
<?php
include('session.php');
?>
<tr class="row1">
<td width="30%"><div align="left">Customer name1</div></td>
<td width="100%">
<div align="left">
<input type="text" name="CMCNA1" id="CMCNA1" style="width:100%;" pattern="[A-Za-z]+" title="Please insert alphabetical only" maxlength="35"/>
</div>
</td>
I know it's an old post, but just in case, for those who have this needs.
Base on the code of Narayan, maybe by doing this (with jquery):
<script type="text/javascript" >
function makerCheckerField()
{
var role= <?php echo $_SESSION['login_user_role']; ?>;
var maker='Maker';
if (role === maker){
$('#CMCNA1').attr('readonly', 'readonly');
} else {
$('#CMCNA1').removeAttr('readonly');
}
}
</script>
If I am not wrong the readonly property works like this :
readonly = "readonly" or "" (empty string) or empty
Specifies that element represents a control whose value is not meant to be edited.
Maybe you will have to manage correctly the differents states of roles (what happens if you came back to the default state etc...).
You can also play with
.setAttribute, .getAttribute and .removeAttribute
I don't know if this is what you was looking for.
Try this -->>
<script type="text/javascript" >
function makerCheckerField()
{
var role= <?php echo $_SESSION['login_user_role']; ?>;
var maker="Maker";
if (role === maker) // equal value and equal type
{
$("#CMCNA2").attr("readonly", true);
} else {$("#CMCNA2").attr("readonly", false);}
}
</script>
you can add attribut readonly="true" to make the input readonly/not editable:
<input type="text" name="CMCNA1" id="CMCNA1" style="width:100%;" pattern="[A-Za-z]+" title="Please insert alphabetical only" maxlength="35" readonly="true" />
we have list employees with email id using below code
<tbody>
<?php
$sqlquery = mysql_query("select * FROM employee");
while($row=mysql_fetch_object($sqlquery)){
?>
<tr class="gradeA">
<td><input type="checkbox" name="eid" value="<?php echo $row->emailid;?>" onclick="send_email_form_test()"><?php echo $row->name;?></td>
</tr>
<?php }?>
</tbody>
when checkbox is clicked following function call,
function send_email_form_test(){
var selected = new Array();
$("input:checkbox[name=eid]:checked").each(function() {
if($(this).val() !=""){
selected.push($(this).val());
}
});
alert(selected.join(','));
var final_email = selected.join(',');
document.getElementById("to").value =final_email;
}
after click the checkbox,email ids are appears in "to" textarea field .when i will go to second page of the employee list, i cant able to get "to" textarea field,it will empty on the second page
<div>
<label for="required">TO</label>
<textarea name="to" cols="5" rows="10"></textarea>
</div>
<div>
<label for="email">Subject</label>
<input type="text" size="80" id="subject" name="subject" >
<input type="submit" name="submit" value="submit">
</div>
how to add and remove the email ids with comma separated,when i click the checkbox.I have issue on when i will go on next page of the pagination
You can add 'this' parameter to the Javascript function as onclick="send_email_form_test(this)"> then you will get the clicked checkbox object. Then you will be able to retrieve the value of the clicked check box
I did not test it, but I think this is how you could collect emails from all pages
<?php
//...
echo '<script>window.tablePage = ', $paginator->currentPage, ';</script>';
?>
<script type="application/javascript">
//...
pageSelected = selected.join(',');
//get emails selected on other pages
allSelected = JSON.parse(localStorage.getItem('emails'));
//add currently selected emails
allSelected[tablePage] = pageSelected;
localStorage.setItem('emails', JSON.stringify(allSelected));
//output emails from all pages
document.getElementById("to").value = allSelected.join(',');
//...
</script>
(JSON library is here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js )
I'm looking for a way to send some hidden form-data to a Django-server, which works out fine as long is a keep the javascript and the html(template) in the same file, but now i'm trying to separate them.
Probably really simple, but i guess all i have to do is get(set?) the 'name' of the window/html-and access it from the javascript module?
HTML:
<html>
<head>
<script src="/media/postIt.js"></script>
</head>
<body>
<form action="" method="post" id="postForm">{% csrf_token %}
<input type="hidden" id="scoreField1" name="score1"></input>
<input type="hidden" id="scoreFieldSet1" name="score1Set"></input>
<input type="hidden" id="scoreField2" name="score2"></input>
<input type="hidden" id="scoreFieldSet2" name="score2Set"></input>
<input type="hidden" id="scoreField3" name="score3"></input>
<input type="hidden" id="scoreFieldSet3" name="score3Set"></input>
</form>
<table>
<tr>
<td id="bg1" onclick="postIt('score1')">
Ones
</td>
<td id="bg1_1">
</td>
</tr>
<tr>
<td id="bg2" onclick="postIt('score2')">
Twos
</td>
<td id="bg2_1">
</td>
</tr>
</table>
Javascript:
function postIt(x){
var pointArray = [d1,d2,d3,d4,d5];
var totVal = d1+d2+d3+d4+d5;
pointArray.sort(function(a,b){return a-b});
alert(pointArray);
alert("total value: " + totVal);
if(x == "score2"){
if("{{ res.score2Set }}" == 0){
var form = document.getElementById('postForm');
document.getElementById('scoreField1').value = score1;
document.getElementById('scoreFieldSet1').value = score1Set;
document.getElementById('scoreField2').value = score;
document.getElementById('scoreFieldSet2').value = 1;
document.getElementById('scoreField3').value = score3;
document.getElementById('scoreFieldSet3').value = score3Set;
form.submit();
}
}
Edit:
Clarifying:
I can't reach the elements in the html 'document' by just calling document.getElement... since they now are in different documents (physically..). I guess i'll have to assign a name/variable to the document, somehow.
And the call it like:
nameOfDocument.getElement..
and so on..
I would guess that the line
if("{{ res.score2Set }}" == 0)
is the problem - an included Javascript file will not go through the Django template loader, so you cannot place variables inside it. This conditional will always evaluate to false.
You need to set the variable in the template file in some manner and then retrieve it in the Javascript. The best way to do this would be probably be to add res.score2Set as an additional argument to the postIt() function, and then do:
<td id="bg1" onclick="postIt('score2', '{{ res.score2Set }}')">
Although obviously I don't really know what your application does so this might not be applicable. If res.score2Set is used elsewhere in the HTML it might be better to load it in from the DOM in the Javascript.
Your assumption about javascript is wrong.Wherever you write JS codes (inline,within file,external file) all JS codes will have access to the DOM.So, the problem is you have not loaded your JS file properly.
I'm trying to get the text from a text box.
I have 2 input text boxes that are not in a form, and I'm trying to retrieve the value and store it in a variable.
This code returns undefined in the alert box that pops up.
<script>
var userPass = document.getElementById('pass');
var userName = document.getElementById('fName');
function submit(){
alert(userPass.value);
}
</script>
When I run it with userName.value as a parameter in the alert function, it will work and display what ever you type in the box.
Here is the html:
<table id="login">
<tr>
<td><label>User Name</label></td>
</tr>
<tr>
<td colspan="2"><input class="textBox" id="fName" type="text" maxlength="30" required/></td>
</tr>
<tr>
<td id="pass"><label>Password</label></td>
<tr>
<td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>
<tr>
<td><input type="button" class="loginButtons" value="Login" onclick="submit();"/>   
<input type="button" class="loginButtons" value="Cancel"/></td>
</table>
You will notice you have no value attr in the input tags.
Also, although not shown, make sure the Javascript is run after the html is in place.
<script>
function submit(){
var userPass = document.getElementById('pass');
var userName = document.getElementById('user');
alert(user.value);
alert(pass.value);
}
</script>
<input type="text" id="user" />
<input type="text" id="pass" />
<button onclick="submit();" href="javascript:;">Submit</button>
// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention
function submit()
{
var userPass = document.getElementById("pass").value;
var userName = document.getElementById("user").value;
this.pass = userPass;
this.name = userName;
alert("whatever you want to display");
}
you have multiple elements with the same id. That is a big no-no. Make sure your inputs have unique ids.
<td id="pass"><label>Password</label></td>
<tr>
<td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>
see, both the td and the input share the id value pass.
Remove the id="pass" off the td element. Right now the js will get the td element instead of the input hence the value is undefined.
Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery
$("#<%= txt_iplength.ClientID %>").val();
This is the sample code for the email and javascript.
params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += " Query: ";
content += unescape(params["FormsMultiLine4"]);
var email = "ni#gmail.com";
document.write('SUBMIT QUERY');