I have this part of my html (more than one of same type):
<div class="this-product">
<img src="images/bag2.jpeg" alt="">
<span class="product-name">iPhone</span>
<span class="product-price">345445</span>
</div>
And this part of my javascript code meant to get the innerHTML of the span tags and assign them values as shown:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
var productName = document.getElementsByClassName('product-name')[0].innerHTML;
var productPrice = document.getElementsByClassName('product-price')[0].innerHTML;
var cartProductname = event.currentTarget.productName;
var cartProductprice = event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
Everything works well and every variable above has its value shown well apart from cartProductname and cartProductprice which display as undefined and also vscode tells me that productName is declared but not read. Where could I be wrong?
If I understand your question correctly, you could call querySelector on each product item element that you are iterating like so:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
// Update these two lines like so:
var productName = element.querySelector('.product-name').innerHTML;
var productPrice = element.querySelector('.product-price').innerHTML;
var cartProductname = productName; // event.currentTarget.productName;
var cartProductprice = productPrice; // event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
You can use event.currentTarget.querySelector('.product-name') to get element inside of another element
Related
Hello I am trying to make my jquery code in working order but its not working at all, I don't know whats a problem behind it but it contains multiple text boxes in multiple rows, each row calculates its own sum
Here is Fiddle link
Here is my Code
$(document).ready(function(){
$('.employee input[type="text"]').keyup(function() {
var basic_salary = parseInt($('input[name^=txtMonthlyRate]').val());
var advance_salary = parseInt($('input[name^=txtAdvance]').val());
var recover_comm = parseInt($('input[name^=txtRecovery]').val());
var sales_comm = parseInt($('input[name^=txtSales]').val());
var deduction_salary = parseInt($('input[name^=txtDeduction]').val());
var adjustment_salary = parseInt($('input[name^=txtAdjustment]').val());
var total_sum = ((basic_salary+recover_comm+sales_comm) - (deduction_salary + advance_salary)) + adjustment_salary;
$('input[name^=txtTotal]').val(total_sum);
console.log(total_sum)
);
});
The txtSales1, txtDeduction1, txtAdjustment1 variables are camel cased in your javascript, but not on the html input name. So these return NaN.
UPDATE Also, you need to set the context of what you're referring to using the second parameter of a selector function:
$('.employee input[type="text"]').keyup(function(e) {
var $scope = $(this).closest('.employee');
var basic_salary = parseInt($('input[name^=txtMonthlyRate]', $scope).val());
var advance_salary = parseInt($('input[name^=txtAdvance]', $scope).val());
var recover_comm = parseInt($('input[name^=txtRecovery]', $scope).val());
var sales_comm = parseInt($('input[name^=txtSales]', $scope).val());
var deduction_salary = parseInt($('input[name^=txtDeduction]', $scope).val());
var adjustment_salary = parseInt($('input[name^=txtAdjustment]', $scope).val());
var total_sum = ((basic_salary+recover_comm+sales_comm) - (deduction_salary + advance_salary)) + adjustment_salary;
$('input[name^=txtTotal]', $scope).val(total_sum);
});
The txttotal1 needs to be changed to txtTotal1
The fiddle needs a closing }
I am trying to refactor old code without completely redoing the program.
I have objects that are strategically named to be a value of the string from vendor. (vendor = "Ansys" or vendor = "Cadence")
var Ansys = {key:'ansyskeys', loaded:0, display: "none", otherkey: 'anotherkey'};
var Cadence = {key:"cdskeys", loaded:0, display: "none", otherkey: 'cotherkey'};
My previous HTML code that was static and had many entries that looked like:
<div id="ansyskeys" style="display:none">
<select id="anotherkey" size="5" onchange="selectOther('anotherkey')"></select>
</div>
To replace this, I made a function -ignore the use of eval, security is no concern:
function createDiv()
{
var vendorKey = eval(vendor).key;
var otherVendorKey = eval(vendor).otherkey;
var myDiv = document.createElement('div');
var html = '<select id="' + otherVendorKey + '" size="4" onchange="selectOther('+ otherVendorKey + ')"></select>';
myDiv.innerHTML = html;
myDiv.id = vendorKey;
document.body.appendChild(myDiv);
}
I am recieving my desired result, however, when I try to use selectedIndex in the function selectOther, it appears that mk is null.
function selectOther(wid)
{
var mk = document.getElementById(wid);
alert(mk);
var index = mk.selectedIndex;
key = mk.options[index].value;
setKey ();
getKeyStats ();
}
The HTML seems to be working, but doesnt seem to recognize the id from wid. Any help would be much appreciated.
I really need some help to create this order list. It's the mening that, when you click on the button it adds the text inside the addToList, to the div, so it shows up on the page. It should add the data (name, price), in javascript.
But can't get it to work properly.
<html>
<body>
<div id="myList">
</div>
<button onclick="addToList('donut', '25,-')">add</button>
</body>
</html>
<style>
#myList {
border: 1px solid black;
margin-bottom: 10px;
}
</style>
<script>
function displayListCart() {
var myList = document.getElementById("myList");
};
function addToList(name,price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name=name;
itemOrder.Price=price;
//Add newly created product to our shopping cart
listCart.push(itemOrder);
displayListCart();
}
</script>
Here is a Fiddle Demo.
I'm not a fan of inline calls to JavaScript functions because it violates separation of concerns, so I've changed the way the event is bound. This isn't part of your problem, but I'm using this approach:
HTML:
<div id="myList">
</div>
<button id="btn" data-name="donut" data-price="25,-">add</button>
Note:
I've added the values as data attributes on the button. You can then
access them from JavaScript.
JavaScript:
function displayListCart(listCart) {
var myList = document.getElementById("myList");
for (i = 0; i < listCart.length; i++) {
myList.innerHTML = myList.innerHTML + listCart[i].Name + " : " + listCart[i].Price;
}
};
function addToList(name, price) {
var itemOrder = {};
//itemOrder with data
itemOrder.Name = name;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Name);
itemOrder.Price = price;
//debugging -- check to make sure this returns what you expect
console.log(itemOrder.Price);
//Add newly created product to our shopping cart
//declare listCart before you use it
var listCart = [];
listCart.push(itemOrder);
//pass listCart to the display function
displayListCart(listCart);
}
function getValues() {
addToList(myBtn.getAttribute('data-name'), myBtn.getAttribute('data-price'));
}
var myBtn = document.getElementById("btn");
myBtn.addEventListener("click", getValues, false);
Notes:
You need to declare listCart before you add objects to it.
I suspect you intended to pass listCart to the display function so that you can access the objects within it for display.
You were missing the logic that adds the values to the div. You need to iterate over the array and access the object properties.
First of all, if you open the Dev Tools, you will see an error - Uncaught ReferenceError: listCart is not defined. So the first thing you need to do is create listCart array, like this : var listCart = [];
Then you should modify your displayListCart function, to display a new div for every item in listCart, like this:
function displayListCart() {
var myList = document.getElementById("myList"),
myListContent = "";
listCart.forEach(function(cart) {
myListContent += "<div>" + cart.Name + ": " + cart.Price + "<div>";
});
myList.innerHTML = myListContent;
};
The code example
I'm having some trouble with my code. the only thing i have to make is an add and delete button. The adding part is already done, but the delete part not. it keeps saying:
uncaught TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'
Can someone please help me?
Thanks!
Code:
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>
<script>
//decline variable
var index = 1;
//adding option
window.onload = function(){
document.getElementById('add').onclick = function(){
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function(){
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('p:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
:last-child works slightly different than you think it does. p:last-child selects the last child of type p(aragraph) of [whatever parent node you called the method on]'. You don't want to select the p, you want to select the div you just inserted.
var alinea = divResult.querySelectorAll('div:last-child')[0]
Do note that your code doesn't handle the case yet where you delete more elements than you added.
Running code snippet:
//decline variable
var index = 1;
//adding option
window.onload = function() {
document.getElementById('add').onclick = function() {
var newElement = document.createElement('div');
varElementid = 'div' + index++;
var node = document.getElementById('txtelement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
}
//delete option
document.getElementById('delete').onclick = function() {
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' word verwijderd...');
divResult.removeChild(alinea);
console.log('verwijderd!');
}
}
<input type="text" id="txtelement">
<button id="add">result</button>
<button id="delete">Delete latest</button>
<p id="divResult"></p>
I have a JQuery function that fetches and displays a page worth of images through the use of JSON files. I want to display the next set of images upon a button click, but that requires adding on a short string to the request url, which is found and stored in a var when I first run the script. I need to call this JQuery function again and pass the string var to it (lastId in code below). I am an utter noob with JavaScript in general and don't know how to go about doing that.
Here is a full version of the code:
$(function runthis(un){
var lastId;
un = typeof un !== 'undefined' ? un : "";
$('#domainform').on('submit', function(event){
event.preventDefault();
$('#content').html('<center><img src="img/loader.gif" alt="loading..."></center>');
//var lastId;
var domain = $('#s').val();
var newdomain = domain.replace(/\//g, ''); // remove all slashes
var requrl = "http://www.reddit.com/r/";
var getmore;
getmore = "?after=t3_"+un;
var fullurlll = requrl + domain + ".json" + getmore;
$.getJSON(fullurlll, function(json){
var listing = json.data.children;
var html = '<ul class="linklist">\n';
for(var i=0, l=listing.length; i<20; i++) {
var obj = listing[i].data;
var votes = obj.score;
var title = obj.title;
var subtime = obj.created_utc;
var thumb = obj.thumbnail;
var subrdt = "/r/"+obj.subreddit;
var redditurl = "http://www.reddit.com"+obj.permalink;
var subrdturl = "http://www.reddit.com/r/"+obj.subreddit+"/";
var exturl = obj.url;
var imgr = exturl;
var imgrlnk = imgr.replace("target=%22_blank%22","");
var length = 14;
var myString = imgrlnk;
var mycon = imgrlnk;
var end = mycon.substring(0,14);
myString.slice(-4);
var test1 = myString.charAt(0);
var test2 = myString.charAt(1);
var timeago = timeSince(subtime);
if(obj.thumbnail === 'default' || obj.thumbnail === 'nsfw' || obj.thumbnail === '')
thumb = 'img/default-thumb.png';
if(end == "http://i.imgur" ){
$("#MyEdit").html(exturl);
html += '<li class="clearfix">\n';
html += '<img src="'+imgrlnk+'" style="max-width:100%; max-height:750px;">\n';
html += '</li>\n';
html += '<div class="linkdetails"><h2>'+title+'</h2>\n';
/*html += '<p class="subrdt">posted to '+subrdt+' '+timeago+'</p>'; /*'+test1+test2+'*/
html += '</div></li>\n';
}
if (listing && listing.length > 0) {
lastId = listing[listing.length - 1].data.id;
} else {
lastId = undefined;
}
} // end for{} loop
htmlOutput(html);
}); // end getJSON()
}); // end .on(submit) listener
function htmlOutput(html) {
html += '</ul>';
$('#content').html(html);
}
});
The way you currently are executing the function run this doesn't ever leave you a handle to that function. This means it only really exists in the context of document.ready (what $(function()) is a shortcut for).
What you want to do instead is to keep a reference to this function for later use.
If you want to be able to put it directly into an onclick='' you will need to put the function in global,
eg:
var myFunction = function() { /*Stuff here*/}
$(myFunction)
this declares a function called myFunction and then tells jQuery to execute it on document ready
Global is generally considered pretty naughty to edit. One slightly better option would be to assign the click to the button inside your javascript
eg:
$(function(){
var myFunction = function() { /*Stuff here*/}
myFunction(); //call it here
$('#my-button-id').click(myFunction);//attach a click event to the button
)
This means that the function myFunction only exists in the scope of your document.ready, not in global scope (and you don't need onclick='' at all)
tTo add listener on some event you can use live('click',function(){}) Like yhis:
<div id="my-button">some content</div>
<script type="text/javascript">
$('#my-button').live('click',function(){
//your code
})
</script>