How to append item to drop down and save - javascript

I have the following drop down list which I am able to append new listings to.
<script>
function Add()
{
var x = document.getElementById("MySelectMenu");
var opt = document.createElement("option");
opt.value= document.getElementById("url").value;
opt.innerHTML = document.getElementById("name").value; // whatever property it has
x.add(opt);
} </script>
<select id="MySelectMenu">
</select>
<button onClick="newSrc();">Load</button>
Name: <input type="text" name="name" id="name">
URL: <input type="url" name="url" id="url">
<button onclick="Add()">ADD</button>
What currently happens (for obvious reasons) is once the user closes the browser page, the list obviously returns to its previou state. How do I make it so the list remembers the appended items?

You can use cookies to save local data for the user, whenever the user adds an item to the list update the local cookie and when the page loads for the first time after a user comes back use an onLoad event to load the items from the cookie into the list.
this ofcourse will only be saved on the BROWSER level for that user, meaning if the same user opens the page in a difrent browser or on a difrent device these changes will not be saved.
to save info on a global nature you will need server side proccessing.

Since javascript or jQuery are front-end scripting languages, the changes made to a page will not be saved.
You would have to explicitly save the newly added items either in Cookies or Session using the following add-on plugins,
https://github.com/carhartl/jquery-cookie
https://github.com/AlexChittock/JQuery-Session-Plugin
And then handle the newly added elements when the page loads at a later time.

Related

Text shows then disappears on page reload; javascript onclick event

I am using javascript to show text on button click. When I click the button, the text appears then disappears in a flash after page reload.
This is the paragraph that contains the text after clicking the button
<p class="lead" id="class"><strong style="color: red; font-size: 15px; display: none;"></strong></p>
This is my button:
<button type="submit" class="btn btn-primary" onclick="myFunction()">Search</button>
This is my script
<script>
function myFunction() {
document.getElementById("class").innerHTML = "Class current balance total";
}
</script>
How can I make the text show and not disappear after page refresh?
PS : I am very new to javascript.
That is because of type="submit"... try <input type="button" ... /> instead.
You cannot do that with this way. That's not how JS works. In order to keep the data back to the state it was, even after refreshing the page, you need to do that with Localstorage.
Localstorage is a concept in JS, while you are displaying the data after the event happen, you are storing the value in your browser's localstorage, so since the value is already stored in browser, you should be able to retrieve that value.
it shud be something like this localstorage.setItem to save the value and localstorage.getItem to access the saved value and display it on your page.
Hope that answers your question!
I do believe that local storage would help with this problem. I have implemented a solution here for you. Local storage allows web applications to store locally within the user's browser. It is different than cookies. What I have done here is stored your text into local storage as a key/value pair. Local storage retrieves it using the "getItem" method. You can see a demo of this code here
The code:
<script>
//an immediately invoked function that checks to see if the text is in local storage already
(function(){
//if the text is in local storage, set the html
if (localStorage.currentTotal){
console.log(localStorage.currentTotal);
document.getElementById('class').innerHTML = localStorage.getItem("currentTotal");
}
})();
//function that gets called for an onclick event
function myFunction() {
// Store in local storage
localStorage.setItem("currentTotal", "Class current balance total");
//set the inner html to what is in local storage
document.getElementById("class").innerHTML = localStorage.getItem("currentTotal");
}
</script>
The form tag is causing a page reload. Remove the form tags and it should work fine.
Try changing display:none to display:block in your script.
function myFunction() {
document.getElementById("class").innerHTML = "Class current balance total";
document.getElementById("class").children.style.display = 'block';
}
issue with input value is on refresh it disappears,localstorage does not work,but you can get it to work,do setItem code,and getItem but have window.onload and inside document.getElementById("demo").innerHTML =localStorage.getItem("peanuts");you see localStorage has stored info but to display you need to retrieve it,f12 to check its stored,also i add if(typeof(Storage) !== etc., to my code when using localStorage

Retain the values after refeshing the page

How do I retain the value of like count even after refreshing the page in ruby on rails?
<p>
<input type="button" value="Like" id="countButton" />(<span id="displayCount">0</span>)
<script type="text/javascript">
var count = 0;
var button = document.getElementById("countButton");
var display = document.getElementById("displayCount");
button.onclick = function() {
count++;
display.innerHTML = count;
}
</script>
</p>
The above code increments the value of like each time we hit the like button. After refreshing the page the value of count be comes 0. What to do to retain the values of like after refreshing the page?
Web pages are stateless so every time you refresh the page, any values will be lost unless you specifically save them. If you want to save them forever, you will need to create a database table that saves the number of likes. Each time the like button is clicked you will need to save the new value to the d/b.
You will need a database backed model for whatever it is that is being liked. You may want to look at the rails guides, active record and learn about REST and RESTful routing
It all depends on what you want to do with the counter.
If it is user related, you can store the value in the user's session
like this : session[:counter] = 2.
If the counter should be shared between all users, you will have to create a new field in your database to store it.

How to store all siblings in a dynamic local storage array?

I have 2 files - first.html & second.html
first.html - here the user will input a few fields: Name, Organization, JobTitle,...
second.html - this will output only the fields that were typed by the user using a textarea field
Purposer: My purpose is to (1) dynamically store all siblings of a particular span (id="spanBox") in an array and (2) to output all the element of that array using text area field in the second.html
Clarifications: Let me just clarify what do I mean by "dynamically store all siblings" in an array. In the next few lines, I will mention only a small part of the fields that will be stored in the array. Dynamically means, that I wouldn't have to store manually each one of the fields by its name, but instead, when an onClick event is triggered (after pressing the button) I'de call sendtoLastPage() that will store all the siblings dynamically in the array.
First.html:
function sendtoLastPage(){
//How do I dynamically store all the siblings of id=spanBox to an array?
window.location="second.html"; //Send users to the next page
}
<span class="box" id="spanBox">
Name<BR><input name="Name" id="Name" type="text" size=40>
Organization<BR><input name="Organization" id="Organization" type="text" size=40>
Job Title<BR><input name="JobTitle" id="JobTitle" type="text" size=40>
<button value="btn" onClick="sendtoLastPage();">Go to Next Page</button>
</span>
Note: I'm looking for a JavaScript solutions (not jQuery).
Thanks for dedicating the time to read this issue. I really tried to search for a solution in others threads, but I couldn't find any similar questions.
You could probably bind the following callback to your "Go to Next Page" button:
function handleSubmit(evt) {
var spanBox = document.querySelector('#spanBox');
var inputs = spanBox.querySelectorAll('input');
var data = {};
inputs.forEach(function(input) {
data[input.name] = input.value;
});
localStorage.setItem('savedData', JSON.stringify(data));
}
This will store the inputs to the localStorage and in the second.html file, you can access the localStorage data by using the savedData key.
It'd looks something like:
var textArea = document.querySelect('textarea');
var savedData = JSON.parse(localStorage.getItem('savedData'));
textArea.value = savedData;

keep spring form select value

I use Spring MVC 4 bring a list and show on the website
<s:select path="almacenesByAlmOri.codAlm" id="select1" name="select1" onchange="tr_EnviarAlmacen('select1');" items="${listalmacen}" itemValue="codAlm" itemLabel="nomAlm" class="form-control input-sm"></s:select>
<script>
function tr_EnviarAlmacen(sel){
var cbox = document.getElementById(sel);
var valor = cbox.options[cbox.selectedIndex].value;
var red = "getprodxalm?cod_alm="+valor;
location.href = red;
}
</script>
As I can keep the option of a select spring form selected by reloading the page?
View is rendered by server everytime you refresh(I mean the 'hard refresh' without browser caching) the page, that means Model is refreshed and proper selected values are injected in to the view(the values wich were posted and saved).
To keep selected option while you refresh your page you have to use AJAX.
You need to HTTP POST selected options everytime user selects something in your select form.

Making Meteor reactive for html elements

So I have a modal box that allows the user to edit / save some data.
I just want to add that unlike other Meteor apps, I don't want to save the data straight away - I want the user to fill in all the fields before hitting save where it will save to the database and send to server etc. This is mainly because I want the user to be able to hit the "cancel" button to revert all changes.
I have a drop down box at the start of the form where depending on the value, fields will be shown or hidden
<select class="form-control" id="ddlNewInputType" placeholder="Enter your input type">
<option value="input">Input</option>
<option value="formula">Formula</option>
</select>
And I have a handlebar around a field like this to determine whether I want to show it
{{#if isFormula }}
<div class="row">
<input type="text"
id="txtNewInputFormula" placeholder="Enter formula">
</div>
{{/if}}
With a helper looking like this
isFormula: ->
$('#ddlNewInputType').val() == 'formula'
However, this doesn't work. Aside from when it first loads onto the page, it never hits isFormula, probably because Meteor doesn't consider any of the HTML elements as reactive so it never re-evaluates when the HTML element changes.
What is a suitable way to get around this? Is it possible to make something reactive explicitly in Meteor? I was also considering putting the dropdown list value into a session variable but that just seems messy because I'm going to need to manage this session variable (remember to clear it when the modal box closes etc.)
Your analysis is correct - a reactive variable needs to be involved in order for your helper to reevaluate after changing the select element. The basic strategy looks like:
Initialize a reactive variable when the template is created.
Whenever the select changes, update the reactive variable.
Read the reactive variable in your helper.
Rather than use a session variable, let's use a ReactiveVar scoped to your template. Here's an example set of modifications:
Template.myTemplate.helpers({
isFormula: function() {
return Template.instance().isFormula.get();
}
});
Template.myTemplate.events({
'change #ddlNewInputType': function (e, template) {
var isFormula = $(e.currentTarget).val() === 'formula';
template.isFormula.set(isFormula);
}
});
Template.myTemplate.created = function() {
// in your code, default this to the current value from
// your database rather than false
this.isFormula = new ReactiveVar(false);
};
Remember that you'll need to also do:
$ meteor add reactive-var
See my post on scoped reactivity for a full explanation of this technique.

Categories