jquery Append add same value always - javascript

I use this jQuery code to append a div to another:
$('#sklep').on('click', '.kup', function () {
var cena = $('#cena').text();
var tytul = $('#tytul').text();
var iden = $('#id').text();
var suma = $('#koszykdiv .cyfry').text();
var dodawanie = parseInt(cena) + parseInt(suma);
$('.cyfry').text(dodawanie);
var source = $("#miniatura").attr("src");
$('.koszyk_content_items').append($('<div class="item_koszyk"><div class="miniatura_koszyk"><img width="165" height="110" src="' + source + '"/></div><span id="opis">' + tytul + ' - ' + cena + ' zł - </span><span class="identyfikator" style="display:none;">' + iden + '</span>USUŃ</div>'));
var licznik = $('#koszykdiv .licznik').text();
alert(licznik);
$('#identyfikator').text(licznik);
var licznik_dodawanie = parseInt(licznik) + 1;
$('#koszykdiv .licznik').text(licznik_dodawanie);
$.cookie("obraz" + licznik_dodawanie, id);
var cena = '';
var tytul = '';
var iden = '';
var source = '';
});
but it always appends a div with the same variables values, even if parent of '.kup' href has another text values. Can you help me and tell where the problem is?

You say in your question that you get the same variable values "even if parent of '.kup' href has another text values."
This is because nothing in your code is relative to the '.kup'-element. You get the src-attribute of the element with id=miniatura everytime.

Related

Not pulling any data from JQuery object

$(document).ready(function(){
var $body = $('body');
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class = tweet></div>');
var $user = $('<div class = users></div>');
var $message = $('<div class = message></div>');
var $time = $('<div class = time></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
$user.text('#' + tweet.user + ': ').attr('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//see user history by clicking on name
//click event on name element
//hide all other users that do not have the same username attribute?
$('.tweets').on('click', '.users', () => {
var user = $(this).data('users');
console.log(user);
})
So I'm trying to pull data from a class when I click on it. This involves the last few lines of my code. The data stored in my .users should give me an output of {someName: 'stringOfName"} however when I click on it I get an empty object {}. What am I doing wrong? I'm adding data to my .users and I can clearly see it being displayed holding information so am I pulling the data from this object incorrectly?
$(this).data('users'); would get info from a data-attribute called "users" on the clicked element. But I don't see anywhere in you code where you attach any data-attributes to any of your elements. You've added a "username" attribute, but that's not the same as a data-attribute, and it also has a different name.
Secondly, you can't use an arrow function as your "click" callback function because this will have the wrong scope. (You can read more about this elsewhere online).
Here's a working demo:
$(document).ready(function() {
//some dummy data
var streams = {
"home": [{
"user": "a",
"message": "hello",
"created_at": "Friday"
}]
};
var index = streams.home.length - 1;
while (index >= 0) {
var tweet = streams.home[index];
var $tweet = $('<div class="tweet"></div>');
var $user = $('<div class="users"></div>');
var $message = $('<div class="message"></div>');
var $time = $('<div class="time"></div>');
// $tweet.text('#' + tweet.user + ': ' + tweet.message + ' ' + tweet.created_at);
$tweet.appendTo($('.tweets'));
$time.text(tweet.created_at + '\n').appendTo($tweet);
//create a data-attribute instead of an attribute
$user.text('#' + tweet.user + ': ').data('username', tweet.user).appendTo($tweet);
$message.text(tweet.message + ' ').appendTo($tweet);
index -= 1;
}
//use a regular function insted of an arrow function
$('.tweets').on('click', '.users', function() {
var user = $(this).data('username'); //search for the correct data-attribute name
console.log(user);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tweets"></div>

Why can't I get the value of this var?

I want to create a live change field input system with jQuery. This is my code:
$(function() {
$('td').on('dblclick', function() {
var tdValue = $(this).text();
var tdTag = $(this).html();
tdTag = '<input id="newClass" type="text" value="' + tdValue + '">';
$(this).html(tdTag);
$('input#newClass').on('change', function() {
var inputVal = $(this).val();
alert('inputVal = ' + inputVal);
var inputTag = $(this).html();
alert('inputTag = ' + inputTag);
var var3 = '<span> var3 ' + inputTag + '</span>';
alert(var3);
})
})
})
Why is inputTag and var3 empty? This is my (very simple) html code
Note that the td tags are repeated using a PHP while loop. Thank you in advance.
Now I don't have enough reputation to comment and I'm still confused. Try following codes and see if anything suits you.
var inputTag = $(this)[0].outerHTML;
or
var inputTag = $(this).parent()[0].outerHTML;
or
var var3 = '<span>' + inputVal + '</span>';
$(this).after(var3);
$(this).remove();
or if you just want to make the input field read only, try with
$(this).prop("readonly", true);

Uncaught ReferenceError: is not defined at HTMLButtonElement.onclick

I have looked at other Questions of this type and none of them solved my problem. I am having this JavaScript code:
var count1;
for (count1 = 1; count1 < 11; count1++) {
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3 <p>' + article.description + '<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#" + count1).css('background-image', 'url(' + ImageURL + ')');
x = article.url;
}
function divLoad() {
alert(article.url);
};
Basically there are 10 items with different articles. Scopes of variables are all correct. I can see the links of the items when I console log them in the loop. I want to alert each URL whenever each Item is clicked for a respected button. But when I click that I get the error:
Uncaught ReferenceError: divLoad is not defined
at HTMLButtonElement.onclick
Am I missing something?
EDIT [My Full Code]:
var x;
function divLoad() {
alert(x);
};
$(document).ready(function(){
var url = 'https://newsapi.org/v2/top-headlines?country='+country+'&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res){
//console.log(res)
var count1;
for(count1 = 1; count1 < 11; count1++){
var article = res.articles[count1]
var ImageURL = res.articles[count1].urlToImage
x = article.url;
$('#showNews').append('<div id="'+count1+'" class="article"><div class="overlayart"><div class="art"><h3>'+article.title+'</h3><p>'+article.description+'<br><br><button onclick="divLoad()">Follow Link</button></p></div></div></div>');
$("#"+count1).css('background-image','url(' + ImageURL + ')');
}
});
The problem is that you're always referencing one single, global variable. That variable (x) will only ever hold the last value it was set to in your for loop.
Instead, we can append the articles and give each one a data attribute - that way, we can associate each element with a specific article URL.
function divLoad(url) {
alert(url);
};
$(document).ready(function() {
var url = 'https://newsapi.org/v2/top-headlines?country=' + "test" + '&apiKey=MYAPIKEY';
$.getJSON(url).then(function(res) {
for (let count1 = 1; count1 < 11; count1++) {
let article = res.articles[count1];
$('#showNews').append('<div id="' + count1 + '" class="article"><div class="overlayart"><div class="art"><h3>' + article.title + '</h3><p>' + article.description + '<br><br><button class="article-btn">Follow Link</button></p></div></div></div>');
$("#" + count1)
.css("background-image", "url('" + article.urlToImage + "'")
.attr("data-url", article.url); //Associate the URL to the element
}
});
$("#showNews").on("click", ".article-btn", function() {
var url = $(this).closest(".article").attr("data-url"); //Get the associated URL
divLoad(url);
});
});
If you inspect the <div class="article"> now, you'll see each one has a data-url attribute that holds its URL.

How can you insert a div into another created in javascript

So I'm trying to insert one div into another both created with Javascript
I have the following code,
// Assign tool attributes to Javascript Variables
var tool_name = String(tool['tool_name']);
tool_name = tool_name.replace(/'/g, '');
var tool_inventory_number = String(tool['tool_inventory_number']);
tool_inventory_number = tool_inventory_number.replace(/'/g, '');
var tool_recnum = String(tool['tool_recnum']);
tool_recnum = tool_recnum.replace(/'/g, '');
// Create the divs for the search results
var toolDiv = document.createElement("div");
var toolDivPicture = document.createElement("div");
//todo: Insert picture into this toolDivPicture div
var toolDivDescription = document.createElement("div");
toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number;
// Assign class to search result toolDiv and add content to it.
toolDiv.className = "toolDiv";
toolDiv.appendChild(toolDivDescription);
I keep getting the following error,
Uncaught NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null.
Could this be because I have to refrence the child div by id? I really just want to have javascript create a div that contains two other divs and then insert it into the page. Any help/suggestions are appreciated!
Since you marked the question with the jQuery tag, I assume that you have the jQuery library loaded:
// Create the divs for the search results
var toolDiv = $("<div/>");
var toolDivPicture = $("<div/>");
var toolDivDescription = $("<div/>");
toolDivDescription.html("<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number);
// Assign class to search result toolDiv and add content to it.
toolDiv.addClass("toolDiv");
toolDiv.append(toolDivDescription);
Note that you start a h2 but end a h3.
jsFiddle
Try this:
Wrap up your JavaScript in an onload function. So first add:
<body onload="loadJS()">
Then put your javascript in the load function, so:
function loadJS() {
// Assign tool attributes to Javascript Variables
var tool_name = String(tool['tool_name']);
tool_name = tool_name.replace(/'/g, '');
var tool_inventory_number = String(tool['tool_inventory_number']);
tool_inventory_number = tool_inventory_number.replace(/'/g, '');
var tool_recnum = String(tool['tool_recnum']);
tool_recnum = tool_recnum.replace(/'/g, '');
// Create the divs for the search results
var toolDiv = document.createElement("div");
var toolDivPicture = document.createElement("div");
//todo: Insert picture into this toolDivPicture div
var toolDivDescription = document.createElement("div");
toolDivDescription = toolDivDescription.innerHTML + "<h2>" + tool_name + "</h3>" + " <br>" + "Inventory Number: " + tool_inventory_number;
// Assign class to search result toolDiv and add content to it.
toolDiv.className = "toolDiv";
toolDiv.appendChild(toolDivDescription);
}

Using a list position as a param to a function to pull certain data

function getList()
{
var string2 = "<img src='close.png' onclick='removeContent(3)'></img>" + "<h4>Survey Findings</h4>";
string2 = string2 + "<p>The 15 Largest lochs in Scotland by area area...</p>";
document.getElementById("box3text").innerHTML = string2;
var myList = document.getElementById("testList");
for(i=0;i<lochName.length;i++)
{
if(i<3)
{
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
else
{
var listElement = "Loch "+lochName[i];
var container = document.getElementById("testList");
var newListItem = document.createElement('li');
newListItem.innerHTML = listElement;
container.insertBefore(newListItem, container.lastChild);
}
}
}
This function generates a list with the 1st 3 elements being hyperlinks. When clicked they should call a function call getLoch(i) with i being the position of the item in the list. However when i pass it the value it just give it a value of 15, the full size of the array and not the position.
function getLoch(Val)
{
var str = "<img src='close.png' onclick='removeContent(4)'></img>" + "<h4>Loch " + lochName[Val] +"</h4>";
str = str + "<ul><li>Area:" + " " + area[Val] + " square miles</li>";
str = str + "<li>Max Depth:" + " " + maxDepth[Val] + " metres deep</li>";
str = str + "<li>County:" + " " + county[Val] + "</li></ul>";
document.getElementById("box4").innerHTML = str;
}
There are 2 errors in your code as far as I can see. The first is the way you create your link.
var listElement = "<a href='javascript:getLoch(i)'>" + "Loch "+ lochName[i] + "</a>";
This will actually result in code like this:
<a href='javascript:getLoch(i)'>Loch name</a>
Passing a variable i is probably not what you intended, you want it to pass the value of i at the time your creating this link. This will do so:
var listElement = "<a href='javascript:getLoch(" + i + ")'>" + "Loch "+ lochName[i] + "</a>";
So why does your function get called with a value of 15, the length of your list? In your getList function, you accidently made the loop variable i a global. It's just missing a var in your loop head.
for(var i=0;i<lochName.length;i++)
After the loop finished, i has the value of the last iteration, which is your array's length minus 1. By making i a global, and having your javascript code in the links use i as parameter, getLoch got called with your array length all the time.

Categories

Resources