So, I am building some sort of e-commerce website and I needed to import a bunch of products from a mysql database, using nodejs and ajax.
I've been able to get that so far, aswell as creating certain buttons below each product that will lead to a /product page where additional information will be displayed of that exact product.
Since those buttons were not dynamic, I had the need to add an attribute, which will contain the products ID, which I will then use to send a POST request to the server so I can get the information about that specific product.
And although I was able to add the attribute to the buttons themselves, I have no idea how to get their value.
This is how I added my attributes to the buttons.
$(function () {
$.ajax({
type: 'POST',
url: '/getPacotes',
success: function (data) {
for (var i = 0; i < data.length; i++) {
var idPacote = data[i].idPacote;
var nomePacote = data[i].Nome_Pacote;
var precoPacote = data[i].Preco_Pacote;
var fornecedorPacote = data[i].Fornecedor_Pacote;
var foto = "https://webitcloud.net/PW/1617/RMR/Views/images/Pacotes/" + data[i].Foto;
var pacoteSet1 = "<div class='col-md-4 pacotes'>";
var pacoteSet2 = "<img src=" + foto + " alt='Mountain View' style='width:150px;height:150px;'><br><br><input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>";
var pacoteSet3 = "</div>";
$("#pacotes").append(pacoteSet1 + "<h1>" + nomePacote + "</h1>" + "<h2>" + fornecedorPacote + "</h2>" + "<h3>" + precoPacote + "euros/mes </h3>" + pacoteSet2 + pacoteSet3);
$(document).find("#btnPac" + i).attr({
"idPacote": idPacote
});
}
}
});
});
And this is how I was trying to get their attributes
$("button").each(function () {
console.log(this.idPacote);
$.post("http://localhost:3000/pacote?id=" + this.idPacote);
});
But it doesn't seem to work
idPacote returns undefined and I have no idea why, because I simply give the buttons an "id" and replace the idPacote with the "id" itself, it will return the buttons ID
Sorry if the question sounds dumb. I am not very experienced in these matters.
When you are using jQuery I would suggest you to use the HTML5 data attribute in order to set a specified attribute to a HTML element:
<button data-id="1"></button>
You can set and access it using jQuery:
$('button').data('id', value); //set data-id
$('button').data('id'); //Read data-id
Furthermore change
<input id=btnPac" + i + "' type='button' name='comprar' value='Comprar Pacote'>
to
<button name='comprar'>Comprar Pacote</button>
in order to get elements from $('button')
Related
to summarize my problem ... I have made a calendar with contains the from - to date range. Now the selected dates are displayed in a div with a delete button for each. But as the id of the button is the same for all the dates ....it deletes the entire date range. I have attached the screenshot as well.
I also tried taking a loop and giving each date a div so that the Del function will work properly. but I wasn't successful. I will mention code for the same
$(document).ready(function () {
var i = 0;
$.each(between, function (key, value) {
var rest = $('#target').append($('<div id="r' + i +value+ '" class="ansbox">
</div>'));
console.log(between);
var template = '<div id="ChildTarget_' + i + '"><span>key + ":" + "' + value + '"
</span><button id="tr' + i + '" class="target">X</button></div><br></div>';
i++;
$('#target').on('click', function () {
console.log("hola");
$('#target').remove();
You should add click event for the button itself.
var template = `
<div id="ChildTarget_' + i + '">
<span>key + ":" + "' + value + '"</span>
<button id="tr' + i + '" class="deleteButton">X</button>
</div>`;
$(".deleteButton').on('click', function() {
// do deletion here
});
First of all ,
The 'X' button should have different id
$.each(between, function (key, value){
$('#results').append(key+":"+value+'<br>');
$('#results').html(between.join('<button id="result"+key+"" > X </button><br>')
here you can see i am adding key to the Button Id making it unique. Use that id to remove the value, that you dont want. Hope this helps
Currently making a website to index and play movies stored on my hard drive that I've recently pulled off dvds just as a little side project. I have a 'master movie list' JSON file with all the data I need for each movie including the name, video source, video poster source, and genre which I would like to allow the use of placing a movie in multiple different genres.
Currently the problem I'm having is while I'm parsing through the genre list generated its not placing the html in the correct ID that id like it to on the webpage.
For example:
"genre":"comedy,recent,scifi"
I went about it how I thought I should, through getJSON and setting an output variable to which I get the genre value, split to make it an array, and get the element by going through each of them in a loop. Its not placing it in the right place though. The example above would be placed in comedy, recent, scifi, horror, and a few others for some reason and I have absolutely no reason why.
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
var output = '';
var ele = $('');
$.each(data, function(key, val) {
output += '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.html(output);
}
});
});
[ {
"name": "a star is born", "video_src":"/files/movies/A%20Star%20Is%20Born/astarisborn.mp4", "video_poster_src":"https://images-na.ssl-images-amazon.com/images/I/51R-TU6VaTL.jpg", "genre":"recently,romance,drama"
}
] // this is an example of the json
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="genre_box">
<h3>RECENTLY ADDED</h3>
<div class="scroll_box" id="recently"></div>
</div>
<div class="genre_box">
<h3>ACTION</h3>
<div class="scroll_box" id="action"></div>
</div>
<div class="genre_box">
<h3>COMEDY</h3>
<div class="scroll_box" id="comedy"></div>
</div>
Your output variable is being appended to and kept on every iteration of your $.each loop. What you want is to append to the end of $("#action"), $("#comedy"), etc. You should do something along these lines:
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
$.each(data, function(key, val) {
var output = '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (var i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.append(output);
}
});
});
My question is this, if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Not sure if I can do this, but I'm hoping I can. What I have is a bit of javascript code that is taking data from an xml document. I have a list of 500+ cards that I have parsed through and stored by categories that are used often. Here are the relevant functions as they apply to my question.
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
Where node is the position within the list of cards, and due to the formatting of the document which I started with contains each card alphabetically by name, rather than numbered logically within sets.
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
Here is what I am using to populate a list of cards, with names that upon hovering over will display a card image.
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
What I am trying to do is retrieve the id of the element with the onmouseover event so that I can retrieve everything that is not being saved to a value.
I realized I can pass the id as part of the changeImage function as a temporary workaround, though it involves rewriting my toLink function and my changeImage function to include a second argument. As a married man, I've enough arguments already and could do with one less per card.
In summary, and I suppose all I needed to ask was this, but is there a way using only javascript and html to retrieve the id of an element, onmouseover, so that I may use it in a function. If you've gotten through my wall of text and code I thank you in advance and would appreciate any insights into my problem.
if I have an Text html element that looks like...
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
Can I retrieve the id (in this case 1) on a mouseover event so that I may use it in javascript to do something else with it.
Yes, if you can change the link (and it looks like you can):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
Note the new argument this. Within changeImage, you'd get the id like this:
function changeImage(foo, element) {
var id = element.id;
// ...
}
Looking at your code, you'd update this line of toLink:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
Of course, you could also just put the id in directly:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
And then changeImage would be:
function changeImage(foo, id) {
// ...
}
I didn't use quotes around it, as these IDs look like numbers. But if it's not reliably a number, use quotes:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
I have a list of elements that are dynamically appended after an Ajax call. I am using a plugin that creates a lightbox click event for the anchors dynamically appended. It works fine except sometimes it says that the title is undefined. I realize this is because the plugin gets initiated before the title attribute is completely done appending to the DOM. I know of several ways to do this, but what is the BEST way to check that all these elements are completely appended?
Ajax call is already made and data parsed with this function (colorbox title is the one that evaluates to 'undefined' for only some):
function pageImages(images,_q){
for(var i = 0; i < images.count; i++){
$('#pageImages').append('<div class="pageImageItem"><a href="' + images.data[i]._clickurl + '" title= "' + images.data[i]._title + '">\
<img src="' + images.data[i]._thumbnailUrl + '" alt= "' + images.data[i]._title + '"/>\
</a><div class="hoverInfo"><h2>' + images.data[i]._title + '</h2><p>' + limitCharacters(images.data[i]._clickurl,40) + '</p></div></div>');
}
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
}
And here is a picture of what is happening (anchor highlighted is the element that clearly has a title attribute but is showing undefined in lightbox):
You can wrap the jQuery element find block in a timeout without timevalue. The timeout will wait for all javascript to be finished with all processes. Example:
window.setTimeout(function() {
$(".pageImageItem a").colorbox({maxWidth:'95%', maxHeight:'95%', title: function(){
var url = $(this).attr('href'),
title = $(this).attr('title');
console.log(title);
return '<h2>' + title + '</h2>' + limitCharacters(url,40) + '';
}});
});
I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});