Local Storage error - javascript

Please someone tell me what is the problem in the code which i have written.
Js
$("button").click(function() {
document.getElementById("demo").innerHTML = document.getElementById("asd").value;
});
$(function() {
var edit = document.getElementById('demo');
$(edit).blur(function() {
localStorage.setItem("data1", this.innerHTML)
});
if (localStorage.getItem("data1")) {
edit.innerHTML = localStorage.getItem("data1");
}
});
Html
<input type="text" id="asd">
<button>asdsad</button>
<p id="demo"></p>
But the same code is working perfectly in this:
Js
$(function() {
var edit = document.getElementById('demo');
$(edit).blur(function() {
localStorage.setItem("data1", document.getElementById("demo").innerHTML)
});
if (localStorage.getItem("data1")) {
edit.innerHTML = localStorage.getItem("data1");
}
});
HTML
<div contenteditable="true" id="demo">Some text here</div>
Please some one tell me what went wrong here.

When you pass the edit variable (which contains a DOM element) into jQuery as an argument, a jQuery object is returned. That changes the scope of this inside your blur event to a jQuery object. jQuery doesn't have a property of innerHTML, so it returns undefined. JavaScript DOM elements do have an innerHTML property of course, so that's why the second example works.
One way to fix your first example is to replace this:
$(edit).blur(function() {
localStorage.setItem("data1", this.innerHTML)
});
With this:
$(edit).blur(function() {
localStorage.setItem("data1", $(this).html());
});

Related

onclick generates invalid function

I have a variable that is attached to a function. I am trying to use that variable in an onclick event.
This is what I am doing
var show = function() {
console.log("hello");
};
$(container).append(
"<div class='info' onclick=" + show + ">Show</div>"
);
However the generated html comes out like this
<div class="info" onclick="function()" {="" console.log("hello");="" }="">
Show
</div>
Any idea how I can fix this so that when I click the div my function gets called ?
You can simply do like this, Just make show a function and call it on click.
This will work
<script>
function show() {
console.log("hello");
}
$(container).append(
'<div class="info" onclick="show()">Show</div>'
);
</script>
This is kind of an unusual approach to what you're trying to do. I think it would be more idiomatic in jQuery to either
a) define the element first, with event handler, and then append it,
$("<div>Show</div>", {
"class": "info",
on: {
click: function(e) {
console.log("Hello");
}
}
}).appendTo($(container));
or
b) append a new element and then add an event handler to it after appending it.
$(container).append("<div class='info'>Show</div>");
$(container).children('.info').last().on('click', function(e) { console.log("Hello"); });
Between those two, I'd recommend the first in this case.
The variable show is a function, Then how can you bind it with string?
The code should be like,
$(container).append("<div class='info' onClick='show()'>Show</div>");
try using :
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick="+'show()'+">Show</div>");
This will work.
The reason why your code
var show = function() {
console.log("hello");
};
$(container).append("<div class='info' onclick=" + show + ">Show</div>");
was not working as required as show is an object of type function, so when one uses the function name without the () the variable is replaced bu the code that it consists.
Hope it helps.

jQuery nested functions

I am still new to JavaScript and jQuery, so I am confused as to why the following code is not working as I anticipated. All I am trying to do is save input on a button click (id=recordInput) and display it with another button click (id=displayInput). What I observe is that tempInput is stored, (the code works until that point) but assignment of displayInputs onclick attribute is not executed. My question is, can you not nest a $().click() call inside of another &().click() call?
<script>
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
</script>
My thinking is this in pseudocode:
assign recordInput onclick attribute to the following function:
store tempInput
set displayInput onclick to alert the tempInput value
what is wrong with my thinking?
NOTE: I did not include any html tags but all of the ids are referenced correctly
It's not working because you have put & instead of $ here
$('#displayInput').click(function(event) {
Fixing this may work, but you shouldn't set event handlers this way. Because every time your first handler function is called it will set an event handler for the second one. You can try with your console.log and you will see that the number of console.log is increasing by every click on #recordInput. So you should better set it like this :
var tempInput;
$('#recordInput').click(function(event) {
tempInput = $('#testInput').val();
});
$('#displayInput').click(function(event) {
console.log(tempInput);
});
I would change
$(document).ready(function () {
$('#recordInput').click(function(event) {
var tempInput = $('#testInput').val();
&('#displayInput').click(function(event) {
console.log(tempInput);
});
});
});
to
$(function(){
var testInput = '';
$('#recordInput').click(function(){
testInput = $('#testInput').val();
});
$('#displayInput').click(function(){
if(testInput !== ''){
console.log(testInput);
}
});
});
You are using & instead of $. Of course, you don't have to format the code exactly like I did.

Two plugins in a textarea

I need to use two plug-ins in one element on my page. I've never needed to do this and tried as it is in the code below. Most did not work!
<script type="text/javascript">
$(document).ready(function()
{
var wbbOpt = {buttons: "bold,italic,underline,|,img,link,|,code,quote"}
// plugin one wysibb
$("#editor").wysibb(wbbOpt);
// plugin two hashtags
$("#editor").hashtags();
//the two plugin worked in textarea #editor
});
</script>
Can anyone help me? Thank you.
So you can't use them because each of them take control and wrap the textarea. Since the editor is the most complex of the two the best thing to do is to take the code of the hashtag and adapt it at your need.
So here's a working example, but if you want you can trigger the function I use to the change event (adding it) or some way else
<div id="higlighter" style="width;1217px;"></div>
<textarea id="editor"></textarea>
<br />
<input id="btn" type="button" value="HASH">
<br />
$(document).ready(function() {
var wbbOpt = {
buttons: "bold,italic,underline,|,img,link,|,code,quote"
};
$("#editor").wysibb(wbbOpt);
$('#btn').click(function () { report() });
});
function report() {
$("#hashtag").val($("#editor").htmlcode());
var str = $("#editor").htmlcode();
str = str.replace(/\n/g, '<br>');
if(!str.match(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?#([a-zA-Z0-9]+)/g)) {
if(!str.match(/#([a-zA-Z0-9]+)#/g)) {
str = str.replace(/#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}else{
str = str.replace(/#([a-zA-Z0-9]+)#([a-zA-Z0-9]+)/g,'<span class="hashtag2">#$1</span>');
}
}
$("#editor").htmlcode(str);
}
you can check a working code here on jsfiddle.
http://jsfiddle.net/4kj7d6mh/2/
You can type your text and use the editor, and when you want to higlight the hastag you click the button. If you want that to happen automatically you have to change this line:
$('#btn').click(function () { report() });
And attach the function to the keypress for example (experiment a bit)

jQuery button takes value from input and do an action - how does it works?

I've got a small piece of code here
<label for="pass">Password</label>
<input type="text" id="pass" value="QWERTY">
<button for="pass">Submit!</button>
and jquery action
$("button").click(function(){
var value=$("input[id=pass]").attr("value");
if (value==="QWERTY"){
alert("Good!");
};
and it doesnt work. Do you know how to fix it?
Try this.
$("button").click(function(){
var value=$("input#pass").val();
if ( value === "QWERTY"){
alert("Good!");
}
});
jQuery has it's own built in function for fetching values from input fields.
You should prevent the default action from triggering when the button is clicked (otherwise the form will be submitted, and the JS will not execute). You should also use val() when accessing an input's value.
You should also wrap your code inside the DOMReady handler, to ensure that the DOM is accessible when your script is run.
Here's an updated version of your code:
$(function() {
$("button").click(function(e) {
e.preventDefault();
var the_value = $("#pass").val();
if(value == "QWERTY")
{
alert("Good!");
}
};
});
Try this : It's more optimized...
$("button").click(function(e){
e.preventDefault();
var value=$("#pass")[0].value;
if (value==="QWERTY"){
alert("Good!");
};
You can also remove the "for" attribute on the button, it's non correct ;)
Your code should work if you don't forget the }); at last and have put the code into dom ready callback function. The demo.
And you could write it like below:
$("button").click(function(){
if ($('#pass').val()==="QWERTY"){
alert("Good!");
};
});
I think you just have a syntax error. You need to make sure you close your function curly brace and your click close paren.
$("document").ready(function () {
$("button").click(function () {
var value = $("input[id=pass]").attr("value");
if (value === "QWERTY") {
alert("Good!");
}
});
});
Example:
http://jsfiddle.net/pandaPowder/5VjeD/3/

Why is my element null?

Why when I do an alert of the value (see below) it returns null? When an element with that ID exists?
// make reference to divs
var countdown_timer = document.getElementById("countdown_timer");
var countdown_image = document.getElementById("countdown_image");
// For element manipulation
if (type == 'image') {
var element = countdown_image;
} else if (type == 'timer') {
var element = countdown_timer;
}
alert(countdown_timer);
The div is as below..
<div class="timer" id="countdown_timer"></div>
It's possible that the javascript is being executed before the elements on your page are not loaded, thus the selector isn't finding anything. Is your javascript above the <body> tag? Try putting it after </body> and see how that works for you.
Another solution is to do:
window.onload = function () {
//put all your JS here
}
onload = function() {
// put you code here
}
Your call to document.getElementById needs to be after the markup for the div.
<div class="timer" id="countdown_timer"></div>
<script type="text/javascript">
var countdown_timer = document.getElementById("countdown_timer");
...
</script>
Alternatively, you could use the window.onload event, which would be the better way to go.

Categories

Resources