How do I set an attribute to a dynamically created button? - javascript

First and foremost, hello. I'm a college student and not a very experienced coder, so forgive me if I end up saying something really dumb.
Either way, I have a school project in which I have to create a functional website using Node.js, where people are able to log in and buy stuff.
Most of the stuff already works, but I am having trouble with a very specific thing which I simply cannot get to work, yet is essential to the project itself.
I import data from a mySql database into the website using AJAX, that data contains products that people can buy. Then, those products are appended to the HTML page itself, and dynamically create two buttons for each product that is appended, one which says "Buy Now" and the other which says "Learn More".
Now, those buttons are supposed to be somehow associated to the values of the database, but I have no idea how to do this.
$(document).ready(function () {
$(function () {
$.ajax({
type: 'POST',
url: 'http://localhost:3000/getPacotes',
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
var pacoteSet1 = "<div class='col-md-4 pacotes'>";
var pacoteSet2 = "<input id=btnPac"+
i + " type='button' name='comprar' value='Comprar Pacote'>";
var pacoteSet3 = "</div>";
var idPacote = data[i].idPacote;
var nomePacote = data[i].Nome_Pacote;
$("#pacotes").append(pacoteSet1 +
"<h1>" + nomePacote + "</h1>" +
"<h1>" + nomePacote + "</h1>" +
"<h3>" + precoPacote + "euros/mes </h3>" +
pacoteSet2 +
pacoteSet3);
}
}
});
});
});
My teacher told me to give an attr to the buttons I create, and that's what I was pretty much trying to do now, but I dont know how to do that, I mean, if the buttons were static it would be pretty easy, but since the buttons are not there when the document is created, I dont know if this will work
$("#btnPac" + i).attr({"id": idPacote,
"nome": nomePacote,
"preco": precoPacote,
});
Anyway, Hopefully, I didn't sound too dumb and thanks in advance
TL:DR how do I give an attribute to a dynamically created button

You just need to change your jquery function like below:
$(document).find("#btnPac" + i).attr({"id": idPacote,
"nome": nomePacote,
"preco": precoPacote
});
This should be your solution.

You can do that while creating the html for button element. By using string concatenation, which you are already using while setting the ID:
var pacoteSet2 = "<input id=btnPac"+ i + " nome='" + nomePacote + "' preco='" + precoPacote + "' type='button' name='comprar' value='Comprar Pacote'>";

Overloading the HTML with attributes is a bad idea in my opinion. You could create the Elements in JS, bind the data to it, and then append the button to the dom. Thats quite easy with jquery:
var button=$("<button>Show More</button>");//create
button.on("click",showMore.bind({name:"test"}));//add listener
$(document.body).append(button);//append
function showMore(){
alert(this.name);
}

You can create a new input tag and set these attributes then append to your div with this code:
$('<input/>', {
id: 'btnPac' + i,
nome: nomePacote ,
preco: precoPacote ,
type: 'button'
}).appendTo("#pacotes");
You can do the same for your others (h1, h3)

Related

How to pass a value from a Javascript generated button to a controller?

My code generates a table with a button at the end of each row. When the user clicks a button how can I pass a property u.userEmail to the controller via the button? Will the value being sent to the controller be a string?
My (non-working) attempt:
<script>
$(document.body).append("waiting on async table to load<br>");
$(document).ready(function () {
$.getJSON("/Account/LoadClaimsTable", function (crewResponse) {
//returns a List<UserClaims>
$(document.body).append("<table>")
crewResponse.forEach(function (u) {
var s = "";
s+="<tr><td>" + u.userEmail + "</td>";
u.userClaims.forEach(function (k) {
console.log("added claim"+k.value);
s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +
"<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+
"<input type=\"button\" value=\"Create\" onclick=\"location.href='#Url.Action("EditClaims", "Account")'" />
+"</td>");
});
s += "</tr>";
$(document.body).append(s);
s = "";
});
$(document.body).append("</table>")
});
});
</script>
AccountController.cs contains:
public ActionResult EditClaims(string userEmail)
{
return View("StringView", userEmail);
}
You have to pass it on the url of the action. Not sure if you want to pass u.userEmail, but it could looks like this:
crewResponse.forEach(function (u) {
var s = "<tr><td>" + u.userEmail + "</td>";
u.userClaims.forEach(function (k) {
console.log("added claim"+k.value);
s += ("<td>" + k.type + "</td><td>" + k.value + "</td><td>" +
"<input type=\"hidden\" name=\"userEmail\" value=\"`${u.userEmail}`\" />"+
"<input type=\"button\" value=\"Create\" onclick=\"location.href='#Url.Action("EditClaims", "Account")?userEmail=" + u.userEmail + "'\"/></td>");
});
s += "</tr>";
$(document.body).append(s);
});
There are multiple ways to do it. One is mentioned in the answer above by Felipe. Here is another alternate approach using unobtrusive js
Add the email as html5 data attributes to the button along with another attribute which we will use bind the click behavior.
u.userClaims.forEach(function (k) {
// Add quotes as needed if you want multiline ( i just removed those)
s += "<td>" + k.type + "</td><td>" + k.value + "</td><td>
<input type='button'
clickablebutton data-email='" + u.email + "' value='Create'/></td>";
});
Now, in your document ready, bind a click event handler to those elements (with our custom attribute) and read the data attribute and build the url you need.
$(document).on("click", "input[clickablebutton]", function (e){
var url = '#Url.Action("EditClaims", "Accounts")?useremail=' + $(this).data("email");
window.location.href = url;
});
Some other suggestions
Use the appropriate element. Button is better than input (Consider accessibility)
If it is for navigation, Use an anchor tag instead of a button.
Inline javascript is not great. Let the browser parses your markup without any interruptions and you can add the behavior scripts later (that is the whole point of uobutrisive js approach)
The approach you appear to be taking would be Ajax, response, render a template. With that being said, you may want to rethink your approach.
Step 1.
Build a template
<template id="...">
<button type="button" value="[action]" onclick="[url]">[text]</button>
</template>
Step 2.
Create your request.
axios.get('...').then((response) => {
// Retrieve template.
// Replace bracket with response object model data.
html += template.replace('[action]', response.action);
});
Step 3.
Have the JavaScript render your template.
The above can create a clear concise codebase that is easier to maintain and scale as the scope changes, rather than an individual request performing a change with embedded markup. This approach has worked quite well for me, also I feel it'll make you troubleshooting and definition easier, as the controller is handing an object back to your JavaScript instead of a markup / view data. Which will be a better finite control for the frontend and clear modifications in future.

Json Individual Links in Table column

I have one page with a json table pulling in information from the json api. This works fine. Now my issue is, On the far right column i'm wanting a link to another page of mine, This link will be a unique link. At the moment, As you can see by the code, i can get it to link to the html page 12345, But all the rows link through to this. Which does not help Ha!
I'm ideally wanting the first button to link to 1.html then second button to link to 2.html and so on and so forth.
Here is the code i have so far.
for(var i =0;i < json.results.collection1.length;i++) {
var title = json.results.collection1[i].Name.text;
var venue = json.results.collection1[i].Venue.text;
var date = json.results.collection2[i].Date;
var button = "<button class='redirect-button' data-url='12345.html'>Link</button>";
$("#apple").append("<tbody><tr><td>"+title+"</td><td>"+venue+"</td><td>"+date+"</td><td>"+button+"</td></tr></tbody>");
$("#apple").find(".redirect-button").click(function(){
location.href = $(this).attr("data-url");
});
}
},
Obviously all help would be greatly appreciated. Thanks Sam
Just to explain the comment above
The link you're creating is a <button> but really it's just a string.
So by concatenating the URL part of the string based on something (like your i index in your loop) you can change it to anything you want.
so for example :
var button = "<button class='redirect-button' data-url='" + i + " .html'>Link</button>";
this gives an element that looks like :
<button class='redirect-button' data-url='0.html'>Link</button>
would give you 0.html, 1.html, etc (change the data-url='" + i + " .html' to data-url='" + (i+1) + " .html' and you get 1.html, 2.html, 3.html...)
or if you can change the API to give you a proper link in the return you can make it a bit more readable with:
var button = "<button class='redirect-button' data-url='" + json.results.collection2[i].LinkUrl + " .html'>Link</button>";
results in :
<button class='redirect-button' data-url='abcd.html'>Link</button>
assuming the return is called LinkURL and it's value is 'abcd'
Finally you append this string to the $("#apple") element and then the click event is added that looks for the data-url value and changes the current browser location to that new value.

JQuery click event firing multiple times

I know that there's lot here on already on multiple click events being fired off, I think I've read them all but still can't see what's going wrong here.
Hope fully I'm missing something obvious that someone else can pick up easily...
Some background
My code works inside an Enterprise Social Networking platform and creates a BI dashboard for content analysis (about a 1000 lines of the stuff, mostly domain specific, so too much to post in it's entirety).
The part that is causing me grief is the function that builds the dashboard visualisation itself.
Here goes...
function makePage(){
$("#policyCount").text(policyCount);
var docTypes=getGlobalDocTypes(polOwners); //returns a constrained vocab array
var statusTypes=getGlobalStatusTypes(polOwners); //returns a constrained vocab array
$.each(polOwners,function(){ // polOwners is a global array that contains the BI data to be visualised
html=""
var ownerName = this.name.split(":")[1]; // name is a str in format "Owner:HR"
html += "<div id='" + ownerName + "' class='ownerData'>";
html += "<div class='ownerHeading'>" + ownerName + "</div>";
html += this.policies.length + " Policy documents maintained<br />"; // policies is an array of docs managed by owner
divIDReview = "dboard_" + ownerName + "reviewchart";
html += "<div id='" + divIDReview + "' class='dboardelement'></div>";
divIDType = "dboard_" + ownerName + "typechart";
html += "<div id='" + divIDType + "' class='dboardelement'></div>";
divIDStatus = "dboard_" + ownerName + "statuschart";
html += "<div id='" + divIDStatus + "' class='dboardelement'></div>";
html += "<div id='" + ownerName + "ToggleTable' class='toggletable' owner='" + ownerName + "'>";
html += "Click to display all " + ownerName + " documents<br /></div>";
html += "<div id='" + ownerName + "polTable' class='poltable'>";
html += getPolTable(this.policies); // Returns an HTML table of doc metadata
html += "</div>";
html += "</div>";
  $("#owners").append(html); // When this function is called #owners is an empty div
$(".toggletable").mouseover(function(){
$(this).css({'cursor':'pointer','text-decoration':'underline'});
});
$(".toggletable").mouseout(function(){
$(this).css( {'cursor':'default','text-decoration':'none'});
});
$(".toggletable").each(function(i, elem){
$(elem).click(function(){
if ($(this).next(".poltable").css("display")=="none"){
// Currently hidden - so show
if (debug){console.log($(this).attr("id") + " was clicked")}
$(this).html("Click to hide " + $(this).attr('owner') + " documents<br/>");
$(this).next(".poltable").css("display","block");
} else {
if (debug){console.log($(this).attr("id") + " was clicked")}
$(this).html("Click to display all " + $(this).attr('owner') + " documents<br />");
$(this).next(".poltable").css("display","none");
}
});
});
// the next section calls functions that use the Google vis api to draw pie charts
drawPie(300,200, "Review Status", "Status", "Policies", getReviewStatus(this.policies), ["green","orange","red"], divIDReview);
drawPie(300,200, "Document Types", "Type", "Docs", getDocTypes(this.policies, docTypes), [], divIDType);
drawPie(300,200, "Document Status", "Status", "Docs", getStatusTypes(this.policies, statusTypes), [], divIDStatus);
});
}
Hopefully that's enough to illustrate the problem.
You'll see that the code builds a dashboard display for each polOwner consisting of three pie charts and an option to hide or display a table of underlying data.
I started by applying the click event to the .toggletable class. When that fired multiple times I used the method described on another answer here with the .each to attach a unique event to each instance of the class.
So, what happens?
There are currently 9 polOwners and at first glance, the click event only seems to be toggling the display state of every other table. The console log however shows that this is because it is firing 9 times for the first instance, 8 for the second, 7 for the third etc. with the odd numbers leaving the table in the alternate state (when this works the display will change to a .toggle animation).
For info, While I'm a text editor person, I do have a copy of MS Expression Web 4 which is a useful tool for error checking HTML. I've pasted in a copy of the entire generated markup (nearly 4000 lines) and can't see any bad nesting or structure errors.
Any ideas folks?
You've got some nested loops:
// jQuery each on polOwners
$.each(polOwners,function(){
// ... code that appends .toggletable class
// jQuery each on .toggletable class
$(".toggletable").each(function(i, elem){
// code that runs on the toggletable element
});
});
For each polOwner you are adding a div with the toggletable class. Then inside there you are looping through each div with a toggletable class and adding a click event.
This adds 1 click for the first polOwner, 2 for the second, three for the third and so on.
Move the toggletable each outside of the polOwner each and you should be good

How much knowledge of the DOM should javascript code have?

I'm implementing OpenID and OAuth on my site, in C# and ASP.NET MVC 3. I'm basing off of DotNetOpenAuth for the back-end and openid-selector for the front-end.
I liked openid-selector but it doesn't have OAuth support out of the box so I started adapting it (with help of StackOverflow's implementation and jsbeautifier).
I found a lot of code that handles the DOM like this:
function highlight(boxId) {
// remove previous highlight.
var highlight = $('#openid_highlight');
if (highlight) {
highlight.replaceWith($('#openid_highlight a')[0]);
}
// add new highlight.
$('.' + boxId).wrap('<div id="openid_highlight"></div>');
};
or
function useInputBox(provider) {
var area = $('#openid_input_area');
var id = 'openid_username';
var html = '';
var value = '';
var style = '';
var label = provider.label;
if (label) {
html = '<p>' + label + '</p>';
}
if (provider.name == 'OpenID') {
id = this.input_id;
value = 'http://';
style = 'background: #FFF url(' + spritePath + ') no-repeat scroll 0 50%; padding-left:18px;';
}
html += '<input id="' + id + '" type="text" style="' + style + '" name="' + id + '" value="' + value + '" />'
+ '<input id="openid_submit" type="submit" value="' + this.signin_text + '"/>';
area.empty();
area.append(html);
$('#' + id).focus();
};
Which both sound to me like they're assuming too much about the DOM (too many ids, or the current state of the DOM).
Is it ok to have javascript so tightly coupled to the DOM? What's the best way to avoid code like this and follow a less intrusive approach?
I guess what perplexes me is the call:
openid.init('openid_identifier', '', 'http://cdn.sstatic.net/Img/openid/openid-logos.png?v=8', true);
When there's so much assuming already in the script file.
I'd argue, as you suspect that this is a bad thing.
There's a huge lack of, well, design patterns in Javascript UI development. I'm guessing a lot of people came straight from html, to learning some jQuery, to writing web applications.
A simple system (I find) that does handle this better, is backbone.js. The sourcecode is legible, and it separates view-concerns from business logic concerns quite nicely.
http://documentcloud.github.com/backbone/
http://martinfowler.com/eaaDev/uiArchs.html
Also for a more MVVM approach ( aka data binding ) knockoutjs is an option. They also have a nice interactive tutorial to get you started.

jQuery: trying hook a function to the onclick when page loads

I have seen a similar question, HERE and have tried that, but I can't seem to get it working.
Here is my code for dynamically generating table rows.
for (var contribution = 0; contribution < candidate.contributions.length - 1; contribution++) {
var id = candidate.contributions[contribution].donor_id;
var uid = candidate.contributions[contribution].user_id;
$("#history-table").append(
"<tr onclick='" + parent.viewEngine.pageChange('public-profile', 1, id, uid) + ";>" +
"<td class='img-cell'>" +
"<img class='profile-avatar-small' src='/uploads/profile-pictures/" +
candidate.contributions[contribution].image + "' alt='' /></td><td class=''>" +
"<h2>" + candidate.contributions[contribution].firstname +
" " + candidate.contributions[contribution].lastname + "</h2></a><br/><br/>" +
"<span class='contribution-description'>" + candidate.contributions[contribution].contribution_description + "</span></td>" +
"<td><h3>$" + formatCurrency(candidate.contributions[contribution].contribution_amount) + "</h3></td></tr>");
}
This still executes the click event as soon as the page loads, which is not the desired behavior. I need to be able to click the tr to execute the click event.
Pass the whole thing as a string:
"<tr onclick='parent.viewEngine.pageChange(\'public-profile\', 1, " + id + ", " + uid + ");>" // + (...)
But, as you are using jQuery, you should be attaching the click handler with .on().
(I really don't recommend using inline event handlers like that, especially when you're already using jQuery, but anyway...)
The problem is that you need the name of the function to end up in the string that you are passing to .append(), but you are simply calling the function and appending the result. Try this:
...
"<tr onclick='parent.viewEngine.pageChange(\"public-profile\", 1, " + id + "," + uid + ");'>" +
...
This creates a string that includes the name of the function and the first couple of parameters, but then adds the values of the id and uid variables from the current loop iteration such that the full string includes the appropriately formatted function name and parameters.
Note that the quotation marks around "public-profile" were single quotes but that wouldn't work because you've also used single quotes for your onclick='...', so you should use double-quotes but they need to be escaped because the entire string is in double-quotes.
I'm wondering if you might be better simplifying things a bit.
If your rows are being dynamically added, then try putting some kind of meta-data in the <tr> tag, e.g. something like this:
<tr id="id" name="uid">
Then try the following with your jQuery (v.1.7 required):
$('#history-table tr').on('click', function(){
parent.viewEngine.pageChange('public-profile', 1, this.id, this.name);
});
This will likely require modification depending on how your page rendering works but it's a lot cleaner and easier to read having been removed from your main table markup.
Well that's because you're executing the function, not concatenating it. Try:
onclick='parent.viewEngine.pageChange("public-profile", 1, id, uid);'
Take this ->
$("#contribution-" + uid).click(function(){
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
And do two things:
1) Move it outside of the 'for' statement
As soon as the for statement is executed, the click function will be executed as well. The click function is not being supplied as a callback function in this for statement.
2) Change it to ->
$("tr[id^='contribution-'").on('click', function(){
var idString = $(this).attr("id").split("-"); //split the ID string on every hyphen
var uid = idString[1]; //our UID sits on the otherside of the hyphen, so we use [1] to selec it
//our UID will now be what we need. we also apply our click function to every anchor element that has an id beginning with 'contribution-'. should do the trick.
parent.viewEngine.pageChange('public-profile',1, id, uid);
});
This is my solution.

Categories

Resources