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.
Related
I have a button called File which is a dropdown that has another button called open. Once the user clicks open I have an ajax GET request that appends a button after each call.
When the user clicks open once, the button is appended. However, when the user clicks open again, the same button is appended again with the same attributes and if the user clicks the open button the third time the button is appended once more, so a total of three times.
How do I ensure the button is only appended once?
The {{}} is from the django web framework and is not a concern
<input type = "button" class = "openGraph" value = "{{titles}}" id="{% url 'openGraph' title=titles.id %}">
This is the occurence when the user presses the open button.
$(document).ready(function(){
$('#openXML').on('click',function(event){
var csrftoken = getCookie('csrftoken');
$.ajax({
type: "GET",
url: "/loadTitles/",
dataType: 'text',
headers:{
"X-CSRFToken": csrftoken
},
success: function(data){
var json = JSON.parse(data)
var length = Object.keys(json).length
var pk = "/openGraph/" + json[length-1]['pk']
var title = json[length-1]['fields']['title']
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
$("#loadAllTitles").append(myButton)
}
});
})
});
Because the IDs must be unique I'd suggest to test if the button already exist before adding. Hence, you need to change this line:
$("#loadAllTitles").append(myButton)
with:
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
I get the following console error: Uncaught Error: Syntax error, unrecognized expression: #/openGraph/104 –
If you are using jQuery 3.x you need to use:
jQuery.escapeSelector(): Escapes any character that has a special meaning in a CSS selector.
UPDATE
While pk is the ID when you create a new element you add to this ID a final /. This is your issue.
$('button').on('click', function(e) {
var pk = '#/openGraph/104';
var title='title';
myButton="<input type=\"button\" class = \"openGraph\" value=\""+title+"\" id="+pk+"/\>";
if ($("#loadAllTitles").find('#' + $.escapeSelector(pk + '/')).length == 0)
$("#loadAllTitles").append(myButton)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="loadAllTitles">
</form>
<button type="button">Click to add the same input field</button>
Check for the presence of a button on line 3
$(document).ready(function(){
$('#openXML').on('click',function(event){
if (!$('#+pk+').length) {
// Your code
}
}
}
I am new to jQuery and I am working with an API to do the following.
Get Multiple values from the API like name, place, weather forecast etc.
I have a bootstrap structure with the following code:-
<div id="place_here" class="row">
</div>
I want to place the data that I get from the API in this DIV.
Only thing that I want to do is get put all that data into a single div and place that div into above row div to create a beautiful table like structure. Something like this:-
var str = '<div class="col-md-4">' + newoverview + '</div>';
(newoverview is a string from JSON that I get. However that is only a single value that I want to place in my div class = "col-md-4" tag above. I want to insert more values as well.
Problems:-
I cannot(or don't know) how to use global variable in JQuery. Whenever I log a variable value in console it give me a null . I know that's because JSON is asynchronous but I don't know a work around this.
I tried using multiple functions and passing values one by one and adding div by div. However that is not doing what I want to do and gives a messed up structure.
How can I collect all the required values that I get in a JSON and combine them in a single div and place it in a div in my HTML structure.
Edit:- Code
$(document).ready(function(){
$("#Search_Button").click(function() {
var name;
name = $("#value").val();
if(!name){
console.log("Enter a name");
}
search(name);
});
function search(name){
var url = "url_here";
$.getJSON(url,function(data){
$.each(data.results,function(i,j){
displayImage(j.path);
displayOverview(j.id);
});
});
}
function displayOverview(id){
var url = "url_here";
$.getJSON(url,function(data){
var overviewx = data.overview;
var newoverview='';
for(var x=0;x<overviewx.length && x<100 ;x++){
newoverview+=overviewx[x];
}
var str = '<div class="col-md-4">' + newoverview +
'</div>';
$("#place_here").append(str);
});
}
function displayImage(id){
var url = "url_here";
var str = '<img src="' + url + '"</img>';
$("#place_here").append(str);
console.log(str);
}
});
I want to place both(and maybe more) tags in a single div from displayOverview and from displayImage and place that div into my main HTML Structure.
This is just an exemple !
to prevent asynchronous processing,we use callbacks
function getItem(){
var dfd = jQuery.Deferred();
var url_to_json = 'json/test.json';
$.getJSON(url_to_json, function(data) {
dfd.resolve(data);
});
return $dfd.promise();
}
when you need a the response you just :
getItem.done(function(data){
console.log(data);
});
In my project, I have a JSON file. I display the data that is parsed inside a list (ul) under a div with the class, "inner", and show only the name and cost of each product that you can see in my JSON.
{
"product": [
{
"name": "samsung galaxy",
"image": "https://rukminim1.flixcart.com/image/832/832/mobile/v/z/x/samsung-galaxy-on-nxt-sm-g610fzdgins-original-imaenkzvmnyf7sby.jpeg?q=70",
"cost": "RS.10,000",
"detail": "Flaunt your style with the Samsung Galaxy On Nxt. Featuring a drool-worthy body and impressive features, this smartphone is built to perform. Talk to your mom, chat with your friends, browse the Internet - stay connected the way that suits you best - this smartphone is powerful enough to keep up with your busy lifestyle."
}
]
}
When I click on the first product (first list item), I want to show the detail (value detail) of this product in another page from that same JSON object; when I click on the second product, I want that to show in a different page too, but also from that same object.
Here's my HTML:
<html>
<head>
<title>jquery</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
url: 'http://sonsofthunderstudio.in/jj/product.json',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
type: 'get',
crossDomain : true,
cache: false,
success: function(data) {
$(data.product).each(function(index, value) {
console.log(value);
$( ".inner" ).append("<li>"+value.name+"<img src='" + value.image + "' width='50px' height='50px' / >"+value.cost+"</li>");
});
}
});
</script>
<div class="inner">
</div>
</body>
</html>
Where can I go from here?
When you want to show details of your product, You have to create a "ProductList.html" to show your product list, and create a "ProductDetail.html" to show product detail based on selected product.
when user click on a product, You have to pass the selected product to "ProductDetail.html" via url and get it in that page.
the 2 "encodeURIComponenet()" and "decodeURIComponent()" are javascript defined functions to make this action encoded and safe.
To achieve this, You have to append a "Link"(A Tag) to $(".inner"):
$(".inner").append("<a href='#'>"+value.name+"</a>");
in code above, you create a link, you pass the Product ID to destination page and In codes below, You set the "href" attribute for the link:
var _SelectedProduct = "ID=" + ProductID;
var _EncodeID = encodeURIComponenet(_SelectedProduct);
document.getElementById("YourLink").href = "ProductDetail.html?" + _EncodeID;
with these codes, when user click on a product, he will be redirected to "ProductDetail.html" with the selected product ID. You can get this ID in Your ProductDetail.js:
var _DecodeURL = decodeURIComponent(window.location);
var ID = _DecodeURL.split("=");
var _ProductID = ID[1];
with these codes, you split the passed url base on ("="), which means you will get the passed Product ID.(_ProductID).
and :
for(i=0;i<=product.lenght; i++){
if(product[i].ID == _ProductID){ ... }
}
You can add onclick event on li and call a function which will store the particular detail in localStorage.
On the next page you can access detail from localStorage and display it.
//--[Appending in your code]--
.
.
.
$(data.product).each(function(index, value) {
console.log(value);
$( ".inner" ).append("<li onclick='foo('"+value.detail+"')'>"+value.name+"<img src='" + value.image + "' width='50px' height='50px' / >"+value.cost+"</li>");
});
<script type="text/javascript">
function foo(detail)
{
localStorage.setItem("DETAIL",detail);
}
</script>
//--[On second page]--
<head>
<script type="text/javascript">
var detail = localStorage.getItem("DETAIL");
$("#details").html(detail);
</script>
</head>
<body>
<div id="details"></div>
</body>
When you append data first you need to do is to add an Identifier because you need to differentiate the elements and you need to put onClick to each element that you will append you can put it like this: '<li id="'+ index +'" onClick="clicklist(this)">'+ value.name (...) +'</li>'
The second thing you need to declare is a function called clicklist or something with the param element.
function clicklist(element) { }
Fill it with the code I will explain now:
You can access to your list data through the element with your jQuery functions. So first you can get id with var id = $(element).attr('id'); then you can find your list elements and get it value with var itemname = $(element).find("typeofelement.class").attr('value'); etc...
When you get all data in your list you need to open a new window with the params you get in the function. Then use this code:
//Add all the values you need in the other html (id and values) So repeat this line:
sessionStorage.setItem("ID", id);
//Open the window
window.open("yourother.html","_blank");
This is the simple way.
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 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