get value from localStorage and append it to class - javascript

I'm messing around with setting data into localStorage, but I'm trying to extract a value and have it populate into an empty span on a specific page load.
This is what I've been messing with, but I'm not sure if this is the correct way to go about it:
if($(".body-class-name").length > 0){
$('.title span').append($(localStorage.getItem("first_name")));
}
The only other examples I've tried to work with deal with external JSON data and that's a little too much for what I'm trying to work with.

The code does what it is suppose to. You could improve abit.
if($(".body-class-name").length > 0){
var firstname = $(localStorage.getItem("first_name");
if (firstname) {
$('#title-text').text(firstname));
}
}
Then there is some missing context in your post. But i would also look at:
Using text instead of append if you don\t want to keep append firstnames to that span.
And as others mentioned in comments be aware of your selector. I changed it to query for an ID instead.

if ( $ ( ".body-class-name" ). length > 0 ){
$ ( '.title span' ). append ( localStorage . getItem ( "first_name" )); }
The $() isn't needed around the localStorage.getItem()

You don't need using load event.
Load event is for assets files, you can use ready event.
In basically jQuery code run after document ready.
You just need to wrap with function, For example:
<h1 class="title">Hello again <span>User</span></h1>
<br/>
<label>
Enter your name here:
<input name="firstname" />
</label>
<script>
(function($){
$("input[name='firstname']").change(function(){
// Store
localStorage.setItem("first_name", $(this).val() );
});
// Load store
$('.title span').text( localStorage.getItem( "first_name" ) );
})(jQuery);
</script>
Live code here

Related

How can I getting textarea value using javascript and ckeditor4 [duplicate]

I'm a learner as far as JS goes and although I've spent a good few hours reading through tutorials which has helped lots but I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
What I'm trying to do is have it so that when someone types into the textarea, whatever they type appears in a div in a different part of the page.
I've got a simple text input doing that just fine but because the text area is a ckEditor the similar code doesn't work.
I know the answer is here: ckEditor API textarea value but I don't know enough to figure out what I'm meant to do. I don't suppose anyone fancies helping me out?
The code I've got working is:
$('#CampaignTitle').bind("propertychange input", function() {
$('#titleBar').text(this.value);
});
and
<label for="CampaignTitle">Title</label>
<input name="data[Campaign][title]" type="text" id="CampaignTitle" />
and
<div id="titleBar" style="max-width:960px; max-height:76px;"></div>
I'm still having problems figuring out exactly how I find out what a
user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article:
http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id of element assigned the editor.
You could integrate a function on JQuery
jQuery.fn.CKEditorValFor = function( element_id ){
return CKEDITOR.instances[element_id].getData();
}
and passing as a parameter the ckeditor element id
var campaign_title_value = $().CKEditorValFor('CampaignTitle');
i found following code working for ckeditor 5
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.model.document.on( 'change:data', () => {
editorData = editor.getData();
} );
} )
.catch( error => {
console.error( error );
} );
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
you can add the following code :
the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

jQuery: children count = 0 and ajax

I'm working on a jQuery that gets a list of elements from a server, appends it to an element, and then loops in the newly appended elements to transform them (make them jEditable).
I'm having trouble with the loop. The appending works alright, so I have a list of elements like :
<div id="innerModal">
<label id="exampleTitle">Title :</label>
<label id="exampleField" class="ftext">Value</label>
</div>
Then I try to loop in:
function makeListEditable(element, type){
//I checked here that the element sent is well '#innerModal'
alert($(element).children().length);
$(element).children().each(function() {
if( $( this ).is( 'ftext' ) ){
makeEditable( $( this ), type, '', '' );
}
});
}
The alert prints "0".
Where does that issue come from? How can I fix it?
Edit : Here's the call of makeListEditable :
getFormOnElement(//Gets the form and appends it
"getorganisationeditable/"+curOId,
"#innerModal"
);
makeListEditable('#innerModal');
Thanks in advance!
Since ajax is asynchronous, it will not wait till elements are appended and execute makeEditable. Since ajax might not necessarily have completed, the element has no children. Move makeEditable to ajax call's success callback
ftext is a class and needs 'dot' .is(".ftext")
Add an other allert like:
alert($(element).text());
or
alert($(element).html());
so you can know if your selector work fine.

Getting the textarea value of a ckeditor textarea with javascript

I'm a learner as far as JS goes and although I've spent a good few hours reading through tutorials which has helped lots but I'm still having problems figuring out exactly how I find out what a user is typing into a ckeditor textarea.
What I'm trying to do is have it so that when someone types into the textarea, whatever they type appears in a div in a different part of the page.
I've got a simple text input doing that just fine but because the text area is a ckEditor the similar code doesn't work.
I know the answer is here: ckEditor API textarea value but I don't know enough to figure out what I'm meant to do. I don't suppose anyone fancies helping me out?
The code I've got working is:
$('#CampaignTitle').bind("propertychange input", function() {
$('#titleBar').text(this.value);
});
and
<label for="CampaignTitle">Title</label>
<input name="data[Campaign][title]" type="text" id="CampaignTitle" />
and
<div id="titleBar" style="max-width:960px; max-height:76px;"></div>
I'm still having problems figuring out exactly how I find out what a
user is typing into a ckeditor textarea.
Ok, this is fairly easy. Assuming your editor is named "editor1", this will give you an alert with your its contents:
alert(CKEDITOR.instances.editor1.getData());
The harder part is detecting when the user types. From what I can tell, there isn't actually support to do that (and I'm not too impressed with the documentation btw). See this article:
http://alfonsoml.blogspot.com/2011/03/onchange-event-for-ckeditor.html
Instead, I would suggest setting a timer that is going to continuously update your second div with the value of the textarea:
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
This seems to work just fine. Here's the entire thing for clarity:
<textarea id="editor1" name="editor1">This is sample text</textarea>
<div id="trackingDiv" ></div>
<script type="text/javascript">
CKEDITOR.replace( 'editor1' );
timer = setInterval(updateDiv,100);
function updateDiv(){
var editorText = CKEDITOR.instances.editor1.getData();
$('#trackingDiv').html(editorText);
}
</script>
At least as of CKEDITOR 4.4.5, you can set up a listener for every change to the editor's contents, rather than running a timer:
CKEDITOR.on("instanceCreated", function(event) {
event.editor.on("change", function () {
$("#trackingDiv").html(event.editor.getData());
});
});
I realize this may be too late for the OP, and doesn't show as the correct answer or have any votes (yet), but I thought I'd update the post for future readers.
Simply execute
CKEDITOR.instances[elementId].getData();
with element id = id of element assigned the editor.
You could integrate a function on JQuery
jQuery.fn.CKEditorValFor = function( element_id ){
return CKEDITOR.instances[element_id].getData();
}
and passing as a parameter the ckeditor element id
var campaign_title_value = $().CKEditorValFor('CampaignTitle');
i found following code working for ckeditor 5
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then( editor => {
editor.model.document.on( 'change:data', () => {
editorData = editor.getData();
} );
} )
.catch( error => {
console.error( error );
} );
Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:
$("#CampaignTitle").bind("keyup", function()
{
$("#titleBar").text($(this).val());
});
If you really wanted a textarea change your input type text to this
<textarea id="CampaignTitle"></textarea>
Hope it helps.
you can add the following code :
the ckeditor field data will be stored in $('#ELEMENT_ID').val() via each click. I've used the method and it works very well. ckeditor field data will be saved realtime and will be ready for sending.
$().click(function(){
$('#ELEMENT_ID').val(CKEDITOR.instances['ELEMENT_ID'].getData());
});
var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

javascript & jquery optimization question

I am creating a website that's being localized through JavaScript, however... I have alot of pages and in each page there are alot of text inputs items, I am using this plugin
http://code.google.com/p/jquery-watermark/
to apply watermark on my inputs, now I just need guides for better performance.
Shall all watermarks be in one javascript file, or each page shall have it's own watermarks in it's own javascript file?
Shall i create one JavaScript file having all the system $(object).watermark() (I am choosing objects by classes), or each page with it's own JavaScript file must contain the jQuery watermark line of code?
TBH I wouldn't do it this way. I would apply the watermarks (or placeholders as they're known) in the HTML, like so:
<input type="text" placeholder="Hello mum!" />
And I would then use jQuery and Moderizer to determine if the current browser supports placeholders or not. If it does, you don't need to worry as the hard work's been done. If it doesn't, you can use a script like this:
if ( !Modernizr.input.placeholder )
{
$( '[placeholder]' ).focus( function()
{
var i = $( this );
if ( i.val() === i.attr( 'placeholder' ) )
{
i.val( '' );
}
}).blur( function()
{
var i = $( this );
if ( i.val() === '' )
{
i.val( i.attr( 'placeholder' ) );
}
}).blur();
}
This script essentially checks to see if the user has clicked into the input or not. If they have, it removes the placeholder as text. If they leave the input and they've left text in there, it doesn't change anything. However, if the input is empty, it then fills it with the placeholder.
I hope that helps.
General: normally you would have page specific things in a page specific javascript.
Your Problem;
assuming your html looks something like this;
<input type='text' name='bla'></input>
You could rewrite it to read;
<input type='text' name='email' class='watermark' data-watertype='email'></input>
You could apply a single javascript snippet and inlcude it throughout the page;
var texts={ "email":"Please enter a valid email address", .... },
elems=jQuery("input.watermark"),
elem,
watermarkType;
elems.each(function(i,elem){
elem=jQuery(elem);
watermarkType = texts[ elem.attr("data-watertype") ] || "";
if (watermarkType.length!==0){
//apply the watermark
elem.watermark(watermarkType);
}
}
//this isn't tested but should work as expected!
thus resolving the need of having a specific javascript for each page to apply the watermarks

Why is query failing in IE only

My query works great, but then I check it on IE and it is a disaster. I am wondering if it is the parent part of the code. The parents are trying to reach the first <table> containing the info. Is there an easier way to get to the table directly?
<script>
if ($('b:contains("Choose a sub category:")').length > 0) {
var newSubnav = document.createElement( 'ul' );
$(newSubnav).addClass("sub_categories_holder");
$('b:contains("Choose a sub category:")').parent().parent().parent().parent().parent().parent().parent().prepend( newSubnav );
$('a.subcategory_link').appendTo($('ul.sub_categories_holder'));
$('a.subcategory_link').wrap("<li class='sub_categories'></li>");
$('li.sub_categories').before("<li class='sub_categories_divider'></li>");
$("li.sub_categories_divider:eq(0)").remove();
$("b:contains('Choose a sub category:')").parent().parent().parent().parent().parent().remove();
$("img[src='/v/vspfiles/templates/GFAR NEW NAV/images/Bullet_SubCategory.gif']").remove();
$("td.colors_backgroundneutral").css("background-color","transparent");
$("td.colors_backgroundneutral").children(':first-child').attr("cellpadding","0");
};
</script>
Unless you provide your markup(at least a dummy one) it's all guess that you are gonna get.
Instead of .parent().parent().parent().parent().parent().parent().parent().prepend( newSubnav ); check if you can use .parents(). This will return you the parents all the way up to HTML. You can even use selectors as parents(selector) to filter. Read more on the jquery api page.
Since you are using jQuery, you can use $("ul") instead of document.createElement("ul")

Categories

Resources