How can I append dynamic variables to div with jquery? - javascript

I'm having some difficulty getting this to work. What I want to do is take dynamic variables from the onclick and place them into a div I am appending to another div in the document. Since each each item will have variables associated from a database query, I figured populating the buildTicket() variables from the database would be easier.
I know I'm doing something wrong. I just can't figure out what.
If you have a better way, I'm all ears.
Here is my javascript:
<script type="text/javascript">
$(document).ready(function(){
$(function() {
buildTicket = function(eventname,ticketprice,venueid,userid) {
$(".ticketbtn").click(function(){
$(".ticketwindow").append("<div class='ticket'>" + eventname + " - " + eventprice + "</div>");
});
}
});
</script>
Here is my HTML:
<div class="ticketbtn" onclick="buildTicket('Some Show','12.00','1','2');">
<img src="assets/images/tixicon.png" alt=""> <div class="eventname">Some Show</div>
<div class="ticketprice">Adult - 12.00 </div>
</div>
<div id="ticketwindow">
</div>
Can someone help me figure this out?
(sorry for the code formatting. Still trying to figure out how to use stackoverflow's forms properly.)
Thanks,
Joe

Firstly, $(function() { is equivalent to $(document).ready(function() { so you only need one of them.
Secondly, you don't need to use the onclick attribute if you are binding to click() with jQuery, or vice versa.
If you just use the onclick attribute, then you can remove your document ready handler, and your click() binding, all together and simply define the buildTicket() function.
Thirdly, the eventprice variable is misnamed in buildTicket().
Here is a working fiddle, using jQuery to bind to the click event of your button div. http://jsfiddle.net/BdJAL/

You are binding the onClick listener on click of your button.
If you must use the onClick element attribute then the following code will work although you should become familiar with the principles of Unobtrusive JavaScript.
$(document).ready(function(){
var buildTicket = function(eventname,ticketprice,venueid,userid) {
$("#ticketwindow").append("<div class='ticket'>" + eventname + " - " + eventprice + "</div>");
});
});

I quote from your question:
"I figured populating the buildTicket() variables from the database would be easier."
If you want to get hold of database data in your JavaScript how about making an HTTP request to get it. Obviously, you could do this in the normal XJAX way using XMLHttpRequest:
http://www.w3schools.com/xml/xml_http.asp
Or you could call up some server side code to produce JSON for you and reference it in a <script> tag e.g.
<script type="text/javascript" src="../js/jsonFromServerSideCode.jsp"></script>

Related

How to pass a variable in javascript to an HTML string

I am trying to pass a variable to the inline JavaScript but its not working.
var namealert = key;
$("#alerta").append("<div class='alert_item clearfix'><a href='#' id='delete_alert' onclick='localStorage.removeItem('" +namealert+ "'');'><img width='15px' style='margin-right:10px;opacity: 0.5;' src='img/error.png'></a><div class='date'>"+obj['0']+"</div><br><div class='title'>"+obj['1']+"</div><br><div class='msg'>"+obj['2']+"</div><br><a href='#' id='candidatar' onclick='candidatar()'><img width='100px' style='margin-right:10px;opacity: 0.8;' src='img/disponivel.png'></a></div>");
The output is:
<a href="#" id="delete_alert" onclick="localStorage.removeItem(" alerts_1481117090'');'>...</a>
I need it to be localStorage.removeItem('alerts_1481117090');
A lot of people have downvoted you but nobody's really given a concrete example of what we mean by "adding event handlers", since technically the onclick method you are using is an event handler (just not a good way to do what you are trying to do).
var $newElement = $("#alert")
.append("<div class='alert_item clearfix'>Click me!</div>");
// $newElement is a jQuery object returned by .append()
// set a click event handler. this is much better than doing the html
// onClick method you had in your question, because it requires no
// stringified javascript code evaluation.
$newElement.on("click", function (ev) {
alert("Hey, I was clicked! " + ev.target);
// your local storage code here instead
});
.alert_item {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="alert">
<!-- elements to append here -->
</div>
You're probably just getting into javascript by the looks of it, but don't get discouraged. It's a strange language for sure, but once you get more of a feel for how things work, there's a great book called "JavaScript, the Good Parts" on how the language can be used safely and powerfully.

how to send more than 1 arg to JS function within a string?

updat
the function name wasnt the problem (accidently copied wrong)
the problem was that i was sending string!
thanks to mplungjan problem solved!!
this is my code:
$("#GVHistory").append("<tr><td>" + order.OrderID +"</td><td><a href='#dialogHistory' id='ShowDet' data-role='button' data-transition='pop' onclick='function(" + order.OrderID +"," + order.Total + ")'>Details</a></td></tr>");
I have a JavaScript function:
function fun(id,t) {
$("#HistHead").empty();
$("#HistHead").append(t + id);
}
when I send 1 argument it works good, but more than 1 it fails.
Plus the data-roll doesn't effects, any thoughts?
Your function is named fun and not function. Please make sure to use the right name in the onclick event.
Regards
in your onclick event in the html, the function is "function" whereas the function is called "fun".
The following code works :
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
</head>
<body>
<div id="HistHead">Test</div>
<table id="GVHistory"></table>
<script>
$(document).ready(function(){
order ={OrderID:12,Total:15};
$("#GVHistory").append("<tr><td>" + order.OrderID +"</td><td><a href='#dialogHistory' id='ShowDet' data-role='button' data-transition='pop' onclick='fun(" + order.OrderID +"," + order.Total + ")'>Details</a></td></tr>");
});
function fun(id,t) {
$("#HistHead").empty();
$("#HistHead").append(t + id);
}
</script>
</body>
For a better understanding, i want to explain in more detail.
Let's assume: order.OrderID = "orderId1" and order.Total = "total100"
At the moment where you append this <tr> to the DOM, the value of order.OrderID and order.Total are appended to your onclick function, not the variables.
Your onclick was rendered to onclick="fun(orderId1, total100)" If you click this, you will get an error, because the variable orderId1 and variable total100 are not defined. The right solution was to add some kind of quotes, to get two strings. You have to escape the quotes with \ otherwise the quotes will destroy the string that you are trying to append, in your first code snippet.
Calling click functions inline is always a bit messy and specially if you want to hand over more than one string or variables. I always take custom data attributes. data-xxx="xxx" to hand over something.
$("#GVHistory").append("<tr><td>" + order.OrderID +"</td><td><a href='#dialogHistory' class='ShowDet ui-btn' data-transition='pop' data-orderid='"+order.OrderID+"' data-ordertotal='"+order.Total+"'>Details</a></td></tr>");
$(".ShowDet").unbind("click").on("click", function (){
var id = $(this).data("orderid");
var t = $(this).data("ordertotal");
$("#HistHead").empty().append(t + id);
});
To your second problem with data-role="button"
This custom jquery mobile attribute, does only something if it's inside the DOM when the page is loaded the first time. If you want to append someting dynamically, you have to call the corresponding widget. In case of the button you just have to call $(".ShowDet").button() to intitalize the button markup. But a much easier way for buttons is to use the css classes to style them. .ui-btn

while loop in Javascript with concatenation

I'm trying to make a while-loop in my Javascript.
So far, I've got this:
<script>
$(document).ready(function(){
var i=0;
while (i<9999) {
$(".add_new_item_field" + i).hide();
$(".add_new_item_button" + i).click(function(){
$(".add_new_item_field" + i).slideToggle("slow");
});
i++;
}
});
</script>
Goal is to make this work:
<div class="add_new_item_button1"></div>
<div class="add_new_item_button2"></div>
<div class="add_new_item_button3"></div>
...
<div class="add_new_item_field1">Show me something</div>
<div class="add_new_item_field2">Show me something</div>
<div class="add_new_item_field3">Show me something</div>
...
But for some reason, it's not working. Am I missing something here?
Your problem is that the concatenation in the line $(".add_new_item_field" + i).slideToggle("slow"); happens when you click one of the divs. Yet, the loop that had set up the handlers was run long ago then and i already has a value of 9999. Use a closure as #David demonstrated to avoid this.
However, I feel this is the wrong approach. Setting up 10000 click handlers, and executing 20000 jQuery selection does make your page very, very slow. Use one common class for the button, and one common class for the fields. If you can't depend on a certain document order, give them unique ids to refer to each other - but not classes.
Then hide all the fields with one single line of CSS, and use event delegation for the buttons to fire 1 single function that looks up the field by id from the data attached to the clicked button.
<style>
.add_new_item_field { display:none; }
</style>
<!-- placing the stylesheet here also avoids flickering.
Even better would be of course if it was written dynamically by JS, for not
hiding the fields in clients that do not support JavaScript -->
<script src=/"jquery.js"></script>
<script>
jQuery(function($) {
$(document).on("click", ".add_new_item_button", function(e) {
var id = "field"+$(this).data("field");
$('#'+id).show();
});
});
</script>
<div class="add_new_item_button" data-field="1"></div>
<div class="add_new_item_button" data-field="2"></div>
<div class="add_new_item_button" data-field="3"></div>
...
<div class="add_new_item_field" id="field1">Show me something</div>
<div class="add_new_item_field" id="field2">Show me something</div>
<div class="add_new_item_field" id="field3">Show me something</div>
...
I’m guessing that i is not what you expect it to be in the handler, because when the handler executes i has already maxed out to 9999. To fix that, you need to bring the variable into the handler closure, something like:
var i=0;
while (i<9999) {
$(".add_new_item_field" + i).hide();
$(".add_new_item_button" + i).click((function(i) {
// i is now saved in this closure
return function() {
$(".add_new_item_field" + i).slideToggle("slow");
};
}(i)));
i++;
}
Sidenote: I’m not really sure this is the best way to solve your actual task here though, looping and attaching 9999 event handlers seems unnecessary...
I think you are using the class the wrong way. You can assign a click handler to all objects of the same class. But you are trying to use the class specifier as an ID and are trying to assign the handler to each seperate object. You wouldn't do the same for the behavior and layout of a link/url? (link) would you?
Read this: jQuery: How do I add a click handler to a class and find out which element was clicked?
You want to setup the handler for a class, specify your divs as that class. I not abusing the class specifier as some sort of ID.
You are creating a closure in your click handler which captures the i variable, not it's value. This means all the click functions will contain the value 9999 which the value of the variable at the end of the while loop.
You can fix it by creating a function that set's the click handler.
var setClick = function(index) {
$(".add_new_item_button" + index).click(function(){
$(".add_new_item_field" + index).slideToggle("slow");
}
}
And use it in your while loop.
while (i<9999) {
$(".add_new_item_field" + i).hide();
setClick(i);
i++;
}
Now the value of i is correctly captured by your click handler

Use getElementById() on non-current HTML document

Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method

JQuery Copy text & paste into textarea

I've created a javascript function that will take a hidden span, copy the text within that span and insert it into a single textarea tag on a website. I've written a function in JavaScript that does this (well, kinda, only after a few clicks), but I know there's a better way - any thoughts? The behavior is similar to a Retweet for twitter, but using sections of a post on a blog instead. Oh, and I'm also calling out to jquery in the header.
<script type="text/javascript">
function repost_submit(postID) {
$("#repost-" + postID).click(function(){
$("#cat_post_box").empty();
var str = $("span#repost_msg-" + postID).text();
$("#cat_post_box").text(str);
});
}
</script>
Based on the comment in your question, I am assuming you have something like this in your HTML:
copy post
And I am also assuming that because you are passing a post ID there can be more than one per page.
Part of the beauty of jQuery is that you can do really cool stuff to sets of elements without having to use inline Javascript events. These are considered a bad practice nowadays, as it is best to separate Javascript from your presentation code.
The proper way, then, would be to do something like this:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
And then you can have many more that look similar:
<a href="#" id='copy-5' class='copy_link'>copy post</a>
<a href="#" id='copy-6' class='copy_link'>copy post</a>
<a href="#" id='copy-7' class='copy_link'>copy post</a>
Finally, you can write code with jQuery to do something like this:
$(function() { // wait for the DOM to be ready
$('a.copy_link').click(function() { // whenever a copy link is clicked...
var id = this.id.split('-').pop(); // get the id of the post
var str = $('#repost_msg-' + id); // span not required, since it is an ID lookup
$('#cat_post_box').val(str); // empty not required, and val() is the proper way to change the value of an input element (even textareas)
return false;
});
});
This is the best way to do it even if there is only one post in the page. Part of the problem with your code is that on the first click it BINDS the function, and in the subsequent clicks is when it finally gets called. You could go for a quick and dirty fix by changing that around to just be in document.ready.
$("#repost-" + postID).click(function(){
$("#cat_post_box").val(''); // Instead of empty() - because empty remove all children from a element.
$("#cat_post_box").text($("#repost_msg-" + postID).text());//span isn't required because you have and id. so the selector is as efficient as it can be.
});
And wrap everything in a $(document).ready(function(){ /Insert the code here/ }) so that it will bind to $("#repost-" + postID) button or link when the DOM is loaded.
I had a problem with Paolo's example when I clicked on the link the text that appeared in #cat_post_box was "object Object". Once I added ".text()" to the end of that statement I worked.
var str = $('#repost_msg-' + id).text();
Thanks for you example Paolo!

Categories