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;
Related
I'm working on a .NET Core project for my company where work orders are loaded from our SQL database using Entity Framework, filtered and then displayed as markers on a map through Google Maps API for our installers.
We have two types of filters: one that gets included in an Ajax POST, and one that filters locally to decrease load times and performance issues. What I'm trying to do is load the local filter items (lists that are included in the response when calling the initial Ajax POST). If the list of filter items exceeds 5 items, I want them to collapse to only 5 items and insert an anchor which expands (utilizes jQuery's toggle()) showing the rest of the items in that list.
This is the excerpt from the JavaScript function which takes care of that:
filterItems
.forEach((filterItem, i) => {
var localItem = '<label class="' + selectorContainerClass
+ ' selectorContainer" id="' + selectorContainerIdPrefix + filterItem.key
+ '"><input id="' + convertValToEng(filterItem.value)
+ '" type = "checkbox" class="filled-in navy" name="' + inputName
+ '" value="' + filterItem.key
+ '" onchange="localFilter(this, this.value)" /><span class="selector-value">'
+ filterItem.value
+ '</span> <span id="' + paramName + 'Cnt__' + filterItem.key
+ '" class="selector-count"></span></label ><br />';
document.querySelector("#" + colId).insertAdjacentHTML('beforeend', localItem);
if (i >= 5) {
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).addClass("collapse");
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key).toggle(100);
$("#" + colId + " #" + selectorContainerIdPrefix + filterItem.key + " + br").toggle(100);
}
});
if (filterItems.length > 5) {
//TODO: Fix the bug here; the .filter-collapse element is not being inserted under local installers.
var newEl = '<a class="filter-collapse" onclick="toggleFilterExpand(false, this)";><i class="material-icons">expand_more</i></a>';
document.getElementById(colId).insertAdjacentHTML('beforeend', newEl);
}
I should be getting a newEl inserted under the "Installer" column (8 installers, 3 of them not being displayed), but I'm not. I've tried jQuery's after() and insertAfter() methods, but neither of those worked. newEl is being generated for the "Area" column, as it should, but for the "Installer" column it's not.
I've also tried inserting the element manually through the console window with the exact same code and it works.
Would appreciate some help with this as I feel lost regarding this issue.
Thanks.
It turned out to be a stupid mistake on my end where I was removing the element newEl from the all the other filter lists before inserting a new one to the currently iterated one.
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
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'm trying to dynamically generate a form after an ajax request. Below is the relevant code sample :
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form').append('<label for=' + i + '>' + i + '</label>' +
'<input id=' + i + ' value=' + field + '>');
}
My problem is that, when var i and var field are strings with blank spaces like "Hello world", my label and inputs will be like <label id="Hello" world=""> and <input value="Hello" world="">. However, the label text will be displayed correctly i.e. <label>Hello world</label>.
I've no idea what kind of sorcery that is, but I'll be very grateful for any help. Thanks in advance.
There's a much more robust way of doing this.
for (var i in response.responseJSON[0].fields) {
var field = response.responseJSON[0].fields[i];
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
}
You won't have to worry about the content of the strings as jQuery and the DOM will handle it for you. Not to mention this is much easier to read.
Use " to enclose the attributes.
$('#properties_form')
.append('<label for="' + i + '">' + i + '</label>' +
'<input id="' + i + '" value="' + field + '">');
EDIT
This will break for the cases where the value for i is something like This "works". Best solution is to append as jQuery or JS objects rather than using HTML string just like Daniel's answer.
Following snippet contains the correct fix for this. Updated based on the answer from Daniel.
i = 'Hello "World"';
field = 'Hello "World"s';
$('#properties_form')
.append($('<label>').attr('for', i).text(i))
.append($('<input>').attr('id', i).val(field));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="properties_form"></div>
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();