How to add data from localStorage into an input box? - javascript

I am trying to pass data from an input field on one page to an input field on a second page.
Using localStorage I am able to get the data and then output it as an alert on the target page.
<script>
function setValue() {
var parseAmount = document.getElementById("amount").value;
localStorage.setItem("amountKey", parseAmount);
}
</script>
However, I need the stored data to populate this input field:
<input type="number" class="" id="demo2" value="3000"/>
My best effort so far is:
<script>
function getValue() {
var parseAmount2 = localStorage.getItem("amountKey");
document.getElementById("demo2").value = parseAmount2;
}
</script>
Any help would be greatly appreciated!

Items from localStorage are defined as strig, your input is defined as number, try parseInt (and do you invoke getValue()?):
function getValue() {
var parseAmount2 = localStorage.getItem("amountKey");
document.getElementById("demo2").value = parseInt(parseAmount2);
}
getValue();

Once the content on the page loads, you can load the value into the page.
/* modern browsers - will execute code once all elements are loaded onto the client */
window.addEventListener('DOMContentLoaded', (event) => {
// content is loaded, load the value from storage
getValue(); // call the function to perform
});
function getValue() {
var parseAmount2 = localStorage.getItem("amountKey");
document.getElementById("demo2").value = parseAmount2;
}
https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event

Related

How to attach a blur event for #(Html.Kendo().DatePicker()?

i have a datepicker and i want to get the value if the user modify the datepicker manually without exit the datepicker.
Thanks
So do you want the value whenever someone changes the value or the value that is posted by the user in the end?
if not you could do something like:
function onDatePickerChange() {
var DateVal = $(".classofdatepicker").val();
}
If you want to post this to the page you should:
function checkMaySend() {
var url = "/MyVeryOwn/UrlIPostTo";
var DateVal = $(".classofdatepicker").val();
var data = { DatePickerValue: DateVal};
}
var jqxhr = $.post(url, data, function () {
//Do something on post here if needed
})
this is my telerik comosant <td>#(Html.Kendo().DatePickerFor(model => model.DateRecherche).Max(DateTime.Today).Events(e => e.Change("LancerRecherche")))</td> if users type date without exiting the composant i want the get the value typed when i submit .

Pass Jquery Data to print.html

I have two page, the index.html and print.html
on my index.html page there is a calculator and i have a button called print that is located on index.html
when you click PRINT button, it would go to print.html. My problem is does not send the input value I made on index.html.
Note: This work if I dont go to print.html. the value shows up, but if set it on another page, the value does show up
PRINT.HTML
$(document).ready(function() {
$('#print_modal').click(function() {
e.preventDefault();
var rec_product = $('#rec_product').val();
var calc_height = $('#calc_height').val();
var calc_width = $('#calc_width').val();
var calc_depth = $('#calc_depth').val();
$('#srec_product').text(rec_product);
$('#sheight').text(calc_height);
$('#swidth').text(calc_width);
$('#sdepth').text(calc_depth);
window.print();
return false;
window.location.href = "print.html";
window.open(url, '_blank');
});
$("#print_modal").click(function(e) {
e.preventDefault();
var value = //get input value
$.get( "print.html", {"value":value});
});
this jQuery code will direct you to print.html?value=12(where 12 is your value).
You can then use PHP in print.html to retrieve the value ($_GET['value'])
You can use
window.location = '/print.html?rec_product='+$("#rec_product").val()+'&calc_height='+$("#calc_height").val();
for loading your print.html in same window tab.
If you are sending multiple parameter use following code to get value on print.html:
<script type="text/javascript">
load();
function load()
{
window.location.search.replace ( "?", "" ).split("&")
.forEach(function (item) {
var tmp = item.split("=");
document.getElementById(""+tmp[0]).value=tmp[1];
});
}
</script>
If you want to do it via jquery then use
$("#"+tmp[0]).val(tmp[1]);
insted of:
document.getElementById(""+tmp[0]).value=tmp[1];
You must have same name input type fields as send in parameter.
You can also use load function code in your
$( document ).ready(function() {
});
on print.html.

Pass different Span and Input element to a Javascript Function

i'm writting an html page to read and write data parameters from a PLC.
My code is mainly composed by a lot of input tag to insert value and a lot of span tag to get value from PLC:
<span style="margin-left:8em;"><b>Set Attuale: </b><input id="iOra1ON3" style="width:15%;text-align:right;border:none"></input></span>
...
<span id="Ora1On3Span" class="isamod_dint" style="display:none">ORA1ON[3] A 0</span>
Inside the tag, i want to use a jscript function to get the value from the input and pass it to the span(internally connected to PLC).
<script type="text/javascript">
$(document).ready(function() {
$('#iOra1ON3').timepicker({
showMinutes:false,
onSelect:
function (){
var oSpanOra = document.getElementById("Ora1On3Span");
var oInputOra = oSpanOra.getElementsByTagName("input");
oInputOra[0].value = parseInt($("#iOra1ON3")[0].value);
var oButtonOra1 = oSpanOra.getElementsByTagName("button");
oButtonOra1[0].click();
}
});
});
</script>
i've tried to write a function SetTime to do the same thing without repeat the code.
function SetTime(OraSpan,Input)
{
var oSpanOra = document.getElementById("OraSpan");
var oInputOra = oSpanOra.getElementsByTagName("input");
oInputOra[0].value = parseInt(document.getElementById("Input").value);
var oButtonOra1 = oSpanOra.getElementsByTagName("button");
oButtonOra1[0].click();
}
and call it inside the input tag in html:
<span style="margin-left:8em;"><b>Set Attuale: </b><input id="iOra1ON3" style="width:15%;text-align:right;border:none"></input></span>
<script type="text/javascript">
$(document).ready(function() {
$('#iOra1ON3').timepicker({
showMinutes:false,
onSelect:
function SetTime(Ora1On3Span,Ora1On3Span){}
});
});
</script>
but it doesn't work because i can't pass the id of my input and span tag to the function itself.
this.id doesn't work, because i call the function inside the input tag, but outside the span tag.
What i should do to pass the id to the function and get a clean code?
Thanks in advance for any kind of suggestion
UPDATE 1:)
i've just modified the html and the js code using 'variable' in the function call
$('#iOra1ON3').timepicker({
showMinutes:false,
onSelect: function () {
SetTime('Ora1On3Span','iOra1ON3')
}
});
and add this mod in the function itself
function SetTime(OraSpan,Input)
{
var oSpanOra = document.getElementById(OraSpan);
var oInputOra = oSpanOra.getElementsByTagName("input");
oInputOra[0].value = parseInt(document.getElementById(Input).value);
var oButtonOra1 = oSpanOra.getElementsByTagName("button");
oButtonOra1[0].click();
}.
with only 1 parameter it works!
but when i try to add another parameter and a second function call, everything doesn't work anymore. So i made a mistake, but i can't figured it out where i did it.
Your function setTimedoesn't need inputs :
function SetTime(){
var oSpanOra = document.getElementById("OraSpan");
var oInputOra = oSpanOra.getElementsByTagName("input");
oInputOra[0].value = parseInt(document.getElementById("Input").value);
var oButtonOra1 = oSpanOra.getElementsByTagName("button");
oButtonOra1[0].click();
}
So your code should be (in the timepicker)
onSelect: function(){SetTime();}
OR
onSelect: SetTime

jquery.get function url parameter

in the jquery.get() function, the first parameter is URL, is that the url to the content I want to retrieve or to the Controller/action method.
The problem is I'm building an asp.net-mvc application and I'm not sure what to pass as this parameter. Right now I'm passing my partialview.cshtml but nothing is being returned, not sure if I'm doing this right or wrong.
Here's what I got
<div id="editor_box"></div>
<button id="add_button">add</button>
<script>
var inputHtml = null;
var appendInput = function () {
$("#add_button").click(function() {
if (!inputHtml) {
$.get('AddItem.cshtml', function (data) {
inputHtml = data;
$('#editor_box').append(inputHtml);
});
} else {
$('#editor_box').append(inputHtml);
}
})
};
</script>
also, what is the second parameter "function (data)" is this the action method?
You need to remove var appendInput = function () { from the script. You are defining a function but never calling it. Just use the following (update you action and controller) names
<script>
var inputHtml = null;
$("#add_button").click(function() {
if (!inputHtml) {
$.get('#Url.Action("SomeAction", "SomeController")'', function (data) {
inputHtml = data;
$('#editor_box').append(inputHtml);
});
} else {
$('#editor_box').append(inputHtml);
}
});
</script>
Edit
Based on your script you appear to be requiring the content only once (you then cache it and add it again on subsequent clicks. Another alternative would be to render the contents initially inside a hidden <div> element, then in the script clone the contents of the <div> and append it to the DOM
<div id="add style="display:none">#Html.Partial("AddItem")</div>
$("#add_button").click(function() {
$('#editor_box').append($('add').clone());
});
The first argument to $.get is the URL which will respond with the expected data. jQuery/JavaScript don't care what kind of server side architecture you have or the scripting language. Whether the URL looks like a file AddItem.cshtml or a friendly route like /User/Sandeep, it doesn't matter as far as the client side is concerned.
In the case of ASP.NET, your URL endpoint can be generated like so:
$.get('#Url.Action("SomeAction", "SomeController")', function (data) {

Javascript static variables and using in different pages

I have a jQuery plugin in my layout page header:
<script src="#Url.Content("~/Scripts/js/kendo.web.min.js")"></script>
<script src="#Url.Content("~/Scripts/app/jsCommon.js")"></script>
<script src="#Url.Content("~/Scripts/app/Layout.js")"></script>
and my layout.js:
(function ($) {
var Layout = function (node, options) {
this.node = node;
this.options = $.extend({
url: ""
}, options);
$(this.node).find('.HButton').bind('click', $.proxy(this.HButtonClicked, this));
};
Layout.prototype = {
constructor: Layout,
_loadBackground: function () {
debugger;
//load second now 'Common.currentTarget' have been lost
$(Common.currentTarget).removeClass();
$(Common.currentTarget).addClass(".HButton_Selected");
},
HButtonClicked: function (e) {
debugger;
//load first
Common.currentTarget = e.currentTarget;
}
}
$.fn.Layout = function (options) {
return this.each(function () {
$(this).data('Layout', new Layout(this, options));
});
};
}(jQuery));
in the other side I have a share repository javascript object like this :
function common() {
}
common.currentTarget = null;
var Common = new common();
then in the other page I've triggered an event like following :
<script>
$(document).ready(function () {
var layout = $("#layout").data("Layout");
$(layout).trigger("_loadBackground")
});
</script>
when the HButton element click happened at the first I'm writing the object inside the "Common.currentTarget" and it saved successfully when I've watched variable but when another page loads completely and then trigger the event "_loadBackground" the value of "Common.currentTarget" have been lost, my question is how I can define a static variable like this to be permanent in whole of my pages?
You can set a cookie from javascript to store the data, and then access the cookie from another page. Cookies can persist just during the browser session, or you can give them an expiration. For HTML5, there is local storage.
All JavaScript data is unloaded when the page is changed or refreshed. There is no way around this in JavaScript itself. You will have to send data to the server instead. Probably the easiest way to do this is to store your data in a hidden field:
<input type="hidden" id="storable" />
....
document.getElementById("storable").value = // whatever value you want to store
Then on the server side you can transfer that data to the new page.
If you are redirecting client side, use a query parameter instead.

Categories

Resources