When selecting an item the header should not change - javascript

I have this script (I'm new to this, so I'm not very familiar with the terminology). Feel free to edit the question if you can rephrase it in a better way.
<script>
var counter=0;
var oldJSON = null;
setInterval(function() {
var mycounter=0;
$.getJSON('mydata.json', function(data) {
if(JSON.stringify(oldJSON) != JSON.stringify(data)){
$("#notifications").html("");
$("#notifications").append("<option style=display:none></option>")
$.each(data.items, function(i, v) {
counter= counter + 1;
document.getElementById('test').innerHTML=counter ;
$('#notifications').append('<option value="' + v.type + '">' + v.type +"->"+ v.text +"->"+v.pnr+ '</option>');
;});
}
oldJSON = data;
});
},2000);
</script>
It takes the data from a JSON file and appends it to #notifications which is a dropdown element.
What I'm trying to create is a Facebook type notification dropdown.
This is my html:
<div class="hello">
<select id="notifications" style="background-image:url(live_data.jpg);" ></select>
</div>
<div id="test" style="color:red;margin-left:90px;font-size: 15px;font-family: arial;"></div>
Now, as you may have seen, I appended a blank item to the dropdown so that the old data gets cleared out.
Now here lies the problem: when I clear this data, the first element comes onto the image(overlaps). I added a empty item for it(not a very good way, I know... here also suggestions are welcome). But the thing is when I select any of them it overlaps onto the image.
Any help or advice would do... thanks in advance.
I'm open to suggestions if there is any other way to do it

Related

How can I loop through a jquery array and then output each item (starting at index 0) one at a time?

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

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);
}

JQuery how to click html element to copy into text area?

Is it possible to click text in a list to add into a text box. I have made a JSON api that gets a list of people in the database. I then have a form that has a text field and displays the list of people. I would like to click a particular person and add it to the text box.
main.js
var ajax_call = function() {
var $people = $('#people');
$.ajax({
type: 'GET',
url: '/all/api',
success: function(people) {
$.each(people, function(i, person) {
$people.empty()
});
$.each(people, function(i, person) {
$people.append('<li>name: ' + person.first_name+', last: '+ person.last_name + '</li>');
});
}
});
$("#people").on("click", "li", function() {
var content = $(this).html();
//$("#testbox").val(content); //replace existing name in textbox
$("#testbox").val($("#testbox").val() + content + "\n"); //add new name to textbox
});
};
var interval = 800;
setInterval(ajax_call, interval);
form.html
<form id="textbox" action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="create" />
</form>
<ul id="people"></ul>
Try this "click" function attached to the ul but filtered by the li's (this allows the list to remain dynamic), it allows you to add the individual names (two versions one that overwrites the existing textfield info and the second that appends to it): DEMO
$("#people").on("click", "li", function() {
var content = $(this).html();
//$("#testbox").val(content); //replace existing name in textbox
$("#testbox").val($("#testbox").val() + content + "\n"); //add new name to textbox
});
I think the answer to your question is pretty easy.
In your code you have the line
$("#people").keyup(function() {
Which is probably not what you wanted to do, cause now you are waiting for a keyup (release of a key) event on a list. First of all your question stated that you want the user to click and not to press a button and second you want the list items not the list itself.
So IMO you have to change that part to something like:
$("li","#people").click(function(){
var content = this.html();
$("#testbox").val(content);
});
Try this :
replace this
$("#people").keyup(function() {
var content = $('#people').html();
$("#testbox").val(content);
});
with this
$("#people").click(function() {
var content = $('#people').html();
$("#testbox").val(content);
});
If I have understood your question right away then
$("#people").click(function(){
var content = $('#people').html();
$("#testbox").val(content);
});
should do the work. But I think you should use something like custom attribute instead of id as there can be only one id for a specific tag.

jQuery EasyUI accordion content from php

Once again I humbly come before you with bruises upon my head from beating my head against a wall...
I have been trying to learn as I go in figuring out how to populate a jQuery EasyUI accordion from a php/MySQL query. I believe that I am now getting the data back to the webpage correctly, but I am unable to figure out how to parse and format this to be displayed as the content on the page. What I am attempting to achieve is basically an accordion to display the contact history with each correspondence with an individual as an accordion item. Here is a sample of the output from the PHP query.
{"rows":[{"phone":"5554072634","contact_dt":"2014-01-27 22:51:37","method":"Email","who":"Scott","note":""},{"phone":"5554072634","contact_dt":"2014-01-27 23:08:49","method":"Spoke","who":"Scott","note":"Called back and she is not interested."}]}
I am trying to get the "contact_dt" as the title of each accordion tab and then format the rest of the elements in the body of the accordion tabs. Currently I'm getting a busy spinner when I select the Contact History tab that contains the accordion but this only yields a tiny square box in the body and does not alter the title. Here is the code that I'm sure I have mangled. First for the HTML portion...
<div id="history" title="Prospect Contact History" closable="true" style="padding:10px;">
<h2 class="atitle">Prospect Details</h2>
<div id="aa" class="easyui-accordion" style="width:500px;height:300px;">
<div title="Title1" data-options="iconCls:'icon-save'" style="overflow:auto;padding:10px;">
<h3 id="hist_title" style="color:#0099FF;">Accordion for jQuery</h3>
<p>Accordion is a part of easyui framework for jQuery.
It lets you define your accordion component on web page more easily.</p>
</div>
</div>
</div>
Now for the jQuery pieces... First is the JS to basically call the function. This is in the body at the end of the page.
<script type="text/javascript">
$('#tt').tabs({
onSelect:function(title){
if (title == 'Prospect Contact History'){
//$( "#hist_title" ).html( "Accordion function is working.");
accordionHistory();
}
}
});
</script>
Now for the function that is defined in the head and where I think the real mess is at.
function accordionHistory() {
$( "#hist_title" ).html( "Accordion function is working.");
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
pp.panel('refresh','contact_history.php?phone=' + phone); // call 'refresh' method to load new content
var temp = $('#aa').form('load',pp);
$.each( temp, function( i, val ) {
var txt1=$("<p>Time: ").html(val.contact_dt);
var txt2=$("</p><p>Method: ").html(val.method);
var txt3=$("</p><p>Who: ").html(val.who);
var txt4=$("</p><p>Note: ").html(val.note);
//$("#hist_title").html(val.contact_dt);
$("#hist_item").html(txt2,txt3,txt4);
});
}
}
I'm sure I'm displaying gross ignorance here in basic JS concepts. As I mentioned at the beginning I'm really using this as a learning exercise as well as building something useful. Any help would be greatly appreciated. Additionally, any online tutorials that might help walk me thru some of my conceptual shortcomings would be most welcome. Thanks in advance.
Well... I finally have figured out my issues. Here is the function that I'm now using to get this working.
function accordionHistory() {
var pp = $('#aa').accordion('getSelected'); // get the selected panel
if (pp){
$.ajax({
post: "GET",
url: "get_history.php?phone=" + phone,
dataType: 'json',
success: function( details ) {
$.each(details.rows, function(index, element) {
$('#hist_title').replaceWith(
'Phone: '
+ element.phone
+ 'Contact time: '
+ this.contact_dt
+ '<br/>Method: '
+ this.method
+ '<br/>Who: '
+ this.who
+ '<br/>Note: '
+ this.note
);
});
}
});
}
}
I hope some other noob like myself finds this useful.

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