How can I hold value in input without cookie - javascript

I append a text value with jquery. But when I was refresh the page, input value disappear. I can use jquery cookie but I don't want to use this method. How can I hold value in input without cookie. There is an example and jsfiddle demo below.
<input type="text" id="couponInput" class="couponInput" placeholder="Coupon code" />
<button type="button" id="couponApply" class="couponApply">APPLY COUPON</button>
<span class="removeCoupon"></span>
<script>
$(document).ready(function(){
$('.couponApply').click(function(event){
var couponInputval = $(".couponInput").val();
if(couponInputval == "x1"){
alert('Coupon Applied!');
$( ".removeCoupon" ).append( "Remove Coupon" );
$(".couponInput, .couponApply").attr('disabled','disabled');
$('.removeCoupon').click(function(){
$(".couponInput, .couponApply").removeAttr('disabled','disabled');
$(".removeCoupon").empty();
});
}
else{
alert('Error');
}
event.preventDefault();
});
});
http://jsfiddle.net/vsgfj05h/

You can use sessionStorage or localStorage - it's the best way to do it

You can use the local storage instead of cookie.
It not working inside the jsfiddle. I think it's because jsfiddle uses iframe to display the results.
Simple usage:
if (localStorage.couponInputval) {
$(".couponInput").val(localStorage.couponInputval)
}
localStorage.couponInputval = $(".couponInput").val();
MDN Documentation

Related

Auto-save all inputs value to localStorage and restore them on page reload

I'm about to code, in Javascript some code (involving looping on each <input> and adding listeners):
allowing, after keypress, to save all <input> values to localStorage
restore all <input> values from localStorage in the case the page/browser has been closed and reopened on the same page
But maybe is there an automatic way, provided by the browsers?
e.g. by adding an attribute to <input>, similar to <input autofocus> (which is not related here)
Question: is there an autosave feature of <form> <input> HTML tags?
As far as I know, there is no built-in way to do that, you should do it manually;
function persist(thisArg) {
localStorage.setItem(thisArg.id, thisArg.value);
}
<input id="test" onchange="persist(this)" />
persist and retrieve all together:
function persist(event) {
localStorage.setItem(event.target.id, event.target.value);
}
// you may use a more specific selector;
document.querySelectorAll("input").forEach((inputEl) => {
inputEl.value = localStorage.getItem(inputEl.id);
inputEl.addEventListener("change", persist);
});
<input id="test" />
there is no automatic way to do that.
you have two options :
save the data by code
example:
localStorage.setItem('testObject', JSON.stringify(yourObject)); // for storing data
JSON.parse(localStorage.getItem('yourObject')); // for retrieving data
code snippet:
// for saving data
function saveData(el) {
localStorage.setItem(el.id, JSON.stringify(el.value));
}
// for retrieving data on page load
function getData() {
var inp = document.getElementById("inp");
inp.value = JSON.parse(localStorage.getItem('inp')) || "";
}
<body onload="getData()">
<input id="inp" onchange="saveData(this)" />
</body>
try a helper library like persisto
Based on the accepted answer, here is a one-liner that can be useful:
document.querySelectorAll('input:not([type="submit"])').forEach(elt => { elt.value = localStorage.getItem(elt.name); elt.addEventListener("change", e => { localStorage.setItem(e.target.name, e.target.value); }); });
It serializes/deserializes the <input>s to localStorage, indexed by their attributes name.

how to access value hidden elements using loop

what i need
i need to fetch hidden element data according to particular element id.
a.html
<input type="hidden" id="evt_date" value="feb 10">
<input type="hidden" id="evt_date" value="Mar 21">
<input type="hidden" id="evt_date" value="april 05">
js
<script>
$.each($('input'), function(i, val) {
if ($(this).attr("type") == "hidden") {
var event_date = document.getElementById('evt_date');
console.log(event_date);
}
});
</script>
problem
on doing console.log im getting
<input type="hidden" id="evt_date" value="feb 10">
i want to fetch all hidden element in loop using js.
updated js code
$.each($('input.event_date'),function(i,val)
{
if($(this).attr("type")=="hidden")
{
console.log(val);
var evt_date=$('.event_date').val();
console.log(evt_date);
$('.date_event').html(evt_date);
}
});
It's not a good practice to use same id for multiple element. You can instead use class attribute. So first you should change those repeated id attributes into 'class' attributes.
HTML : Updated
<input type="hidden" class="event_date" value="feb 10">
<input type="hidden" class="event_date" value="Mar 21">
<input type="hidden" class="event_date" value="april 05">
<div class="date_event"></div>
<div class="date_event"></div>
<div class="date_event"></div>
Next about your answer, loop through the each element and log the value or use it anyway. Try this,
jQuery :
You question seemed little confusing to me when in one part you asked for the data of the element and in another part you asked for the element itself.
$.each($("input[type='hidden'][class='evt_date']"), function(){
console.log($(this).val()); // value of the element
console.log($(this)); // the element itself
});
jsFiddle
Modification of your code :
jQuery :
var counter = 0;
$.each($('input.event_date'),function(i,val)
{
if($(this).attr("type")=="hidden")
{
console.log(val);
var evt_date=$(this).val();
console.log(evt_date);
$('.date_event:eq('+ counter +')').append(evt_date);
counter++;
}
});
jsFiddle
Dont know why you used same Id but this will be the short way:
$("input [id='evt_date'][type='hidden']").each(function(){
console.log($( this ))
});
$.each($('input'),function(i,val){
if($(this).attr("type")=="hidden"){
console.log($(this).val());
}
});
Demo
Try this
$('input[type="hidden"]').each(function(index,item){
console.log($(item));
});
Working demo
You are using the same id for all the inputs. The id should be unique. Use a class instead
$.each($('input.evt_date'),function(i, field) {
if($(this).attr("type")=="hidden") {
console.log(field);
}
});

How to not execute hidden forms

<script>
$(document).ready(function(){
$("#hdcChoose").click(function(){
$("#hdcNumber").toggle();
$("#hdcNumber2").hide();
});
});
$(document).ready(function(){
$("#hdcWrite").click(function(){
$("#hdcNumber").hide();
$("#hdcNumber2").toggle();
});
});
</script>
"hdcWrite" and "hdcChoose" are my fields that the user can show or hide. Both consist of a Number that is needed for my SQL query. Here are my SQL WHERE statments:
WHERE HDC.NAME ='$hdcChoose'
OR HDC.NAME = '$hdcWrite'");
The problem is, that when first field is hidden,and it's not null, it's executed as first in my SQL Query.
any idea how can I avoid that? Is there any usefull function for that?
The best solution is to set the wanted values as "" when the form is clicked. It's very simple:
$("#hdcNumber").val("");
You can check onsubmit if the field is hidden and empty the value:
if($('#hdcChoose').css('display') == 'none')) {
$('#hdcChoose').val("");
}
You can add an <input type="hidden" id="hdc"> which is filled by the good value when the user click on "hdcWrite" or "hdcChoose" and SQL works with this value.
I thought something like this:
<input type="hidden" id="hdc">
<script>
$(document).ready(function(){
$("#hdcChoose").click(function(){
$("#hdcNumber").toggle();
$("#hdcNumber2").hide();
$("#hdc").val($("#hdcNumber").val()); // or $("#hdc").val("hdcNumber");
});
});
$(document).ready(function(){
$("#hdcWrite").click(function(){
$("#hdcNumber").hide();
$("#hdcNumber2").toggle();
$("#hdc").val($("#hdcNumber2").val()); // or $("#hdc").val("hdcNumber2");
});
});
</script>
and SQL would recover the value of the "hdc" like something that:
WHERE HDC.NAME ='$hdc'

Clear multiple input[type=text] default values on button click before sending

I have a form with a lot of fields and want to clear all the default values (unchanged ones) for the input[type=text] when I click the button preferably using jQuery. I am using the button rather than submit because I am will be using the same button to then submit the form to a local script and then on to a third part for processing. But my script doesn't seem to be working.
A simplified version of the form:
<form name="cpdonate" id="cpdonate" method="post" action="" >
<input type="text" value="First Name" id="BillingFirstName" name="BillingFirstName" onFocus="clearField(this)" onBlur="setField(this)" />
<input type="text" value="Last Name" id="BillingLastName" name="BillingLastName" onFocus="clearField(this)" onBlur="setField(this)" />
<input type="hidden" name="Submit" value="Submit" />
<button id="cpbutton">Submit</button>
</form>
and the script I'm using:
<script type="text/javascript">
$(document).ready(function(){
// default values will live here
var defaults = {};
// Set the default value of each input
$('input[type=text]').each(function(){
defaults[$(this).attr('value')] = $(this).text();
});
// Functions to perform on click
$('#cpbutton').click(function(){
// clear unchanged values
$('input[type=text]').each(function(){
if (defaults[$(this).attr('value')] === $(this).text())
$(this).text('');
});
});
});
</script>
input doesn't have text, it has value and you can't rely on the attribute once user changes it, need to get it from the value property. Also, your defaults object won't locate the value if it is changed.
Am going to store each value on the elements itself using data()
Use val()
$(document).ready(function(){
// Set the default value of each input
$('input[type=text]').each(function(){
$(this).data('val', $(this).val());
});
// Functions to perform on click
$('#cpbutton').click(function(){
// clear unchanged values
$('input[type=text]').each(function(){
if ($(this).data('val') === $(this).val())
$(this).val('');
});
});
});
You should use defaults[$(this).attr('name')] instead of defaults[$(this).attr('value')] because when user changes value then attribute "values" value also changes
You may try this (Example)
// clear unchanged values
$('input[type=text]').each(function(){
if ($(this).val() == this.defaultValue) $(this).val('');
});
An input type=text has .val() jQuery method, not text() and use this.defaultValue to check the initial default value.

How to send multiple values from a checkbox input

I am trying to collect multiple pieces of data from a checkbox, but I am unsure of how to do this. Right now I have:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" style="display:inline-block;">
Which allows me to collect an id (contained in {{$friend}}) that I need. But I also need the name associated with this id. Is there a way to collect multiple values from a single checkbox? I would need this because I am collecting the data and moving to another form without changing the view. This would be used for javascript which would print out stuff in the view as it is checked (i.e. the id and name).
Here is the javascript:
<script>
$(document).ready(function(){
var callbacks_list = $('.callbacks ul');
$('.facebook-friends-larger input').on('ifChecked', function(event){
callbacks_list.prepend('<li><img src="https://graph.facebook.com/'+this.id+'/picture" alt="" height="50" width="50"><span id="#'+this.id+'">#' + this.id + '</span> is ' + event.type.replace('if', '').toLowerCase() + '</li>');
});
$('.facebook-friends-larger input').on('ifUnchecked', function(event) {
callbacks_list.find('span#'+ this.id).closest('li').remove();
console.log(this.id);
});
});
</script>
Any ideas? Thank you for your help.
Try this this will be helpyou..
$("input[type=checkbox]").change(function(){
alert($(this).val()); //get a val
alert($(this).attr('name')); //get a value of name attribute
});
Fiddle here
If you have the access to the username before the page is loaded (and is therefore able to inject it into the DOM without making ajax queries after pageload or user action), you can store them in HTML5 data- attributes, for example, data-name in the following format:
<input tabindex="1" type="checkbox" name="friend[]" id="{{$friend}}" value="{{$friend}}" data-name="{{name}}" style="display:inline-block;">
You can access the name by simply calling the .data() method in jQuery, i.e. $('input').data('name').
Use:
var name = $("#checkbox-id").attr("name"); // Use whatever method you have to target the checkbox
and so on to get the other values
Try this
HTML
<input tabindex="1" type="checkbox" name="friend[]" id="123" value="{{$friend}}" style="display:inline-block;">test
JS
$(document).ready(function(){
$("#123").change(function(){
$(this).val(); //get a val
console.log($(this).attr('name')); //get a value of name attribute
});
});
FIDDLE

Categories