How to pass a variable in javascript to an HTML string - javascript

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.

Related

Is it possible to write a js variable into plain html?

I am counting my user specificated and dynamically appearing divs...
My situation:
<div class="grid-stack" data-bind="foreach: {data: widgets, afterRender: afterAddWidget}">
<div id="streamcontainer1" class="streamcontainer grid-stack-item" data-bind="attr: {'data-gs-x': $data.x, 'data-gs-y': $data.y, 'data-gs-width': $data.width, 'data-gs-height': $data.height, 'data-gs-auto-position': $data.auto_position}">
</div>
</div>
In PHP i can simply write my COUNT variable inside the html. That would look something like this:
<div id="streamcontainer<?php echo $count ?>" class="" ... and so on...>
How can i archive the same with JS/Jquery?
It's a DOM manipulation question. What do we have to work with? We're adding divs to the page, they have a particular class, and we want to give them an ID.
function assignIds(){
var list = document.getElementsByClassName('streamcontainer');
for(var i=0; i<list.length;i++){
if(list[i].id == undefined) // skip the ones that have already been done.
list[i].id = 'streamContainer' + i.toString();
}
}
Now we just have to run that function on some event so it will keep updating. If you just want to do it on an interval, that's simplest. (setInterval) But that could give you a bug, where there's a small amount of time where that ID hasn't been assigned yet. You could try listening to whatever AJAX/websocket process is streaming these things onto the page.
We'd need to know a bit more about your use case to know which event to attach it to.
Without a Javascript Reactive Framework (Vue.js, React, AngularJS) you can't do this.
What you can do with JS is set a content in element when DOM is loaded, example:
document.getElementById("myElement").textContent = "Hello World!";
Or
document.getElementById("myElement").innerHTML = "<span>Hello World!</span>";
OBS: .innerHTML can insert HTML tags and .textContent just insert texts.
You can make use of the text bindings in knockoutjs to display the javascript value in the HTML. There are lot of ko bindings which can help you. More reference here
var viewModel = {
javascriptVariable: "I am javascript string"
};
ko.applyBindings(viewModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<span data-bind="text: javascriptVariable"></span>

How to pass JSON data as parameters in JavaScript function while data appending to the div?

jQuery + JavaScript + Rails 4
prefix = "onward_"
json_data = {"367278":
{"bus_schedules":
{ "id": 367278,
"origin_id": 134,
"destination_id": 506
},
"drop_points": null,
"board_points": null,
"operator_name": "ABC"
}
}
json_data1 = JSON.stringify(json_data);
html = '<a href="#" id="'+prefix+'active_travel_filter_'+
operator_ids[i]
+'"onclick="removeTravelFilter('
+'\''+prefix+'\''+',\'travels\''+',\''
+json_data1+'\',\''+json_data1+'\')"
value="'+operator_ids[i]+'">'
+getOperatorName[operator_ids[i]]+'</a>'
console.log(html);
$("#active_fiters_blk").append(html);
//console.log output
ABC
But while append to the div I am getting this format, but it should be above format.
<a value="33" group)"}}')"="" group)"}}','{"367278":{"bus_schedules":{"id":367278,"origin_id":134,"destination_id":506},"drop_points":null,"board_points":null,"operator_name":"sre="" booking(ananth="" 367278":{"bus_schedules":{"id":367278,"origin_id":134,"destination_id":506},"drop_points":null,"board_points":null,"operator_name":"sre="" onclick="removeTravelFilter('onward_','travels','{" id="onward_active_travel_filter_33" href="#">ABC</a>
It should be an inline script only because I want each individual onclick event.
The HTML you're trying to insert, is this string:
0
When you place that into the DOM, your browser will be confused by the parameters of the onclick part: onclick="removeTravelFilter('onward_','travels','{" That last quote (") there will be interpreted as the end of the onclick parameter.
If you switch around the quotes in your JavaScript like this:
html = "<a href='#' id='"+prefix+"active_travel_filter_"+operator_ids[i]+"' onclick='removeTravelFilter("+"\""+prefix+"\""+",\"travels\""+","+json_data1+","+json_data1+")' value='"+operator_ids[i]+"'>"+getOperatorName[operator_ids[i]]+"</a>"
Then you should be fine:
<a href='#' id='onward_active_travel_filter_0' onclick='removeTravelFilter("onward_","travels",{"367278":{"bus_schedules":{"id":367278,"origin_id":134,"destination_id":506},"drop_points":null,"board_points":null,"operator_name":"SRE Booking(Ananth Group)"}},{"367278":{"bus_schedules":{"id":367278,"origin_id":134,"destination_id":506},"drop_points":null,"board_points":null,"operator_name":"SRE Booking(Ananth Group)"}})' value='0'>0</a>
I'm not saying this is the best way to pass those parameters to your function, but it works.
I'd maintain a dictionary associating anchor id names with their corresponding json data.
window.dataCache = {
"onward_active_travel_filter_90": {...},
...
}
Once element clicked I'll fetch the required json object.
$('a').click(function(){
var id = this.id;
var jsd = dataCache[id];
//pass to target function
foo(jsd);
});
Now if the anchor is added a little late into the page dom, I'd have to take care about attaching event handlers appropriately.
In jquery, we can just work with the .on() handler.
Explanation:
Well, we normally do something like $('element').click(function(){...});. This is usually executed in the jquery dom ready event:
$(function(){
$('element').click(function(){...});
});
The stretch of code in the dom ready event is executed once the DOM is ready for jquery consumption. Hence the click event will get attached to any element that exists in the DOM at that point of time.
Any subsequent addition of element into the web page, the click event handler will not get attached to it.
But we'd want such a functionality!
Hence we have to manually take care of it. Meaning create the element wire the event click handler appropriately, and then add it to DOM.
An alternative to this we have the jQuery .on() method. However, it functions differently from whats is described above. It listens for the click event which "bubbles" up on a target container.
Please read the docs of .on() to get a better idea.

How can I append dynamic variables to div with jquery?

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>

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

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