Setting and getting localStorage with jQuery - javascript

I am trying out localStorage and attempting at getting text from a div and storing it in localStorage, however, it sets it as an [object Object] and returns [object Object]. Why is this happening?
localStorage.content = $('#test').html('Test');
$('#test').html(localStorage.content);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>

You said you are attempting to get the text from a div and store it on local storage.
Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.
Step 1: get the text from div.
what you did is not get the text from div but set the text to a div.
$('#test').html("Test");
is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].
To get the text you have to write like this
$('#test').html();
This will return a string not an object so the result will be Test in your case.
Step 2: set it to local storage.
Your approach is correct and you can write it as
localStorage.key=value
But the preferred approach is
localStorage.setItem(key,value); to set
localStorage.getItem(key); to get.
key and value must be strings.
so in your context code will become
$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);
But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;
If you are facing any other problems please update your question accordingly.

Use setItem and getItem if you want to write simple strings to localStorage. Also you should be using text() if it's the text you're after as you say, else you will get the full HTML as a string.
Sample using .text()
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// alert the value to check if we got it
alert(localStorage.getItem('test'));
JSFiddle:
https://jsfiddle.net/f3zLa3zc/
Storing the HTML itself
// get html
var html = $('#test')[0].outerHTML;
// set localstorage
localStorage.setItem('htmltest', html);
// test if it works
alert(localStorage.getItem('htmltest'));
JSFiddle:
https://jsfiddle.net/psfL82q3/1/
Update on user comment
A user want to update the localStorage when the div's content changes. Since it's unclear how the div contents changes (ajax, other method?) contenteditable and blur() is used to change the contents of the div and overwrite the old localStorage entry.
// get the text
var text = $('#test').text();
// set the item in localStorage
localStorage.setItem('test', text);
// bind text to 'blur' event for div
$('#test').on('blur', function() {
// check the new text
var newText = $(this).text();
// overwrite the old text
localStorage.setItem('test', newText);
// test if it works
alert(localStorage.getItem('test'));
});
If we were using ajax we would instead trigger the function it via the function responsible for updating the contents.
JSFiddle:
https://jsfiddle.net/g1b8m1fc/

The localStorage can only store string content and you are trying to store a jQuery object since html(htmlString) returns a jQuery object.
You need to set the string content instead of an object. And use the setItem method to add data and getItem to get data.
window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));

Related

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

Convert String from Element to working HTML code with jQuery

I'm having a checkbox which is generated dinamically. The Checkbox text contains a string with some html code inside of it. The text comes directly from the database and doesn't display it as html, but just as a string. Is it possible to convert the string to html, so it get displayed correctly? The checkbox:
<label for="id_122_gen">"I hereby consent to the processing of my above-mentioned data according
to the <a href="/declarationofconsent.pdf" target="_blank">declaration of consent." </label>
<input type="checkbox" name="confirm" id="id_122_gen" >
I tried to get the containing text with $.text() method, what worked so far.
$mystring = $("#id_122_gen").text();
After that I've tried to use jQuery method $.parseHTML() and save the result again.
$myhtml = $.parseHTML( $mystring );
Apparantly it is saved as an array, because when I try to save the result again with the $.text() method, it displays:
[object Text],/declarationofconsent.pdf,[object Text]
It's just this. No clickable link and the checkbox disappeared aswell. I'm a bit confused now what to do and don't know how I can display the correct content with a clickable link.
The solution depends on how the html of your page is generated. Your label either has has it's inner html escaped or not.
This is important; inspect view may guide you wrong with escaped HTML and show as proper HTML, so make sure to check the page source.
Most likely your data is HTML escaped and that's why you can't see the link on initial render.
If you see < and > inside the label's source it's HTML escaped.
If it's escaped and you just want to convert it to proper HTML and set it to the label, use this:
$("label[for='id_122_gen']").html( $("label[for='id_122_gen']").text() );
Basically this unescapes the label's value. It reads the innerHTML as text and thus changes the escaped characters to real ones, and when you set it back as it's html value and the innerHTML becomes unescaped.
If you just want to get the link, read on.
If the value inside the label is HTML escaped then you'll have to use .text() to read that value. If it contains unescaped HTML then you'll have to use .html().
Afterwards the flow is the same, you parse the html first.
Since there is text and a link, the parsed html will return as an array with multiple elements. If you just want to get the link you have to search in the array.
You can check out the code below.
$mystring = $("label[for='id_122_gen']").text(); //Use .html() for unescaped
$myhtml = $.parseHTML( $mystring );
var mylink = null;
var e;
while (e = $myhtml.pop())
{
if(e.tagName == "A"){
mylink = e;
break;
}
}
console.log(mylink);

Polymer: paper-autocomplete set value

I have a paper-autocomplete element as follows inside a <paper-card>
<paper-autocomplete label="Select HWName"
id="HWName"
on-autocomplete-selected="onDeviceSelect"
no-label-float="true"></paper-autocomplete>
in a given html file. I am accessing this from another file as follows
var hwName = document.querySelector("#HWName");
I need to be able to set some value in its input area on refresh, which i've remembered using localStorage API. I tried using
hwName.value = "test"
or
hwName.label = "test"
but it doesn't work. Even tried using setOption(option) as described here but doesn't work.
Is it possible to show some value on the paper-autocomplete element? I don't want to type, it should just set the last value.
You need to set text property of paper-autocomplete.
So your code will be like
hwName.text = "test"

Get whole HTML of page included values of inputs

I'm trying to save whole page as HTML file included all already written values into inputs. I tried this:
$("#content").html();
but it wont save values from inputs.
$("#content").get(0).outerHTML;
$("#content").prop('outerHTML');
Works same but still not save values of inputs. I need function which save everything on the page.
You need to set up each input values first:
$('#content input').each(function() {
$(this).attr('value', $(this).val());//set up all the input values
});
var html = $('#content').html(); //now from here you can get input values
You could try:
$("html").html();
If you want to also capture the hmtl tags you could concatenate them to the html like this:
function getPageHTML() {
return "<html>" + $("html").html() + "</html>";
}
you have save the inputs values in some variable like
var input=$("#input-id").val()
When an input is changed by the user it's .value is being changed. .value is not in the DOM, it's in the JS. So, what you need to do is transfer the .value to value= in order to be able to get it in the string. Here is how to accomplish it:
$('input').each(function(index, input){input.setAttribute('value', input.value)});
Now try to get the HTML ;)
PS: You could also modify the selector here, not to get all the inputs (like type="password").

How insert an input field in a table cell?

Sorry for the noob question: I want to create a table with input fields where the can add new ones, if they are needed. But I can'T figure out how add another input field inside a cell where another input field already exists.
My code is:
var par=obj.parentNode;
while(par.nodeName.toLowerCase()!='tr')
{ par=par.parentNode; }
// this gives me the index of the row.. works fine.
cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;
// this puts the content of the cells into the array "cell1"
var feld = cell1[1].createElement("input");
feld.setAttribute("name","avz_keywords" + avz_array + "[]");
feld.setAttribute("onblur","");
feld.setAttribute("type","text");
feld.setAttribute("size","30");
// Now I create a input element
// And now comes the problem:
cell1[1].appendChild(feld); // --> doesn't work
Has anyone a suggestion for me?
I got the idea to work without a table, theoratically that would work with my way. But that wouldn't be satisfying :/
If you look in a debugging console, you should see something like
TypeError: Object #<HTMLDivElement> has no method 'createElement'
Instead of creating the element from cell1[1], use document.createElement()
var feld = document.createElement("input");
You should use document.createElement("input"); instead of cell1[1].createElement("input");
As always (and as also stated in another answer here), the JavaScript console should be the first place to look for hints on what the problem is!
And wouldn't it actually be much easier if each table cell you want to add values to got a separate ID? Something containing perhaps the row index and the column index ... Then you could just select it directly.

Categories

Resources