I am using this codepen https://codepen.io/ravitadi/pen/CsIFL and I would like to add another field for the user to input a title for the note.
I am a javascript noobie and I can't seem to get it right. This is the function for adding notes. The full script is in the codepen.
function addNote(){
var usrInput = $('.txtBox').val();
//console.log(usrInput);
if(usrInput.length > 0){
console.log($(this));
$('#').removeClass('ntActv');
addtoSticky(usrInput);
cnclOvrly();
//console.log(notes);
}else{
}
}
function addtoSticky(note){
if(note.length > 0){
console.log(note);
createSticky(note);
localStorage.setItem('note_'+note.length, note);
}
}
function createSticky(text){
$('#stkyNts').append('<li class="box">'+text+'</li>');
}
Any help is highly appreciated.
Codepen
I tried to update following your requirement.
You should change way to save object and load object from localstorage.
storedNotes = JSON.parse(localStorage.getItem("notes"));
if(current == null) current = [];
current.push(JSON.stringify(note));
localStorage.setItem('notes', JSON.stringify(current));
https://codepen.io/viethien/pen/RdqKxM
In the modal, add another text box for title before the textarea.
<!-- add this -->
<input type="text" id="title" />
<!-- /add this -->
<textarea class="txtBox"></textarea>
Now you have to grab the value from the title. In the createSticky() function:
function createSticky(text) {
var heading = $("#title").val();
$('#stkyNts').append('<li class="box"><h3>' + heading + '</h3>'+text+'</li>');
}
And there you go:
For the extended functionality, try to change the way, heading is included in the local storage while setting and getting it. For doing so, you need to include the heading in the functions addtoSticky() and getStoredNotes().
Related
I have a main page with a popup window.
<textarea class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
There is also a second page. (/conclusion/main)
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
I enter the text in the window and send. The window should close and the text should be sent to the second page and the text should be saved in the field "textarea". Even if they close the page or reload, the text should remain in the second page.
This code allows you to save, but after closing the page, does not save
(function(){
var textarea = document.getElementById('retro');
if (localStorage.retro)
{
textarea.value = localStorage.retro;
}
textarea.onchange = function()
{
localStorage.retro = this.value;
}
})();
Sends from the first page to the second
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params2;
}
params = getParams();
name = unescape(params["name"]);
document.getElementById('retro').innerHTML = name;
There are some questions around what you are trying to do here. What I have done is broken this down into 2 parts
Passing the local storage between 2 pages and accessing it.
Decoding Parameters in the URL and assigning them
Some assumptions that I made:
I have noticed some of the classes from bootstrap so i assume that you have jQuery on the page and also you may know how to use it.
Using chrome for testing this
PART 1 - Passing localstorage between windows:
First thing to note is you may be better using a cookie library (js-cookie) or creating one yourself that you can access. As localstorage may well be insecure depending on what data you want to store in there.
With that out of the way, you were on the right track, just needed to add your event listener to 'input' as i think then every keystroke the data in local storage is being updated.
Page 1
HTML
<textarea id="retro" class="form-control item"></textarea>
<button type="button" class="btn btn-primary" name="name">Send</button>
JS (I would recommend place this at the bottom of you page for quick testing)
<script type="text/javascript">
var textarea = document.getElementById('retro');
textarea.addEventListener('input',function(){
localStorage.setItem('retro', this.value);
})
</script>
In Chrome developer tools if you watch the variable 'localstorage' then you will see this change as you key in the value.
What I have done here is bound the event listener to the text area so that any 'input' the value changes, furthermore is am setting the item in the localstorage
PAGE 2
HTML
<textarea id="retro" style="height: 200px; width: 800px"></textarea>
JS
<script type="text/javascript">
var textarea = document.getElementById('retro').value = localStorage.getItem('retro');
</script>
Here using the 'getItem' method for localstorage you can then retrieve it from the storage area and output it as the value of the textarea.
Obviously is the cache or localstorage is cleared then this value will disappear.
PART 2 - Decoding Parameters in the URL and assigning them
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^]*)').exec(window.location.href);
if (results==null){
return null;
}
else{
return results[1] || 0;
}
}
This function above will get you any parameter you want form the url I found this from here. This is using jQuery.
Here is how you would use it
// example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
Well I hope this answers your question on both parts, and helps you further, please add any comments if I have missed anything and I will be happy to update my answer
I'm trying to collect user responses and add them into the answers array. Then I want to display the most recent user input (answers[0]) into the .user-answer div. I've managed to get that part taken care of but if you see a better way to do it then please show me.
The second part of is that I want to show the items in the array one at a time in the .dynamic-content h2 slot. I need to loop through the array (starting at answers[0]), pull out each item, show it in the div and then move to the next item and show it in the div.
Here's a link to the CodePen.
HTML
<div class="answer">
<h1>Life, Liberty, and </h1>
</div>
<div class="user-answer">
<h1>_________</h1>
</div>
<input type="text"/>
<input type="submit"/>
<div class="dynamic-content">
<h1>What is your pursuit of happiness?</h1>
<h2>Output array items here</h2>
</div>
JavaScript
// create an empty array
var answers = [];
// STORE AND OUTPUT DATA ON SUBMISSION
function handleUserInput() {
// store user input
var userInput = $('input[type=text]').val();
// append input value to answers array
answers.unshift(userInput);
// add latest user input into the HTML
$('.user-answer').html('<h1>' + answers[0] + '</h1>');
}
// RUN FUNCTION ON SUBMISSION
$('input[type=submit]').on('click', function() {
handleUserInput();
});
It's not the best way but here it goes. This method is like you asked to change the SAME DIV dynamically, so no other items are created, they just "change"
Add this function:
function rotateTerm() {
if(answers.length>0){
var ct = $("#rotate").data("term") || 0;
$("#rotate").data("term", ct == answers.length -1 ? 0 : ct + 1).text(answers[ct]).fadeIn().delay(2000).fadeOut(200,function(){
rotateTerm();
});
}
}
$(rotateTerm);
Then in your submission put:
$('input[type=submit]').on('click', function() {
handleUserInput();
$(rotateTerm);
});
working CodePen thanks to Nick Craver's answer in this thread.
Just change your JS a little bit to this:
var answers = []; // create an empty array
// STORE DATA ON SUBMISSION
function handleUserInput() {
var userInput = $('input[type=text]').val();
$('.user-answer').html('<h1>' + userInput + '</h1>');
answers.push(userInput);
$('.dynamic-content h2').html(answers + ', ');
}
$('input[type=submit]').on('click', function() {
handleUserInput();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="answer">
<h1>Life, Liberty, and </h1>
</div>
<div class="user-answer">
<h1>_________</h1>
</div>
<input type="text"/>
<input type="submit"/>
<div class="dynamic-content">
<h1>What is your pursuit of happiness?</h1>
<h2>Output array items here</h2>
</div>
First, I don't know if you want to do this on server side or in client side, but for server side you need to make it work with a server side scripting language, like PHP, or Perl. For clent side, you need to cancel the default submit event when user clicks the submit button, else the page will refresh posting the form data.
So, to do this without the page refreshing, first add the event to the onclick event and pass it to your handleUserInput function like this:
$('input[type=submit]').on('click', function(e) {
handleUserInput(e);
rotate();
});
then, cancel the event by using preventDefault to the event object:
e.preventDefault();
now, to display the data to .dynamic-content and add the answers in h2 tags, you first need to remove all h2 elements (because you already have an h2 element there, or you could also prepend if you remove the h2 Output array items here tag) and then add all the answers starting from the first one like this:
$('.dynamic-content h2').remove();
$.each(answers, function(i, v) {
$('.dynamic-content').append($('<h2/>').text(v));
});
The final code will be something like this:
var answers = []; // create an empty array
// STORE DATA ON SUBMISSION
function handleUserInput(e) {
e.preventDefault();
var userInput = $('input[type=text]').val(); // store user input
answers.unshift(userInput); // append value to answers array
// $('.user-answer').fadeIn().html('<h1>' + answers[0] + '</h1>').delay( 500 ).fadeOut(); // add user input into the HTML
$('.user-answer').html('<h1>' + answers[0] + '</h1>'); // add user input into the HTML
$('.dynamic-content h2').remove();
$.each(answers, function(i, v) {
$('.dynamic-content').append($('<h2/>').text(v));
});
// $('.answer').html('<h1>' + answers[0] + '</h1>');
// $.each(answers[0 + i], function() {
// $('.answer').fadeIn().html('<h1>' + answers + '</h1>').delay( 500 ).fadeOut();
// });
}
$('input[type=submit]').on('click', function(e) {
handleUserInput(e);
rotate();
});
http://codepen.io/clytras/pen/zoBXpE
I am trying to load a HTML page into a variable in Jquery, then replace a div element tag in it, so I can get my own id into the div. I am using this way to dynamically add more users in my web app, and then do a batch POST to the back end, and put the info into json.
Here is my html that I am loading.
info.html
<div id="user">
<label>name</label>
<input type="text" name="name">
<br>
<label>email</label>
<input type="text" name="email">
<br>
</div>
I load this with jquery and I want to replace <div id="user"> with something
like <div id="user 1">
I have the following jquery script that has a counter to keep track of what number to append onto the div tag.
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
var content = $('<div>').load("static/info.html"); //using python flask
console.log(typeof(content)); //is of object type
console.log(typeof(content.html())); //is of type string
console.log(content.html());//shows up as an empty string
console.log(content);//prints out the object
content = content.html().replace('<div id="user ">','<div id="user "'+counter+'>'); // doesn't work.
$("#add_div").append(content); //appends correctly if I remove the above line, but all divs have the some id.
});
});
Any suggestions would be great thanks. Also, is the is the best way going about keeping track of how many times a new user is added(as in using a counter and keep track of how they are added, and then do the same when I click submit and create the json)?
.load() is asynchronous. make your changes in side callback.
.load("..",function(){
// your changes
});
Also $( "selector" ).load() is the syntax. So create a div and load content to it.
// modified code structure
<div id"content"></div>
$(document).ready(function(){
var make_counter = (function(){
var count = 0;
return function(){
count++;
return count;
};
});
var _counter = make_counter();
$("#add").click(function(){
var counter = _counter();
$("#content").load("static/info.html",function(){
content = $("#content").html().replace('<div id="user ">','<div id="user "'+counter+'>');
$("#add_div").append(content);
}); //using python flask
});
});
Using JavaScript, you can use the .attr() method to target id, then set its value like so:
$("#content").attr("id", "user_" + counter);
Try an $.each() function for #user like this:
$('#user').each(function(indexNumber){
$(this).replace('<div id="user'+indexNumber+'"></div>');
});
hope someone can help a noob. Many thanks in advance.
I have an index page with links to hundreds of other pages holding song words.
I have built each song page but it would be MUCH simpler to have one MASTER page that took a variable from the index page and found the corresponding words (which exist as png graphics.)
I have sorted Step 1 - I can pass a variable from the index page to the master page using:
<a href="javascript: window.open('MUSIC/beatles/mastertest2.html?song=ER', '_parent')">
where song=ER is the variable to display the words for Eleanor Rigby. For Step 2, I can also retrieve that information in the master page with:
var imageSrc = (qs("song")+".png"); document.write(imageSrc);
which will display the text ER.png which is the name of the image I want to display.
For Step 3 I am trying to get this same variable read into:
<input type="image" src="imageSrc;">
to display the picture. I have searched this and other forums for days now and nothing suggested works for me. I could be missing out an essential early step in the coding?
Update:
My master html file has this code to retrieve the variable:
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
And it uses this code to disply the variable (appended with .png) just to prove to me that it is getting through:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
Then I am trying to feed the variable into a routine to display the png selected. The next script doesn't work but I am thrashing about trying anything right now:
var imageSrc = (qs("song")+".png");
document.write(imageSrc);
<input type="image" src="#imageSrc;" border="0" value="Notes" onClick="placeIt(); showIt()">
<input id="song-image" type="image">
var imageSrc = 'ER.png';
var input = document.getElementById('song-image');
input.src = imageSrc;
If you have already <input type="image"> in your HTML page, you must add an id and then set it's src attribute with
HTML:
<input id="song-image" type="image">
JS:
var imageSrc = 'http://www.lorempixel.com/200/100';
var input = document.getElementById('song-image');
input.src = imageSrc;
JSFiddle for testing.
If I understood you right, its very simple. Are you looking for this?
var input = document.createElement('input');
input.type = 'image';
input.src = imageSrc;
document.body.appendChild(input);
If you can print the variable imageSrc using document.write, then you can use it like shown above.
I am trying to build a very simple tool for use at my work. I work for eBay and currently the tools available are cumbersome for the task. We are asked to compare text and images to check that sellers aren't stealing each others content. I am using the eBay Trading API and the sample HTML/CSS/Javascript code given when the developer account was created. Ultimately what I hope to achieve is a simple page that displays two items' photo and description next to each other. However, right now I am simply trying to edit the sample code given to display the start date of the auction.
My question is this: I am trying add a variable who's value is determined by a response from the API. some of these are provided in the sample however, when I add my own var starttime = items.listingInfo.startTime to the function and add the variable to the HTML table none of the data displays including those that displayed prior to my addition. Unfortunately I don't have more than a rudimentary understanding of javascript and so am unsure if I am even properly phrasing this question, let alone getting the syntax of my addition correct. What am I doing wrong?
below is the sample text with my addition of one declared variable (starttime) and one addition to the HTML table
<html>
<head>
<title>eBay Search Results</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
</head>
<body>
<h1>eBay Search Results</h1>
<div id="results"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = items.listingInfo.startTime;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '' + starttime + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%203g&paginationInput.entriesPerPage=3>
</script>
</body>
</html>"
If you believe listingInfo is an property of individual items, and that it is an object that has the property startTime, then the proper syntax is:
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = item.listingInfo.startTime;
You are currently referencing items which is the array of items, not an individual item.
Update
I looked into this via the URL you put in the comments. The solution to this particular problem is this:
var starttime = item.listingInfo[0].startTime;
I hope that helps. Please review the FAQ; Imho this question falls outside the scope of this site (the question is really quite narrow, and not likely to help anyone else). I recommend Mozilla Developer Network as a source for learning more about JavaScript.