Save input on cache when button click - javascript

this is a part of my html:
<p>City: <input type="text" id=city value="New York"> </p>
<p>State: <input type="text" id=state value="NY"> </p>
<button id="search">Search!</button>
<button id="favorite">mark as favorite!</button>
Bellow is my .js
The search function is working like a charm, it does an ajax call with the inputs and receive weather infos.
my problem is with the favorite button, what i need is to search for example Baltimore and click on Mark as favorite. This will make Baltimore to be the one to opens when I refresh the page.
I believe that one alternative would be changing the standard input text because my ajax call is made when document its ready or when search button is clicked but i have no idea how to do it yet.
$('#search').click(function() {
ajax();
});
$('#favorite').click(function() {
var $city= $('#city')
document.getElementById('city').value= $city.val();
});
any ideas??
edit: solution:
$(document).ready(function() {
var $city= $('#city')
document.getElementById("city").value = localStorage.getItem("city");
ajax();
});
...
...
...
$('#favorite').click(function() {
var $city = $('#city')
// Check browser support
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("city", $city.val() );
// Retrieve
document.getElementById("city").innerHTML = localStorage.getItem("city");
} else {
document.getElementById("city").innerHTML = "not possible to store";
}
ajax();

Related

How to get data from Local storage onClick in javascript

How to use the data from local storage in javascript onClick. I have my html file and javascript file below. Thanks
<fieldset>
<form>
<!--GET USER NAME-->
<p>
<label for="inName" >What is your name?</label>
<input type="text" id="inName" name="f_name"/>
</p>
<!-- GET COLOUR--> // I m not sure about how the get color as user can
//choose the color from drop down color palet.
<p>
<label for="inColor" >What is your favourite colour? </label>
<input type="color" id="inColor" name="f_color" />
</p>
<p> // how to get the value when user clicks the button
// in order to call onClick function to output the
user's name and
// display favorite color in background.
<input type="submit" value="Click to save" />
<p/>
</fieldset>
</form>
I don't know how to get data from local storage when user click to submit the form :
//NOW THAT WE HAVE STORED DATA ON ONE PAGE, WE CAN ACCESS IT FROM ANY PAGE ON THIS
WEBSITE.
window.onload = function(){
//GET ELEMENTS USED FOR OUTPUT
var userOut = document.getElementById("newMsgBox");
//GET VALUES FROM COOKIES/LOCAL STORAGE
var userName = localStorage.getItem("nameIn");
var userColor = localStorage.getItem("inColor");
//CREATE OUTPUT WITH VALUES
if (userName !== null) {
userOut.innerHTML = " " +userName;
}
}//end onload
If you want to listener event from an specific button and then access to your localStorage you could do this:
first get the element:
const button = document.getElementById('<clickable_element_id>');
then add a listener to the button;
button.addEventListener("click",(event)=> {
event.preventDefault() // only if you want to prevent the action
//here you can access to your local store items like:
const a = localStorage.getItem("<item you saved previously>");
...
});
It's really unclear what you want to do but
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inColor');
Will fetch the values for you.
I think you are looking for something like this.
<script>
function saveData() {
let inColor = document.getElementById('inColor');
let inName = document.getElementById('inName');
localStorage.setItem("inColor", inColor);
localStorage.setItem("inName", inName);
}
</script>
<input type="Button" value="Click to save" onclick="saveData"/>
Import Jquery and use this. I hope help you. when you click on button with id idOfBtn jquery gonna eject the event and call the localStorage with key (key). Replace it for you key name.
$("#idOfBtn").click(function() {
alert(localStorage.getItem('_key_'));
});

Use changed values in other page

I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".

Displaying local storage variables without page refresh

I'm able to pass the displayMessage variable, but the page reloads. I've been looking at ajax tutorials, but I'm not sure how to pass displayMessage without the page reloading.
I want to store more than one message on the phone. So if I send "help me stackoverflow," then "please," they both get stored. (right now "please" would replace "help me...").
// this is my form
<form role="form">
<div class="form-group">
<textarea class="form-control" id="message" rows="3"></textarea>
</div>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
// this is where message displays
<span class="displayMessage"></span>
// this is my js
$(document).ready(function () {
$('#submit').click(function () {
var displayMessage = $('#message').val();
localStorage.displayMessage = displayMessage;
});
});
$(document).ready(function () {
$('.displayMessage').html(localStorage.displayMessage);
})
The page reload is triggered by the default button click behaviour. You need to disable it by calling preventDefault on the event object:
$('#submit').click(function (e) {
e.preventDefault();
// your code
});
As DontVoteMeDown already said, you can store an object or array as JSON in the local storage. So you could do something like this:
$(document).ready(function () {
$('#submit').click(function (e) {
e.preventDefault();
var storedMessagesJSON = localStorage.displayMessages || '[]',
storedMessages = JSON.parse(storedMessagesJSON),
displayMessage = $('#message').val();
storedMessages.push(displayMessage);
localStorage.displayMessages = JSON.stringify(storedMessages);
});
var storedMessagesJSON = localStorage.displayMessages || '[]',
storedMessages = JSON.parse(storedMessagesJSON);
$('.displayMessage').html(storedMessages.join('<br>'));
});
I also made a JSFiddle.

JQuery Ajax call stop refresing the page

I have the following html code:
<div>
<form id="ChartsForm">
<div id="optionsheader">
<p>Choose your page:</p>
<div id="dateoptions">
<p>Until date: <input type="date" name="until_date" value="Until date"></p>
<p>Since date: <input type="date" name="since_date" value="Since date"></p>
</div>
</div>
<select name="accmenu" id="accmenu" style="width:300px; float:left; clear:both;">
<?php
$user_accounts = $facebook->api('/me/accounts','GET');
foreach($user_accounts['data'] as $account) {
?>
<option data-description="<?php echo $account['category'] ?>" data-image="https://graph.facebook.com/<?php echo $account['id']; ?>/picture" value="<?php echo $account['id'] ?>"><?php echo $account['name'] ?></options>
<?php
}
?>
</select>
<div class="insightsoptions">
<p>Choose your insights:</p>
<input id="newLikes" class="insightsbuttons" type="submit" name="submit" value="Daily new likes">
<input id="unlikes" class="insightsbuttons" type="submit" name="submit" value="Daily unlikes">
</div>
<div class="insightsgraphs">
<div id="dailyNewLikes"></div>
<div id="dailyUnlikes"></div>
</div>
</form>
</div>
which has a form with the id=ChartForm that contain two date inputs until_date and since_date, one select accmenu and two submit inputs with the values Daily new likes and Daily unlikes. I use the following Jquery function:
$(function () {
$('#accmenu').change(function() {
$(".insightsgraphs div").hide();
$(".insightsoptions input").attr("class","insightsbuttons");
});
$("#newLikes").one('click', function () {
$.ajax({type:'GET', url: 'newLikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
var json = response.replace(/"/g,'');
json = "[" + json + "]";
json = json.replace(/'/g,'"');
var myData = JSON.parse(json);
var myChart = new JSChart('dailyNewLikes', 'line');
myChart.setDataArray(myData);
myChart.setSize(960, 320);
myChart.setAxisNameX('');
myChart.setAxisValuesColorX('#FFFFFF');
myChart.setAxisNameY('');
myChart.setTitle('Daily New Likes');
myChart.draw();
}});
return false;
});
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
});
$("#unlikes").one('click', function () {
$.ajax({type:'GET', url: 'unlikes.php', data:$('#ChartsForm').serialize(), success:
function(response) {
alert(response);
$("#dailyUnlikes").html(response);
}});
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
});
});
for the application flow in the following manner: every time I click on one of the input submit buttons the script will make only one Ajax GET request to a specific php file that send me back a response with which I create a Chart in a hidden div with the id=dailyNewLikes or id=dailyUnlikes by case (for testing purposes I work for the moment only on the first button). The button it will change his background color into green and the div it will be shown. I use $("#newLikes").on('click', function(){ for change back and forth the background color and the display time of the div. (from green and display:block to red and display:none, you get the point I hope :D). Also I use $('#accmenu').change(function() { to change all buttons to red and hide the respective div in case an option from the select is changed. My problem is that after I refresh the page (Ctrl+R) choose since and until date, click on the first button (it change to green and the div is shown, also the toggle is working fine) and then click on the second button which works fine on the first click (is becoming green and div is shown) but on the second click I have an issue: the script is making another Ajax GET request (a wrong URL one) and the page is refreshed. Ex. of a good reguest URL:
http://localhost/smd/unlikes.php?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701
and an ex. of a wrong request URL:
http://localhost/smd/?until_date=2013-05-01&since_date=2013-04-01&accmenu=497232410336701&submit=Daily+unlikes#_=_
Like it can be seen (it doesn't need in the first to make this extra request) the php file is not present and also a new submit parameters is added. This also happen if I change from the select with another option. What am I do wrong? I really need to know, not just to have my code "fixed". It bugging me for a little while. Any feedback is more than welcomed. P.S. Also, how can I start the .one function only if both date inputs has been choosen? Something like how could help me?
var until = $('#dateoptions input[name="until_date"]').val();
var since = $('#dateoptions input[name="since_date"]').val();
if (until == "" || since == "") {
alert('Until date or Since date missing!');
return;
}
it will work that way? Sorry for the long question...
i think you should make your question a little shorter and just point what you need and what errors are you getting ..anyways...going through your code i see you have two click event for same button at the end for $("#unlikes").one and $("#unlikes").on(..and no return false in other function.
try adding return false
$("#newLikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyNewLikes').toggle();
return false;
});
$("#unlikes").on('click', function(){
$(this).toggleClass('green');
$('#dailyUnlikes').toggle();
return false;
});
my guess is that , since you have two click event..when it gets clicked ..these event will fire and since you are missing return false in second click function...the form gets submitted hence refreshing the form.
however its better if put your codes in single click function than creating two seperate click event.

passing old value back to javabean from javascript

I have this piece of javascript:
<script type="text/javascript">
function show_confirm()
{
var type = '<%= nameBean.getTxnType() %>';
var old_cd = '<%= nameBean.getCode() %>';
var new_cd = document.getElementById("tbCode").value;
var cd;
if (type == "Update")
{
if(old_cd != new_cd)
{
var response = confirm("Code already exists. Do you want to replace it?");
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
}
}
</script>
and this is what i am doing in my jsp page to invoke this script:
<INPUT TYPE=SUBMIT NAME="action" onclick="show_confirm()" VALUE="Save Changes">
Its working fine when I hit ok.. but my question is how can i pass the value of old_cd back to the bean so it wont update it with the new code that was entered by the user in the tbcode box.. when user hit cancel i want to ignore what value was entered in textbox and not to update that field in database
I'm not entirely clear on the use case here, but here are a couple of answers:
If the question is, "how do I stop the form from submitting when the user hits cancel?", then the answer is, return false in the click handler:
if (response){
document.NameUpdate.submit();
}
else{
cd = old_cd;
return false;
}
If you need to submit the form no matter which one the user clicks, then you probably need to submit the old value in a hidden input field and have a way to tell the server that user hit "cancel" (probably another hidden field), e.g.:
<!-- html -->
<input type="hidden" name="old_cd" value="<%= nameBean.getCode() %>">
<input type="hidden" id="canceled" name="canceled" value="0">
and javascript:
// js snippet
if (response){
document.NameUpdate.submit();
}
else{
document.getElementById("canceled").value = 1;
return true;
}

Categories

Resources