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");
Related
Any idea how make it with link? I try but nothing
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
$(".wd-entities-title").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
http://jsfiddle.net/nd46b23L/
The text you want to separate is inside an <a> tag - you should include that in your query or else the first space you'll encounter is the space in the <a> tag.
$(".wd-entities-title a").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
Slightly less verbose approach using html(function) which will iterate over all instances of matching selector <a> exposing the current html for each instance
Then use replace() to insert the break at first space and return the modified string
$(".wd-entities-title a").html((i, curr) => curr.trim().replace(' ', ' <br/>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
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?
I have a simple menu
<div class="nav-container desktop">
One
Twp
</div>
I am looping through this with jQuery each and then creating <li> tags with the complete <a.../a>.
$.each( $('.nav-container>a'), function(i, item){
var menupunkt = '<li>' + item + '</li>'
console.log(i, menupunkt);
});
Examples: http://codepen.io/anon/pen/bwbgap, https://jsfiddle.net/86g44ssp/
In my console I see only the following
<li>http://xyz.ccom/_index.php?page=_sub_papa&main=tw</li>"
Why don't I get the whole a? Because when I just print "item" I get the whole <a.../a>
item or this represent a DOM element. You're casting it to string when you treat it as as string. You can use item.outerHTML - the string you're looking for - in place of item.
$.each( $('.nav-container>a'), function(i, item){
var menupunkt = '<li>' + item.outerHTML + '</li>'
console.log(i, menupunkt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-container desktop">
One
Twp
</div>
NOTE
Not sure if there's an advantage to it but I would prefer:
$('.nav-container>a').each(function(i, item){
var menupunkt = '<li>' + item.outerHTML + '</li>'
console.log(i, menupunkt);
});
I have updated your fiddle, you just need to change
var menupunkt = '<li>' + item + '</li>'
to
var menupunkt = '<li>' + item.outerHTML + '</li>'
And there is no need to add extra wrapping or stuff, just get the HTML from outerHTML and you're done !
$.each( $('.nav-container>a'), function(i, item){
var menupunkt = '<li>' + $(item).text() + '</li>'
console.log(i, menupunkt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-container desktop">
One
Twp
</div>
I believe you want to access the outerHTML. I've included code from another SO answer:
jQuery, get html of a whole element
https://jsfiddle.net/86g44ssp/1/
The change I've made is here:
jQuery.fn.outerHTML = function() {
return jQuery('<div />').append(this.eq(0).clone()).html();
};
... other code here ...
var menupunkt = '<li>' + $(item).outerHTML() + '</li>'
This is caused by type conversion. When you do '<li>' + item + '</li>' the JavaScript runtime will try to convert item to a string. This is done "under the hood" by calling toString() method on the item, e.g. item.toString(). You can do forced type conversion by doing it explicit:
console.log(i, item.toString());
$( ".nav-container a" ).wrap( "<li></li>" );
This is the fastest way to wrap .nav-container a inside list element.
While looping $.each('.nav-container a', function(i,v) {}); each <a> are like object NOT at TEXT
if you want target specific elements use:
$.each('.nav-container a', function(i,v) {
var fullObject = $(this).html(),
link = $(this).attr('href'),
text = $(this).text();
});
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;
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();