Jquery adding items to a list without reloading page - javascript

I'm pretty stuck on how this should be achieved, mostly down to my lack of javascript knowledge. This is the code I'm looking at:
http://jsfiddle.net/spadez/VrGau/
What I'm trying to do is have it so a user can type add a "responsibility" in the responsibility field, then click add and have it appear in a list above it. The user can do this for up to 10 responsibilities.
The result would look something like this:
**Responsibility List:**
- Added responsibility 1
- Added responsibilty 2
*responsibility field - add button*
Can anyone explain how this should be done, it seems like it would have to involve ajax. I would really appreciate some more information or even an example.
Thank you.
EDIT: Here is a little bit more clarification. I want this data to be sent to the server as a list of items. I have seen examples of this being implemented, and here is a screenshot:
The user types in something in the text box, then clicks "add" and then it appears in a list above it. This information is what is submitted to the server.

Maybe this one can help also, this limits only 10 list
var eachline='';
$("#send").click(function(){
var lines = $('#Responsibilities').val().split('\n');
var lines2 = $('#Overview').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += '- Added ' + lines[i] + '\n';
}
}
$('#Overview').text(eachline);
$('#Responsibilities').val('');
});
Try it here
http://jsfiddle.net/markipe/ZTuDJ/14/

Something like that maybe?
http://jsfiddle.net/VrGau/10/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#send'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
$responsibilityList.val(newVal+'\n');
$responsibilityInput.val('');
}
}
$inputButton.click(addResponsibility);

Add id for textarea fields
<textarea rows="4" cols="50" placeholder="Responsibilities" id="resplist"></textarea>Add responsibility<br />
<textarea rows="4" cols="50" placeholder="How to apply" id="inputresp"></textarea>
You need Jquery. Use this js code
var i=0;
$("#send").click(addresp);
function addresp()
{
if (i<10)
{
$("#resplist").val($("#resplist").val()+$("#inputresp").val()+'\n');
$("#inputresp").val("");
i++;
}
}
http://jsfiddle.net/br0nsk1y/bDE9W/

It depends on if you want to post data to the server or not. If only in the client side you can do like this.
$("#send").on("click", function(event){
if($("#list li").size() < 10){
$("#list").append("<li>" + $("#responsibilities").val() + "</li>");
}
});
http://jsfiddle.net/VrGau/7/

Related

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

javascript function is adding data to screen but then being overridden by another function

My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}

Dyamically inserting array back into HTML from Javascript

In short, I'm trying to figure out how to change an HTML drop down based upon a selection made in another HTML dropdown. Something like this is the end product.. where you select something in the first box, and the second box populates based upon that first option.
However, I've become stuck at how to populate that second box with the code I have. It's not as simple as adding as the code creates arrays for all the options you have.
Some of the snippets I have are laid out like this.. (Javascript first)
function setModelLevels(mdlselc){
var selection = mdlselc;
if (selection == "nam_ncep" || selection == "nam_4km_ncep" || selection == "gfs_ncep" || selection == "rap_ncep" || selection == "wrf_nmm_ncep" || selection == "wrf_arw_ncep"){
levelDyMenuItems = new Array();
numDyLevelMenuItems = 0;
makeDyLevelMenuItem("sfc","***Surface***","","level")
makeDyLevelMenuItem("sfc","Surface","SELECTED ","level")
makeDyLevelMenuItem("pcp","Precip","","level")
makeDyLevelMenuItem("windvector","Wind Vector","","level")
makeDyLevelMenuItem("windgust","Wind Gusts","","level")
makeDyLevelMenuItem("ref","Simulated Reflectivity","","level")
} //Ends Model check
} //Ends setModelLevels
(HTML next)
<TR><TD>
<SELECT NAME="model" CLASS="controls1" onchange=setModelLevels(document.controls.model[document.controls.model.selectedIndex].value);>
<SCRIPT>
createMenuItems();
for (i = 1; i <= numModelMenuItems; i++) { document.writeln('<OPTION ' + modelMenuItems[i].modelDefault + 'VALUE="' + modelMenuItems[i].modelValue + '">' + modelMenuItems[i].modelLabel) }
</SCRIPT>
</SELECT>
</TD></TR><TR><TD>
<SELECT NAME="level" id="levelsel" CLASS="controls1">
<SCRIPT>
for (i = 1; i <= numDyLevelMenuItems; i++) { document.writeln('<OPTION ' + levelDyMenuItems[i].levelLabel + 'VALUE="' + levelDyMenuItems[i].levelValue + '">' + levelDyMenuItems[i].levelLabel) }
</SCRIPT>
</SELECT>
</TD></TR>
(The code isn't mine, it's a somewhat publicly available weather model animator that I'm messing around with on my side.)
So basically, when you change the dropdown with the NAME="model", it drops the name of the model into the setModelLevels code. That sees what model you've selected, and makes an array with the necessary parameters to drive the rest of the page.
The problem comes with the fact that the created array never displays back into the main webpage. I would assume I need to push my newly created array into the HTML document.. but I've only done that with jquery before. And I cannot use jquery for this due to the restrictions we have on our pcs.
I'm looking for any help here.. I'm a bit of a novice of a coder and I'm trying my hardest not to edit/rewrite the code here.
Thanks.
Addendum
The makeDyLevelMenuItem basically makes the array of menu items to list. It looks like this..
function makeDyLevelMenuItem(levelDyValue,levelDyLabel,levelDyDefault,levelDyClass) {
numDyLevelMenuItems++;
levelDyMenuItems[numDyLevelMenuItems] = new levelDyMenuItem(levelDyValue,levelDyLabel,levelDyDefault,levelDyClass);
}

Display summary of choices in JS

this is my first time here as a poster, please be gentle! I have zero knowledge of JS (yet, working on it) but am required to do some JS anyway. Here's my problem. I got some code (not mine) allowing a user to select multiple choices. I found the function that gathers these choices and store them
function getProductAttribute()
{
// get product attribute id
product_attribute_id = $('#idCombination').val();
product_id = $('#product_page_product_id').val();
// get every attributes values
request = '';
//create a temporary 'tab_attributes' array containing the choices of the customer
var tab_attributes = [];
$('#attributes select, #attributes input[type=hidden], #attributes input[type=radio]:checked').each(function(){
tab_attributes.push($(this).val());
});
// build new request
for (var i in attributesCombinations)
for (var a in tab_attributes)
if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
request += '/'+attributesCombinations[i]['group'] + '-' + attributesCombinations[i]['attribute'];
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')// DISPLAY ATTRIBUTES SUMMARY
request = request.replace(request.substring(0, 1), '#/');
url = window.location + '';
// redirection
if (url.indexOf('#') != -1)
url = url.substring(0, url.indexOf('#'));
// set ipa to the customization form
$('#customizationForm').attr('action', $('#customizationForm').attr('action') + request);
window.location = url + request;
}
I need to make a simple display summary of these choices. After quite a bit of searching and findling, I came with the line with the DISPLAY SUMMARY comment, this one:
$('#[attsummary]').html($('#[attsummary]').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')
In the page where I want those options, I added an empty div with the same ID (attsummary):
<div id="attsummary"></div>
Obviously, it is not working. I know I don't know JS, but naively I really thought this would do the trick. May you share with me some pointers as to where I went wrong?
Thank you very much.
Correct form of the line it isn't working for you:
$('#attsummary').html($('#attsummary').html() + attributesCombinations[i]['group']+': '+attributesCombinations[i]['attribute']+'<br/>')

Unable to retrieve values from eBay API response using Javascript

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.

Categories