I've been trying forever to keep the values the user entered into the added input fields when the web page is refreshed but with no success. I was wondering if anyone can help me with this so far I got the input fields to remain when the web page is reloaded. If it helps I'm using JQuery and PHP. My JQuery code is located below.
JQuery
$(document).ready(function(){
var max_fields = 10;
var x = 1;
if(typeof(Storage) !== 'undefined'){
$('.worker').on('click', function(e){
e.preventDefault();
e.stopPropagation();
if(x < max_fields){
x++;
$(this).closest('li').find('div:eq(3)').append('<input type="text" name="first_name[]" /><input type="text" name="last_name[]" /><select name="title[]" class="title"><option value="Select a Title" selected="selected">Select a Title</option><option value="Boss">Boss</option><option value="Worker">Worker</option><option value="Manager">Manager</option></select>');
sessionStorage.setItem('Data',$(this).closest('li').find('div:eq(3)').html());
}
});
if(sessionStorage.getItem('Data')){
$('.worker').closest('li').find('div:eq(3)').html(sessionStorage.getItem('Data'));
}
}
});
You need a mechanism to:
Devise a way to save data to session storage for all inputs
Trigger saving data to session storage (like a button or input change)
Iterate through all session storage on reload and find the ones you are interested in
Populate the fields with that data
Here's a sample for two text inputs:
$( document ).ready(function() {
if(typeof(Storage) !== 'undefined'){
populateInputs();
}
function populateInputs(){
for(var i=0; i<sessionStorage.length; i++) {
var temp = sessionStorage.key(i);
if(temp.startsWith('inputData')) {
console.log('Setting ' + temp.split('-')[1] +
' to ' + sessionStorage.getItem(temp));
$('#'+temp.split('-')[1]).val(sessionStorage.getItem(temp));
}
}
}
$('.saveInput').on('input', function(){
sessionStorage.setItem('inputData-'+this.id, this.value);
});
});
The HTML:
<label>First Name :</label><input type="text" class="saveInput" id="firstname"></input> <br>
<label>Last Name :</label><input type="text" class="saveInput" id="lastname"></input>
Running example at https://plnkr.co/edit/MrAUBAMALOmYRwxLqBs0?p=preview
You could keep every input and select (and others if needed) value in local storage, save on unload and reload on page load. See simple example:
$(document).ready(function() {
$(window).unload(saveSettings);
loadSettings();
});
function loadSettings() {
$('input, select').each(function(i,o) {
$(o).val(localStorage[$(o).attr('id')])
});
}
function saveSettings() {
$('input, select').each(function(i,o) {
localStorage[$(o).attr('id')] = $(o).val();
});
}
This example save inputs and selects as key-value pairs based on their id attribute. It is dynamic and easily expandable.
See it running
Related
Hi I want to create a stamp script and I want the user to enter his name and address in three fields,
then he should see the fields later in the stamp edition?
I have 3 input fields where the user can give in his data,
now i will give this data in a new class. This is what i have:
window.onload = function() {
$( "#Text1" )
.keyup(function() {
var value = $( this ).val();
$( ".ausgabe" ).text( value );
})
.keyup();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
It looks like you want to mimic what the user is typing in the text inputs and show it in ausgabe. If that's what you want, then you can tie the keyUp event to each of the inputs.
$(input [type='text']).keyUp(function() {
var value = $(this).val();
$('.ausgabe').text(value);
}
But this will overwrite .ausgabe every time text is entered into a different input.
You could get the value of .ausgabe every time keyUp fires and pre-pend that value:
So you may want to have a button that renders each input's value into .ausgabe:
<button>.click(function() {
$(input[type="text"]).each(function() {
var boxText = $(this).val(); //text box value
var aus = $('.ausgabe').text(); //ausgabe value
$('.ausgabe').text(boxText + ' ' + aus); //combine the current text box value with ausgabe
})
})
As you have not made it very clear what you are trying to accomplish, I am providing a simple example that might send you down the right path.
$(function() {
function updateDiv(source, target) {
var newVal = "";
source.each(function() {
newVal += "<span class='text " + $(this).attr('id').replace("Text", "item-") + "'>" + $(this).val() + "</span> ";
});
target.html(newVal);
}
$("[id^='Text']").keyup(function(e) {
updateDiv($("input[id^='Text']"), $(".ausgabe"));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="Text1">
<input type="text" id="Text2">
<input type="text" id="Text3">
<div class="ausgabe"></div>
Since you already seem to understand .html() and .text(), we can look at the Selector. The one used will select all elements with an ID Attribute of Text in the beginning of the string. See More: https://api.jquery.com/category/selectors/attribute-selectors/
How can you make the browser remember what the user typed in the form, which has not yet been submitted and make the page refreshing not affect the data entered?
I have a form in which the user enters a number. Initially the form has 0 by default. I am storing the data in localStorage, so the browser can remember the data. However, when the page is refreshed, the user-entered data disappears and 0 is displayed by default. (still the localStorage data exists for it)
I tried to use jQuery's
$(".formClassName").val(localStorage.getItem(key));
but it does not work. Can anyone give me a piece of advice on this?Thank you in advance.
Edited: My form looks like this:
<form>
<!--There are multiple forms, and the only difference among them is the "name" attribute -->
Enter a number <input type="text" value="0" class"dataEntered" name="****">
<!--The button below saves the data entered in the above form -->
<input type="button" class="savedata" value="Save Value" name="****">
</form>
And I am adding the data to localStorage like below:
//JavaScript
<script>
//Using on because the website retrieves the above form dynamically
$(document).on("click", ".saveData", function(e){
//retrieve the number entered in the form
var userNum = $(this).siblings(".dataEntered").val();
//retrieve the value in name attribute
var thisFormName = $(this).attr("name");
//store the data
localStorage.setItem(thisFormName, userNum);
//Now that the save button has been pressed (not submitted to the
//server yet), and the data is stored in localStorage, I want to
//the page to show the number in userNum even after you refresh the page
//but this does not work.
$(".dataEntered").val(localStorage.setItem(thisFormName));
});
</script>
use cookie:
function addCookie(sName,sValue,day) {
var expireDate = new Date();
expireDate.setDate(expireDate.getDate()+day);
document.cookie = escape(sName) + '=' + escape(sValue) +';expires=' + expireDate.toGMTString();
}
function getCookies() {
var showAllCookie = '';
if(!document.cookie == ''){
var arrCookie = document.cookie.split('; ');
var arrLength = arrCookie.length;
var targetcookie ={};
for(var i=0; i<arrLength; i++) {
targetcookie[unescape(arrCookie[i].split('=')[0])]= unescape(arrCookie[i].split('=')[1]);
}
return targetcookie;
}
addCookie('type','1',1024);
var cookiesample = getCookies();
$(".formClassName").val(cookiesample.type);
cookiesample.type could be remembered unless the cookie is deleted.
Checkout this codepen I have it shows a functional solution to the problem. Also you need to make sure jQuery script checks if the DOM is ready, you can do that by using $(function() { }) a short hand for .ready().
$(function() {
var input = $("[type=text]");
var thisFormName = input.attr("name");
if (localStorage.getItem(thisFormName)) {
var value = parseInt(localStorage.getItem(thisFormName));
input.val(value);
}
$(document).on("click", ".savedata", function(e) {
var userNum = input.val();
localStorage.setItem(thisFormName, userNum);
input.val(localStorage.getItem(thisFormName));
});
});
I have a simple form that will show hidden div when category is selected in a select tag.
What I want is when I refresh the page, the contents is still visible and also the checked items is still there.
here is the sample code
HTML
<select class="form-control" name="food_type1" id="food_type1">
<option selected="selected" disabled="disable" value="0">SELECT</option>
<option value="1">Fruits</option>
<option value="2">Meat</option>
</select>
<div id="food1" style="display: none;">
<input type="checkbox" name="food1[]" value="Mango">Mango <br>
<input type="checkbox" name="food1[]" value="strawberry">Strawberry
</div>
<div id="food2" style="display: none;">
<input type="checkbox" name="food2[]" value="Beef">Beef <br>
<input type="checkbox" name="food2[]" value="Pork">Pork <br>
<input type="checkbox" name="food2[]" value="Chicken">Chicken
</div>
SCRIPT
$(document).ready(function(){
$('#food_type1').on('change', function() {
if ( this.value == '1') {
$("#food1").show();
$("#food2").hide();
}
else if ( this.value == '2') {
$("#food2").show();
$("#food1").hide();
} else {
$("#food1").hide();
$("#food2").hide();
}
});
});
FIDDLE
https://jsfiddle.net/bk2ohogj/
The simplest way would be to use Local storage. I've updated your fiddle, however you will not be able to test the refresh while in JSFiddle, so you will have to try the code locally on your machine.
JSFiddle: https://jsfiddle.net/m0nk3y/bk2ohogj/4/
You will have to create a couple functions to implement it. I kept them as simple as possible, so they may not address all your use cases, but this should help you get closer to what you are trying to do:
JS:
$(document).ready(function(){
var storedItems = [];
//Store selected items
function storeItem(item) {
storedItems.push(item);
localStorage.setItem("storage", storedItems);
}
//Remove item
function removeItem(item) {
var index = storedItems.indexOf(item);
storedItems.splice(index, 1);
}
//Show list according to Dropdown
function showList(type) {
var $food1 = $("#food1");
var $food2 = $("#food2");
localStorage.setItem("list", type);
if ( type == '1') {
$food1.show();
$food2.hide();
} else if ( type == '2') {
$food2.show();
$food1.hide();
} else {
$food1.hide();
$food2.hide();
}
}
//Get list type
if (localStorage.getItem("list")) {
showList(localStorage.getItem("list"));
}
//Get stored items
if (localStorage.getItem("storage")) {
storedItems = localStorage.getItem("storage");
$.each(storedItems, function(i, val) {
$('input[type="checkbox"][value="'+val+'"]').prop("checked", true);
});
}
//Dropdown
$('#food_type1').on('change', function() {
showList(this.value);
});
//Checkbox
$('input[type="checkbox"]').on('change', function() {
var $this = $(this);
if ($this.is(':checked')) {
storeItem(this.val())
} else {
removeItem(this.val());
}
});
});
You'll need a mechanism to remember the states and dynamically set them on page re/load. You can use sessions (if you are using a server language to generate the pages) or cookies in your scripts. It depends on your scenario.
You can store the states on the server in the db. Whenever the state changes, send an update to the back end which will store the state and return the state. You should use this state to populate the form.
You can use HTML5 Local storage on the browser to retain the states. However, ensure you handle this carefully, per user. Whenever the page reloads, read the state from the local storage and populate the form. In case you have security concerns, be aware that users of the browser can see the content of the local storage.
Need to append a script to a text field in an 'enter postcode' field, which will actively check the content and pop up an alert. Blacklisting postcodes, basically.
Here is what I have:
HTML:
<input type="text" maxlength="20" size="25" value="" name="zipc" id="zipc">
JS:
jQuery("#zipc").ready(function () {
function BFPO(t) {
if (t.value.match(/\"BF1 3AA"/g)) {
alert('We cannot send parcels to BFPO addresses. Ever.');
t.value = t.value.replace(/\s/g,'');
}
}
});
Now, I'm aware that is doesn't work but how do I fully 'ready' an alert like this when you then select the next field to type in? Perhaps the use of indexOf()?
Any help would be great and thanks in advance.
I think you can use focusout function. check this out
Focusout jquery
and also you can use
blur() function as well
$('#textfieldid').blur(function() {
//logic
});
So here's the solution, if anyone was wondering:
jQuery('#zipc').focusout(function () {
var _val = jQuery(this).val();
var _array = ["BF1 3AA", "Some_postcode"];
for (var i = 0; i < _array.length; i++) {
if (_val.indexOf(_array[i]) != -1) {
alert('OH, snap! That\'s a BFPO postcode... We don\'t send stuff there. Bummer.');
jQuery('#zipc').val("");
}
}});
Fiddle:
http://jsfiddle.net/hslincoln/WbDpG/1/
Here is the working demo of what I want to achieve. Just enter some value in input and you might get what I want to achieve. (Yes, I got it working but stay on..)
But it fails when multiple keys are pressed together.
What I am trying :
I have screen which contains few enabled and few disabled input elements. Whenever user updates any value in editable input element, I want to update disabled input which had same value with user updated value.
HTML :
<input value="foo" /> // When User updates this
<br/>
<input value="bar">
<br/>
<input value="Hello">
<br/>
<input value="World">
<br/>
<input value="foo" disabled> // this should be updated
<br/>
<input value="bar" disabled>
<br/>
<input value="foo" disabled> // and this also
<br/>
<input value="bar" disabled>
<br/>
<input value="Happy Ending!">
<br/>
I tried this which I think will save me from multiple_clicks_at_a_time
JS:
$(":input:not(:disabled)").keyup(function () {
// Get user entered value
var val = this.value;
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings");
$(siblings).each(function () {
// Update each input with new value
this.value = val;
});
});
$(function () {
$(":input:not(:disabled)").each(function () {
// Find inputs which should be updated with this change in this input
siblings = $(":input:disabled[value=" + this.value + "]");
// add them to data attribute
$(this).data("siblings", siblings);
});
});
But I am not able to pass the selectors to keyup function and invoke .each on it.
PS:
My previous completely different try, working with single_click_at_a_time but I felt that I am unnecessarily traversing the DOM again and again so dropped this
$(":input").keypress(function () {
$(this).data("oldVal", this.value);
});
$(":input").keyup(function () {
var oldVal = $(this).data("oldVal");
$(this).data("newVal", this.value);
var newVal = $(this).data("newVal");
$("input:disabled").each(function () {
if (this.value == oldVal) this.value = newVal;
});
});
I would group those inputs first and bind a handler for enabled elements to apply to the group. See below,
var grpInp = {};
$(":input").each(function () {
if (grpInp.hasOwnProperty(this.value)) {
grpInp[this.value] = grpInp[this.value].add($(this));
} else {
grpInp[this.value] = $(this);
}
});
$.each(grpInp, function (i, el) {
el.filter(':enabled').keyup(function () {
el.val(this.value);
});
});
DEMO: http://jsfiddle.net/fjtFA/9/
The above approach basically groups input element with same value, then filters them based on :enabled and bind a handler to apply it to the group.
// Find associated inputs which should be updated with new value
siblings = $(this).data("siblings", siblings);
No. The .data method called with two arguments does not get, but set the data (and returns the current selection). Also, you should make your variables local:
var siblings = $(this).data("siblings");
Working demo