Button click not working on dynamically created table row - javascript

I've tried a few different variations of this but for some reason, none of it seems to be working for me.
I issue an ajax get and loop through the response to print rows to the html.
Each row has a button to delete that element from the row.
It's a little bit lengthy, but here is that ajax get with how I run through the response to append rows to the table.
function getIEXSymbolQuote(symbol) {
$.ajax({
url: IEXurlBase + "/stock/" + symbol + "/quote",
method: "GET",
success: function (data) {
symbol = data.symbol;
companyName = data.companyName;
change = data.change;
changePercent = data.changePercent * 100;
changePercent = changePercent.toFixed(2);
iexRealtimePrice = data.iexRealtimePrice;
iexRealtimePrice = iexRealtimePrice.toLocaleString();
close = data.close;
close = close.toLocaleString();
if (iexRealtimePrice === null) {
if (change > 0) {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small>$" + latestPrice + "</small></td><td class='positive-data'><small>$" + change + "</small></td><td class='positive-data'><small>+" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
} else {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small>$" + latestPrice + "</small></td><td style='color: red'><small>$" + change + "</small></td><td style='color: red'><small>" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
}
} else {
if (change > 0) {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small>$" + iexRealtimePrice + "</small></td><td class='positive-data'><small>$" + change + "</small></td><td class='positive-data'><small>+" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
} else {
$('#watchListItems').append("<tr id='" + symbol + "'><td><small>" + symbol + "</small></td><td style='color: #ffc107'><small >$" + iexRealtimePrice + "</small></td><td style='color: red'><small>$" + change + "</small></td><td style='color: red'><small>" + changePercent + "%</small></td><td><button id ='" + symbol + "' class='btn btn-danger btn-sm removeWatchListitem'><i class='fa fa-trash'></i></button></td></tr>");
}
}
$('#watchListTable').css('visibility', 'visible');
$('#watchListErrBox').css('visibility', 'hidden');
},
error: function (err) {
$('#watchListErrBox').css('visibility', 'visible');
}
})
}
I need to be able to click on one of the trash buttons and get the id of the button clicked.
I've tried:
$("button").on("click", "button.removeWatchListitem", function () {
event.preventDefault();
alert($(this.id));
});
And;
$(".removeWatchListitem").on("click", function () {
event.preventDefault();
alert($(this.id));
});
but neither fire. This should be simple but I don't know if I'm just having a massive brain fart.

Add eventlistener to an exist div,such as body.
$(body).on('click','.removeWatchListitem',function(){...});

Related

Dom HTML return elements twice

am a newbie and am stuck with this for a week now, when I click the button to save the book information in session storage and post the book information in an other div, I get this result:the div is written twice, once with the css and the other without it, this my code:( for the whole code git#github.com:yaminecy/html.git)
`
//icons buttons
let bookmark = '<a id="' + items[i].id + '" data-id="' + items[i].id + '" data-title="' + items[i].volumeInfo.title + '" data-description="' + items[i].volumeInfo.description + '" data-author ="' + items[i].volumeInfo.authors + '" data-image ="' + items[i].volumeInfo.imageLinks.smallThumbnail + '"><i id="bookmark" class="fas fa-bookmark fa-3x"></i></a>';
let trashicon = '<a class="trash" id="' + items[i].id + '" onclick="return this.parentNode.remove();"><i id="icon2" class="fas fa-trash fa-3x"></i></a>';
//add elements to the book.
const livre = document.createElement("div");
livre.innerHTML = '<div id= "livre">' + bookmark + title + id + author + selectdescription + image + '</div>';
capture.appendChild(livre);
let bookmarkbutton = document.getElementById(items[i].id);
//click bookmark button
bookmarkbutton.addEventListener('click', function () {
var book = '{"id": "' + this.dataset.id + '", "name": "' + this.dataset.title + '", "description" : "' + this.dataset.description + '", "author" : "' + this.dataset.author + '", "image": "' + this.dataset.image + '"}';
favori(book);
});
//create a function for the action click on the button "bookmark"
function favori(item) {
console.log(item);
let pochList = [];
if (sessionStorage.getItem("maPochList") !== null) {
pochList = JSON.parse(sessionStorage.getItem("maPochList"));
}
if (pochList.includes(item)) {
alert("Vous ne pouvez pas ajouter deux fois le même livre!")
}
else {
pochList.push(item);
sessionStorage.setItem("maPochList", JSON.stringify(pochList));
item = JSON.parse(item);
favorite_books.append(setFavori(item));
}
}
// create a function that returns a div with information of favorite books
let bookdiv = document.createElement("div");
favorite_books.appendChild(bookdiv);
function setFavori() {
return bookdiv.innerHTML= '<div id= "livre">' + trashicon + title + id + author + selectdescription + image + '</div>';;
}
}
}
}
))
}
//Show Favorites
let pochList = [];
if (sessionStorage.getItem("maPochList") !== null) {
pochList = JSON.parse(sessionStorage.getItem("maPochList"));
}
for (var k in pochList) {
var item = JSON.parse(pochList[k]);
bookdiv.append(setFavori(item));
}
} `

How to validate HTML content with multiple variables put inside a string

I've below code
issuesList.innerHTML += "<div class=\"well\">" +
"<h6> Issue Id:" + id + "</h6" +
"<p><span class=\"label label-info\">" + status + "</span></p>" +
"<h3>" + desc + "</h3>" +
"<p><span class=\"glyphicon glyphicon-time\">" + severity + "</span></p>" +
"<p><span class=\"glyphicon glyphicon-user\">" + assignedTo + "</span></p>" +
"Close" +
"<a href=\"#\ onclick=\"deleteIssue( \"" + id + "\")\" class=\"btn btn-danger\>Delete</a>" +
"</div>";
I wish to validate if this is correct format of HTML as it contains many variable and it's hard to debug if something goes wrong.
To make it one degree less complicated, you can use single quotes to wrap class or style declarations and double quotes to wrap the overall html (or vice versa).
In this piece of html, I observed issued at closing of </h6> and in the class declaration of last anchor tag.
issuesList.innerHTML += "<div class='well'>" +
"<h6> Issue Id:" + id + "</h6>" +
"<p><span class='label label-info'>" + status + "</span></p>" +
"<h3>" + desc + "</h3>" +
"<p><span class='glyphicon glyphicon-time'>" + severity + "</span></p>" +
"<p><span class='glyphicon glyphicon-user'>" + assignedTo + "</span></p>" +
"<a href='#' onclick= 'setStatusClosed(\"" + id + "\")' class='btn btn-warning'>Close</a>" +
"<a href='#' onclick='deleteIssue( \"" + id + "\")' class='btn btn-danger'>Delete</a>" +
"</div>";
You may use following function to validate the html so created:
function validator(createdhtml) {
var tempdiv = document.createElement('div');
tempdiv.innerHTML = createdhtml;
return tempdiv.innerHTML;
}
Further I recommend reading:
check-if-html-snippet-is-valid

How to get script's value in .append()?

Here is my dropdownlist:
<div id="addCam"></div>
<div id="addDiv">
<select id="type1">
<option value="">- Kiểu áo -</option>
#foreach (var item in Model.teetypes)
{
<option value="#item.Image">#item.Name</option>
}
</select>
<a class="btn btn-info btn-default" id="addBtnH" style="text-align:center" title="Thêm sản phẩm"><i class="fa fa-plus"></i></a>
</div>
And here is my javascript .append():
$(document).ready(function () {
var count = 2;
var maxAppend = 0;
$("#addBtnH").click(function () {
var name = $("#type1 option:selected").val();
var name1 = $("#type1 option:selected").text();
if (name == '') return;
if (maxAppend >= 5) {
$("#addDiv").hide();
return;
}
$("#addDiv").show();
$("#type1 option:selected").attr('disabled', 'disabled');
$("#type1").val('');
$("#addCam").append("<div class='widget' id='del" + count + "'><div class='widget-body'><div class='col-md-3'><span style='display:block'><img src='" + name + "' id='tee" + count + "' height='75'/></span></div>" +
"<div class='col-md-1'><select id='color" + count + "' onchange='changeColor" + count + "()'>#foreach (var item in Model.teecolors){<option value='#item.Color' style='background-color: ##item.Color'></option>}</select></div><div id='dis" + count + "'>" + name1 + "</div>" +
"<hr class='wide'><input type='text' name='input'><a class='btn btn-info btn-default' rel='"+name+"' id='delete" + count + "' style='text-align:center' title='Xóa sản phẩm'><i class='fa fa-trash'></i></a>" + #*str +*#
"<script>$('#delete" + count + "').click(function(){var images = $(this).attr('rel'); $('#type1 option[value = "+"images"+"]').removeAttr('disabled');$('#del" + count + "').remove();});" + "<" + "/script>" +
"<script type='text/javascript'>function changeColor" + count + "(){var eID = document.getElementById('color" + count + "'); var colorVal = eID.options[eID.selectedIndex].value; document.getElementById('tee" + count + "').style.background = '#' + colorVal;}" + "<" + "/script>" +
"</div></div>");
count = count + 1;
maxAppend++;
});
});
My problem is, when I click button add, it will add div as content in append, and the value has been add will be disabled in dropdownlist. In the added div, there is a button delete, when i click it, the div will disappear, and the disabled attribute value will be remove. I create 'images' to get attr('rel') of that button, but i don't know how to let $("#type1 option[value=images]") understand that 'images' is a value, not a string? Please help me!
It is not the best practice to write the scirpts elements into the code to be evaluated.
The technique you are looking for is to continuously use jquery selector to get the appended node and set the attributes dynamically.
Consider this solution:
$("#addCam").append($('<ul>').attr('class', 'some-class')
.append($('<li>').attr('class', 'some-other-class')
.append($('<img>').attr('src', 'somePath'))
.on('click', liClickedHandler)));

Dynamic Pictures are Not Showing up

I have list of restaurants and I have to append pictures of each restaurant, which is coming from a database. For this I made div's id dynamic but the pictures not append on that div. If I make the div's id static then it shows the picture coming from the server. The problem is with making the div id dynamic. Please help me. Here is my sample code:
$("#list").empty();
$.each(data, function (i, item) {
if (data[i].has_logo == 1) {
$('#pic' + i).css("background-image", "url('http://www.thefoodhive.com/web_root/provider_uploads/" + data[i].id + "/logo.jpg')");
}
if (data[i].has_menu == 0) {
status = 'Call Now';
} else {
status = 'Order Now';
}
if (data[i].from_time == '' || data[i].from_time == null) {
data[i].from_time = 'NA';
data[i].to_time = '';
}
content = '<div ><div class="container"><div id="pic' + i + '" class="left"></div><div class="right"><div class="rightno">' + data[i].name + '</div></h4></p><i>Address:' + data[i].address + ',Timing:' + data[i].from_time + '-' + data[i].to_time + '</i><br><center><div style="float: right;"></div></div> <div class="bottom"><div class="btnleft" style="float: left;"><input class="callbttn" value="CALL NOW"type="button"></input></div><div class="btnright" style="float: left;"><input class="callbttn" value="' + status + '" type="button" onclick="getdata(\'' + data[i].id + '\',\'' + data[i].has_menu + '\',\'' + data[i].phone_no + '\');"></input></div></div>';
You are applying style to a div that doesn't exists yet...
Try to apply the background inline, like this:
content = '<div ><div class="container"><div id="pic' + i + '"
class="left" style="background-image:url(http://www.thefoodhive.com/web_root/provider_uploads/' + data[i].id + '/logo.jpg">...

How can I jump to another page by clicking a button in Javascript?

I am going to redirect my page by clicking a button. But I am totally messed up by the quotes.
Here is the code:
child.innerHTML += "<a class='sliding-element' href='javascript:sendSurvey(" + (m + 1) + ")'>Survey " + surveyList[m].Name + "</a>" + "<input type='button' onClick='parent.location='QuestionPage.aspx''/>";
It can't redirect me to the QuestionPage.aspx. It simply does nothing.
I don't know what your function does, but you could try escaping the double quotes:
child.innerHTML += "<a class=\"sliding-element\" href=\"javascript:sendSurvey(\" + (m + 1) + \")\">Survey " + surveyList[m].Name + "</a>" + "<input type=\"button\" onClick="parent.location=\"QuestionPage.aspx\""/>";
Don't construct the HTML, construct the elements:
var link = document.createElement("a");
link.className = "sliding-element";
link.href = "";
link.onclick = function (e) {
e = e || window.event;
e.preventDefault && e.preventDefault();
e.returnValue = false;
sendSurvey(m + 1);
};
link.appendChild(document.createTextNode("Survey " + surveyList[m].Name));
var btn = document.createElement("input");
btn.type = "button";
btn.value = "click me";
btn.onclick = function (e) {
parent.location.href = "QuestionPage.aspx";
};
child.appendChild(link);
child.appendChild(btn);
It's a little more verbose, but less prone to errors.
Here's your code made legible-ish:
child.innerHTML += "<a class='sliding-element'"
+ "href='javascript:sendSurvey(" + (m + 1) + ")'>Survey "
+ surveyList[m].Name + "</a>"
+ "<input type='button' "
+ "onClick='parent.location='QuestionPage.aspx''/>";
The quotes inside onClick (that last line) are wrong. You have nested quotes and must escape them, and there's an extra quote at the end.
Change to:
child.innerHTML += "<a class='sliding-element'"
+ "href='javascript:sendSurvey(" + (m + 1) + ")'>Survey "
+ surveyList[m].Name + "</a>"
+ "<input type='button' "
+ "onClick='parent.location=\"QuestionPage.aspx\" />";
child.innerHTML += "<a class='sliding-element' href='javascript:sendSurvey(" + (m + 1) + ")'>Survey " + surveyList[m].Name + "</a>" + "<input type='button' onClick=\"parent.location='QuestionPage.aspx'\"/>";
There's a problem with your quotation marks: You need to use escaped " and not nested '

Categories

Resources