i'm working on a text editor as part of a school project and i'm having a small issue with my save and open code.
Here are my buttons:
<button id="gu" onclick="save()">Save</button>
<button id="ab" onclick="open()">Open</button>
Here's my textarea:
<textarea name="comment" rows=30 cols=101 id="texto"></textarea>
And here's my javascript functions:
function save(){
gu = document.getElementById("texto");
localStorage.setItem("texto",gu);
console.log(texto+"="+gu);
}
function open(){
console.log("Abierto")
document.getElementById('texto').innerHTML=gu;
}
My goal is that if write something and then press the "save" button, the content inside my textarea is saved, and if i press the "open" button it shows what i wrote on the textarea.
Any idea on how to fix my code?
Sorry if my english is bad.
Here you go: https://jsfiddle.net/cinerobert/qwgv18r5/
function save()
{
localStorage.setItem("someitem", document.getElementById("texto").value);
document.getElementById("texto").value = "";
console.log(texto + "=" + gu);
}
function retrieve(){
console.log("Abierto")
document.getElementById("texto").value = localStorage.getItem("someitem");
}
You can't use open() as a function name because it's already a built-in function in javascript, so I changed it to retrieve(). See here: http://www.w3schools.com/jsref/met_win_open.asp
Is there some reason you're required to use setItem()? Using a variable (gu) and setItem is redundant. It would work either way.
Also to get and set the text inside a text area I you need to use value().
I also changed the save() function so that it clears the textbox, so that you can see something happen when you click retrieve().
Below are the things need to be done
function save()
{
gu = document.getElementById("texto");
localStorage.setItem("texto",gu.innerText); //here you were saving the dom object not the text inside
console.log(texto+"="+gu.innerHTML);
}
function open()
{
console.log("Abierto")
document.getElementById('texto').innerHTML=localStorage.getItem("texto"); //here you need to get the text from your local storage
}
Related
To prevent answers like: 'is the JavaScript file loaded?' -> Yes, it is loaded, at the footer part of the page! I have checked that with a simple message to the console, which is displayed!
But:
I've got a page with a button:
<button id="portfolio-posts-btn">Load portfolio related blog posts</button>
And a file main.js:
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
The text the button was clicked! should be displayed in the console, but it stays empty!
Apparently, the button click is not recognized, and thus, the var portfolioPostsBtn is false, or NULL... -> the method addEventListener() is not fired ?
I don't see the cause for this; I checked the spelling, should I use single or double quotes? Please help?
Thank you!
I've had this happen to me before, since theres two ways to do this I just used the other.
The first is onclick="function()", this is used as an attribute inside the element. Ex:
function clicked(){
alert("button clicked");
}
<button onclick="clicked();">Press me</button>
exaplaination: When you add this attribute to this element and I do believe some others when the button is clicked the specified code inside the quotes of the attibute will run. It doesn't have to be a number, e.g. onclick="alert(12+4/2);". But this is more of HTML than JavaScript using this version
The other way is using what you've got which (to me) is a lot more difficult then it needs to be. Heres my example
var b = document.getElementById("btn");
b.addEventListener("click", blogged);
function blogged(){
alert("this post has been blogged");
}
<button id="btn">Blog it</button>
This side of things has more to do with JavaScript and Event listeners. But the problem with you're code is that you're putting the event listener after you call the if statement. Here's my solution
var portfolioPostsBtn = document.getElementById('portfolio-posts-btn');
portfolioPostsBtn.addEventListener("click", function(){
check();
});
function check(){
if(portfolioPostsBtn){
console.log("posted");
}
}
<button id="portfolio-posts-btn">press this to post<button>
Presumably you have made a decision not to use jQuery. You'll need to wrap your code in an event listener so that the code is executed when the DOM is ready.
document.addEventListener("DOMContentLoaded", function(event) {
var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
if (portfolioPostsBtn) {
portfolioPostsBtn.addEventListener("click", function () {
console.log("the button was clicked!");
});
}
});
The answer is found in the uploading of the file page-portfolio.php!
I found out that the id="portfolio-posts-btn", added later, was not updated - could be my mistake, or the SFTP upload extension in Brackets - I did not see an error message!
Anyway, the issue is solved!
One more question: "are there methods to check if an id exists?". That could make live easier!
All contributors, thank you for your answers!
Here I want to trap and alert or echo the value of var thisCount
The problem is I can't display the value.I'd tried many ways but no luck.
$(document).on("click", ".open-dialog", function () {
var thisCount = $(this).data('count');
//this place the code
$(".modal-body #count").val( thisCount);
});
Your question doesn't really clarified what you've tried or where you want the value displayed, but common answers are:
1) Console. This will output to your browsers log.
console.log(thisCount);
2) If you want to put it into an HTML tag, you can use classic javascript
document.getElementById('yourTagsId').innerHTML += thisCount;
// You can use = instead of += as well
3) You could also use an alert or a confirm
alert(thisCount);
confirm(thisCount, function(){return true;});
// confirm takes both a displayed value, and a function which will be performed when the user presses the 'Ok' button
If you need ah dataattribute like this below .alert console.log both are working
$(document).on("click", ".open-dialog", function () {
var thisCount = $(this).data('count');
$("#count").val( thisCount);
console.log(thisCount)
alert(thisCount)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="open-dialog" data-count="hello">click</button>
<input type="text" id="count">
Maybe you should verify if the jquery library is properly imported
Also, you can use the Chrome Developer tools (Ctrl +Shift+ i) and verify the value in the javascript console. Just to see if you can see the value in the debugger.
I'm using a modal, the thing is that I want to change the value of an input field based on it. If modal is open value is "Update" when the modal is not displayed, the value is "create".
I tried like this but since it is executed only one time on page load it's not what I want.
if (($("element").data('bs.modal') || {}).isShown) {
$('#action-description').val('Update');
} else {
$('#action-description').val('Create');
}
And the input field:
<input type="text" id="action-description" name="action-description" value="">
I need to make something on change so I also tried like this:
$('#modalElement').on('hidden', function(){
$('#action-description').val('Create');
});
But I can't make it work!
Your logic is correct. You can just convert it to a function and open the modal using jquery only.
So, write a function as:
function openModal(){
$('#myModal').modal('show');
if (($("element").data('bs.modal') || {}).isShown) {
$('#action-description').val('Update');
}
}
Also you can write a similar function to close the modal on clicking cross or cancel button(if you have any)
function closeModal(){
$('#myModal').modal('hide');
$('#action-description').val('Create');
}
I had a more complicated form working a couple of days ago, but suddenly it stopped working and I'm rubbish at saving versions, so I've taken it right back to basics, and I can't get it to work. What am I doing wrong? Am I using onInput incorrectly?
<input type="text" id="number-of-copies-value" onInput="quote()" value="500">
<span id="total-cost-value">0.00</span>
And here's the Javascript:
function quote() {
var totalcostvalue = document.getElementById("total-cost-value");
var numberofcopiesvalue = document.getElementById("number-of-copies-value").value;
var totalcost = (+numberofcopiesvalue);
totalcostvalue.innerHTML=totalcost.toFixed(2);
}
quote();
https://jsfiddle.net/tod0wusv/1/
Your HTML expects the quote() function to be globally available. Make sure that is the case.
If I change your fiddle to have quote() available on global window object like,
window.quote = function quote() {
// ...
};
the fiddle starts working again.
WORKING FIDDLE
If I create a local HTML file with your content, it works right away, which makes sense since quote() is defined on global scope.
Looks like JSfiddle executes the JavaScript in a function scope which breaks your quote() call.
If you care about browser compatibility I would suggest using the onkeydown event with a setTimeout function as described here Detecting "value" of input text field after a keydown event in the text field?
To make this work in JSFiddle, change the javascript "load type" setting in your JavaScript settings to one of the "no wrap" options.
HTML
<input type="text" id="number-of-copies-value" onkeydown="window.setTimeout(function() { quote(); }, 1)" value="500">
<span id="total-cost-value">0.00</span>
JavaScript:
function quote() {
var totalcostvalue = document.getElementById("total-cost-value");
var numberofcopiesvalue = document.getElementById("number-of-copies-value").value;
var totalcost = (+numberofcopiesvalue);
totalcostvalue.innerHTML = totalcost.toFixed(2);
}
quote();
I've updated your JSFiddle...
https://jsfiddle.net/tod0wusv/6/
I'm trying to call a js function when a button is clicked in html, but it won't run. The button is being clicked, because I tested a prompt and it showed up, but when we put a function there it wont run...
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = <c:outvalue= "${lesson.GetNextLesson()}"/>";}
Then I call the method in a button
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next"/>
We've found that when a function gives an error, javascript declares the entire function as dead, but I don't know the error
This works:
You had a couple syntax issues that was killing your function- including not completely wrapping your innerHTML content in quotes - and your Button element was not using the correct syntax.
<p style="font-size: 4em" id ="Kek23"></p>
<button onclick = "NextLesson();" value = "Next">Next</button>
<script>
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= ${lesson.GetNextLesson()}/>"
};
</script>
Fiddle
Errors corrected in the 2nd line of function:
function NextLesson(){
prompt("myprompt");
document.getElementById("Kek23").innerHTML = "<c:out value= '${lesson.GetNextLesson()}'/>";
}