Appending HTML Block to Selector with Variables - javascript

We have a fairly simple function called alert which basically creates an alert card (HTML element) anytime it is triggered. For reference we are using Eel to pass variables from Python and run this in a chrome wrapper.
<script type="text/javascript">
eel.expose(alert);
function alert(serial, time_key, card_color, screen_msg, ping) {
//clone card_template for each new alert
var clone = $("#card_template").clone();
clone.attr("id", serial);
clone.find("#message-card").attr("id", "message-card-" + serial + "-" + time_key);
clone.find("#python-data").attr("id", "python-data-" + serial + "-" + time_key);
//append clone on the end
$("#message-zone").prepend(clone);
document.getElementById("message-card-" + serial + "-" + time_key).classList.remove('bg-info');
document.getElementById("message-card-" + serial + "-" + time_key).className += card_color;
document.getElementById("python-data-" + serial + "-" + time_key).innerHTML = screen_msg;
var button_template = '<button type="button" class="btn btn-sm btn-danger">Clear</button>';
var selector_id = 'python-data-' + serial + '-' + time_key;
// $('#python-data-'+ serial + '-' + time_key).append(button_template);
$('#'+ selector_id).append(button_template);
$('#python-data').append(button_template);
if (ping === true)
document.getElementById('alert').play();
}
</script>
It clones and alters this element based on the type of alert that is received.
<div class="row justify-content-center" id="card_template">
<div class="col-md-8">
<div class="card bg-info" id="message-card">
<div class='card-body' id="python-data">
No messages
</div>
</div>
</div>
</div>
So this is where we are losing it. We want to append a HTML block to the cards after they are cloned and given unique ids. We have created a variable button_template that contains that code block. We can insert this code block easily into an element with a hardcoded id.
For example:
$('#python-data').append(button_template);
Will append the code block to the #python-data div in the original (clone source) card.
But we can't seem to get it to work when our selector is assembled from variables (necessary to address the cloned alert cards with unique ids).
Neither:
var selector_id = 'python-data-' + serial + '-' + time_key;
$('#'+ selector_id).append(button_template);
or
$('#'+ 'python-data-' + serial + '-' + time_key).append(button_template);
Works on the newly cloned cards.
TLDR Everything else on this function works. It clones our starting element, gives it, and its children, a unique id (assembled from variable), removes a class, adds a class and writes a message to the innermost div. This all works. All we need help with is appending a HTML block to a div with a unique, variable-based id.

This is the jsfiddle link (https://jsfiddle.net/abhishekraj007/w3m3r8oL/12/) I created to understand your code. Here I hardcoded unique ids while passing to function and its working. Something like this:
aalert("serial1", "a", "blue", "message", true)
aalert("serial2", "b", "blue", "message", true)
I've changed function name because alert is reserved Javascript function. Please check and let me know if this not what you want.

I have created a codepen from your code and its working fine there. The issue is must be somewhere else in your code.
My code.
JS
var serial = "123";
var time_key = "67868678";
var card_color = "bg-warning";
var screen_msg = "This is new message";
var clone = $("#card_template").clone();
clone.attr("id", serial);
clone.find("#message-card").attr("id", "message-card-" + serial + "-" + time_key);
clone.find("#python-data").attr("id", "python-data-" + serial + "-" + time_key);
//append clone on the end
$("#message-zone").prepend(clone);
document.getElementById("message-card-" + serial + "-" + time_key).classList.remove('bg-info');
document.getElementById("message-card-" + serial + "-" + time_key).className += " "+card_color;
document.getElementById("python-data-" + serial + "-" + time_key).innerHTML = screen_msg;
var button_template = '<button type="button" class="btn btn-sm btn-danger">Clear</button>';
var selector_id = 'python-data-' + serial + '-' + time_key;
$('#'+ selector_id).append(button_template);
$('#python-data').append(button_template);
HTML
<div class="row justify-content-center" id="card_template">
<div class="col-md-8">
<div class="card bg-info" id="message-card">
<div class='card-body' id="python-data">
No messages
</div>
</div>
</div>
</div>
<div id="message-zone"></div>
Here is a codepen.
I think this issue is related to duplicate IDs. Can you please check the unique IDs you are generating are really unique?

Related

Want to add delete functions for a list of date displayed

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

How to write the HTML code for the inline element showing an image for use in webpage?

I'm writing my first code in an interactive/follow-along program through Cengage (MindTap). The program is instructing me to "write the HTML code for the inline element showing the sky image to use in the webpage." I am supposed to create a variable named imgStr that stores this text string:
<img src='sd_skyMap.png' />
Where Map is the value of the mapNum variable (there are 23 files titled sd_sky0, sd_sky1, sd_sky3 and so fourth). It says to use the + operator to combine text strings together and to include single-quote characters within the text strings.
I cannot get the sky images to appear on the webpage to save my life.
I've attempted going through a tutor provided through my university but have still have no luck getting the image to display.
var imgStr = "<img src='sd_sky0 + sd_sky1 + sd_sky2 + sd_sky3 +
sd_sky4 + sd_sky5 + sd_sky6 + sd_sky7 + sd_sky8 + sd_sky9 +
sd_sky10 + sd_sky11 + sd_sky12 + sd_sky13 + sd_sky14 + sd_sky15
+ sd_sky16 + sd_sky17 + sd_sky18 + sd_sky19 + sd_sky20 +
sd_sky21 + sd_sky22 + sd_sky23' + mapNum + '.png' />";
document.getElementById("planisphere").insertAdjacentHTML() = imgStr;
Having inserted the code into jshint.com, it stated one warning and one unused variable.
(Bad assignment.)
document.getElementById("planisphere").insertAdjacentHTML() = imgStr;
and mapNum is an unused variable.
InsertAdjacentHTML takes two strings as parameters.
The first parameter is the position which takes one of four static values.
The second parameter is your HTML string to be inserted.
An example for what you want could be:
document.getElementById("planisphere").insertAdjacentHTML('afterbegin', imgStr);
You were nearly there, just append beforeend using the document.insertAdjacentHTML()
const imgStr = `<img src='sd_sky0 + sd_sky1 + sd_sky2 + sd_sky3 +
sd_sky4 + sd_sky5 + sd_sky6 + sd_sky7 + sd_sky8 + sd_sky9 +
sd_sky10 + sd_sky11 + sd_sky12 + sd_sky13 + sd_sky14 + sd_sky15
+ sd_sky16 + sd_sky17 + sd_sky18 + sd_sky19 + sd_sky20 +
sd_sky21 + sd_sky22 + sd_sky23' + mapNum + '.png' />`;
document.getElementById("planisphere").insertAdjacentHTML('beforeend', imgStr);
<div id = "planisphere">
</div>
There are two problems on your code, the first is you need to run trough the different image files and add each one separately. On the code you provided, all image's names are being combined as one.
The second problem is your use of the insertAdjacentHTML() function. The function expects as arguments the position of the new tag and the tag itself, none is being passed. Check here for a better explanation.
Assuming you have n images that you want to add as n tags, you can try something like this:
// variable to hold the total number of images used
var numberOfImages = 23;
// we loop trough all images, where i will count from 0 to numberOfImages
for (var i = 0; i < numberOfImages; i++) {
// on each step of the loop we add a new img tag with sd_skyi as source
document.getElementById("planisphere")
.insertAdjacentHTML('afterend', "<img src='sd_sky" + i + ".png' />")
}
If you use this exerpt as is, it will add 23 img tags to an element with id planisphere.

Optimize way to append element in html using jquery

What is the optimize way to append this element to my specific DIV Class using JQUERY. This will generate dynamic elements. I use .AppendTo then display dynamically the element inside <div class='parent-list-workorder'>.
Here's my code so far but it doesn't work:
$(document).ready(function(){
var ListOfWorkOrders = [];
$("#button").click(function(){
//var _WOID = $('.list-workorder-id').text();
var _WOID = $('#txtWOID').val();
//alert(_WOID);
$.ajax({
url:'getWorkOrders.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
for (var key in output) {
if (output.hasOwnProperty(key)) {
$("<div class='child-list-workorder'>
<div class='list-workorder'>
<div class='list-workorder-header'>
<h3 class='list-workorder-id'>" + output[key] + "</h3>
</div>
<p>" + Sample + ":" + key + "</p>
</div>
</div>").appendTo("<div class='parent-list-workorder'>");
//alert(output[key]);
}
}
console.log(output);
}
});
});
});
Am I missing something?
Your problem is in the code below:
.appendTo("<div class='parent-list-workorder'>");
The parameter of appendTo() should also be a valid selector.
you can try this instead:
.appendTo("div.parent-list-workorder");
granting that div.parent-list-workorder already exists.
You have two problems. First, you need to use a selector as an argument to .appendTo(), not an HTML string. Second, you need to remove or escape the newlines in the HTML string.
$("<div class='child-list-workorder'>\
<div class='list-workorder'>\
<div class='list-workorder-header'>\
<h3 class='list-workorder-id'>" + output[key] + "</h3>\
</div>\
<p>" + Sample + ":" + key + "</p>\
</div>\
</div>").appendTo("div.parent-list-workorder");

jquery each loop write data for each div

I hope this makes sense. I have an onclick and I am trying to write this data for each div with this.
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
I am cloning items but I can only write the data for one of them. How do I write data for each cloned item?
So with the above example I want tagtext to equal
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
Full Code
HTML
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<input type="submit" class="sc_options circle_counter_div" id="insert" name="insert" value="<?php _e("Insert", 'themedelta'); ?>" onClick="insertcirclecountershortcode();" style="display:none"/>
Script
// Insert the column shortcode
function insertcirclecountershortcode() {
var tagtext;
var start;
var last;
var start = '[circlecounters]';
var last = '[/circlecounters]';
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
var finish = start + tagtext + last;
if (window.tinyMCE) {
window.tinyMCE.execInstanceCommand(window.tinyMCE.activeEditor.id, 'mceInsertContent', false, finish);
//Peforms a clean up of the current editor HTML.t
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Extended Answer: After some more information was provided perhaps you're just missing the index and value properties on the loop. Its hard to tell, since little sample code is provided.
$('.test').each(function(i,v) {
var tagtext = $(v).html();
console.log(tagtext);
})
http://jsfiddle.net/4xKvh/
Original Answer:
Use use classes instead of an Id. Id's are only suposed to be used once on a page.
Since there should only be one occurance jQuery is filtering the result down to 1, even though the markup may have multiple elements with that Id on the page. This is to make use of the built-in browser function getElementById().
For proof checkout this jsFiddle
Using the class attribute is more appropriate for what you're trying to do.
jQuery('.clone_this').each(function() {
var tagtext = '[something][/something]';
})
And the markup:
<div class="clone_this"></div>
This will allow jQuery to return an array of elements like you're looking for
This is what I needed... Finally got it working.
tagtext = ' ';
jQuery('#circle_counter_div .circlecounter').each(function() {
tagtext += '[circlecounter rel="' + jQuery('.circle_size').val() + '" datathickness="' + jQuery('.circle_thickness').val() + '" datafgcolor="' + jQuery('.circle_color').val() + '" text="' + jQuery('.circle_text').val() + '" fontawesome="' + jQuery('.font_awesome_icon').val() + '" fontsize="' + jQuery('.circle_font_size').val() + '"][/circlecounter]';
});
var start = '[circlecounters]';
var last = '[/circlecounters]';
var finish = start + tagtext + last;

JQuery remove() not working with a two word id

I have a button <button onclick="takedown()"> take down </button> that creates a H1 and button with the id of the text in my text field and h1 at the end for the h1 and button at the end for the button the button has a onclick onclick="delete()". This is that function
function takedown(){
note = document.getElementById("noteinput").value;
idh1 = note + "h1";
idbutton = note + "button";
idcenter = note + "center";
$('<center id="' + idcenter + '"> <h1 id="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
For the delete function the remove() works only if the id of the button and the h1 is one word.
function deletenote(){
// First setting
var idbuttondelete = event.target.id;
var idh1delete = idbuttondelete.replace("button", "h1");
// Removing the button, h1,center
$('#' + idbuttondelete).remove();
$('#' + idh1delete).remove();
}
Does anybody know whats wrong or how to use JQuery to delete something if it has a two word id.
This will not behave as expected because ID attribute values cannot contain spaces. Replace the spaces with underscore or some other allowed character:
// don't forget VAR or you will have a global variable (bad)
var note = document.getElementById("noteinput").value.replace(/\s/g, '_');
How string.replace() works
First your replace in the delete function will fail if the user enters the word "button", "center", or "h1" as the javascript replace in the delete will only work on the first instance. To prevent the user from having spaces try the below with the delete function you have:
function takedown(){
var note = document.getElementById("noteinput").value;
var idh1 = "h1" + note.replace(/\s/g, '_');
var idbutton = "button" + note.replace(/\s/g, '_');
var idcenter = "center" + note.replace(/\s/g, '_');
//the above 3 variables will use _ instead of space
$('<center id="' + idcenter + '"> <h1 id="' + idh1 + '">' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote()"> Delete </button> </center>').appendTo("body");
}
If you do not have control over the ID's and need to do this for a lot of objects you can change them all at once (buttons in this case)
$('button').each(function () {
var id = $(this).attr('id');
id = id.replace(/\s/g, '_');
$(this).attr('id', id);
});
And then you can reference all the buttons by ID using a _ instead of space. Otherwise do as others suggested and use a selector other than ID
Since you're using jQuery, you could try this:
var note = $("#noteinput").val().replace(/\s/g, '_');
idcenter = note + "center";
$('<center id="' + idcenter + '"> <h1>' + note + '</h1> <button id="'+ idbutton +'" onclick="deletenote(idcenter)"> Delete </button> </center>').appendTo("body");
}
function deletenote(id){
$('#' + id).remove();
}
You don't need to individually remove the child elements of your tag. I would also recommend against using the center tag, go with a div and center the contents with CSS rather than using center.
I also refactored your function. It's much better to pass in your values and this way, the function is more resuable and testable
As mentioned in the other answers...spaces in ids is bad practice!
BUT if you really need "two words" in your ids, instead of the query selector $, you can use:-
document.getElementById("doesnt mind spaces").remove();

Categories

Resources