This question already has answers here:
How can I apply a variable as an element ID with JavaScript?
(5 answers)
How can I pass an element to a function from onclick?
(2 answers)
Closed 7 months ago.
I have this function:
function displayInputIntro() {
var submitbutton = document.getElementById('submitbutton')
var intro = document.getElementById('Intro')
var introNewSection = document.getElementById('intro-row')
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id="intro">';
submitbutton.style.display = ''
}
This function displayInputIntro() can be called multiple times, and it will insert this new section into the body of the HTML as many times as one decides to do so. Problem is, I want to add a unique identifier, so that if I were to add something like this:
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id="intro">Remove Input';,
and click on Remove Input, then it would delete the input, not all of them.
I have tried something like this:
var uniqueID = new Date()
introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id="' + uniqueID '"'>Remove Input';, and click on `Remove Input`, then it would delete the input, not all of them.
but that doesn't work. How can I do this?
you are passing an string to html code, not the real JS variable.
You can try something like this thant I found in How can I apply a variable as an element ID with JavaScript?:
var id = new Date();
var html ='<li id="' + id + '">'
+ '<input type="image" id="' + id + '" src="images/subtract.png" onclick="javascript:deleteProduct(this.id)" href="#">'
+ id
+ '</li>';
Related
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?
This question already has answers here:
Encode URL in JavaScript
(22 answers)
Closed 6 years ago.
I have a jQuery code where I am trying to append to an existing div a label tag which contains a URL. Below is the code:
var strURL = 'http://financials.morningstar.com/ratios/r.htmlt=tup®ion=usa&culture=en-US';
var str = '<li>';
str += '<label style="font-family:Arial;">' + strURL + '</label>';
str += '</li>';
$('#existingDiv').append(str);
When the page is actually displayed it shows the URL as:
http://financials.morningstar.com/ratios/r.html?t=tup®ion=usa&culture=en-US
A quick fix would be to add the label as a text as a second step after appending the html to the existingDiv - see demo below:
var strURL = 'http://financials.morningstar.com/ratios/r.htmlt=tup®ion=usa&culture=en-US';
var str = '<li>';
str += '<label style="font-family:Arial;">' + '</label>';
str += '</li>';
$('#existingDiv').append(str);
$('#existingDiv label').text(strURL);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="existingDiv"></div>
I have a written a javascript which will return the value in the variable, in the title property.
It is not returning the values with spaces, when i execute the below code it is returning the last value as 'ashok' instead of 'ashok sensiple'
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title='
+ ltenantName
+'>'
+ ltenantName.split(',').length
+'</div>';
return ltenantNameLength;
HTML attribute values containing spaces must be quoted.
You are generating the title attribute without quotes around the value.
Your code:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title='
+ ltenantName
+'>'
+ ltenantName.split(',').length
+'</div>';
document.body.appendChild(document.createTextNode(ltenantNameLength));
As you can see sensiple is a new attribute and not part of the value of the title attribute.
Add quotes:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = '<div style="cursor:Pointer" title="'
+ ltenantName
+'">'
+ ltenantName.split(',').length
+'</div>';
document.body.appendChild(document.createTextNode(ltenantNameLength));
Better yet, don't try to mash strings together in JS to make HTML:
var ltenantName = 'Sensiple,new-tenant-001,tenant-new,Tenant_1208,ashok sensiple';
var ltenantNameLength = document.createElement('div');
// This normally indicates a link. If you want a link, why not use <a>?
ltenantNameLength.style.cursor = "pointer";
ltenantNameLength.title = ltenantName;
ltenantNameLength.appendChild(
document.createTextNode(
ltenantName.split(',').length
)
);
document.body.appendChild(ltenantNameLength);
I have a div in my page which contains a table with inputs (with ids), I have some conditions and functions on the inputs written in the Javascript code. What I'm trying to do is to make a button (add new) that clones exactly the same div in the page but with same conditions and functions on the new elements and the submit button to work for each separately.
I tried this :
$('#button-add').bind({
click: function()
{
$("#repeat").clone().appendTo("#add");
}
});
the problem is that I get the same appearance for the div but the functions are not working (because the inputs have the same id) and i cannot submit only that block (new div).
Is there a simpler way to achieve that?
Just in case if you ignore making clones.
The way of doing it using a dynamic id.
Say if appending div with different id for every element using random function in javascript.
$('#add-item').on('click', function (e) {
var num = Math.floor(Math.random() * 90000) + 10000;
var numtd = Math.floor(Math.random() * 50000) + 10000;
$('<tr id="trowdynamic_' + num + '">' +
'<td>' +
'<div class="input-group">' +
'<input type="hidden" id="selected_item_' + numtd + '" name="selected_name" />' +
'<input type="text" name="Inv_Itemsdetail" value="" class="Itemsdetail-typeahead_' + numtd + ' input-search" autocomplete="off" data-provide="typeahead" />' +
'<input type="hidden" id="Inv_Itemsdetail_' + numtd + '" class="auto-complete" name="Itemxx[]" />' +
'<span class="input-group-btn">' +
'<i class="fa fa-plus"></i>' +
'</span>' +
'</div>' +
'</td>' +'</tr>').appendTo('#yourcontainer_id');
});
Now using jQuery call for same id elements-
Now Note this way I have every element starting with same id name plus a random number.
$('input[id^="selected_item_"]')
Since you're going to duplicate the div, you should not use IDs, because their uniqueness would be compromised. But you can use css class names ($('.className')) or custom data attributes ($('[data-my-id=xxx]')) to address your inputs because they do not need to be unique.
Second, you need to clone your div so that the events attached to your inputs are cloned as well. Check out the jQuery doc for .clone([withDataAndEvents] [,deepWithDataAndEvents]) (http://api.jquery.com/clone/).
Since the new div is created in new space ie, in #add, select the new div as
#add #repeat
{
} // in css
in jquery use next or siblings or children etc to select the new div
For example
see the FIDDLE
I'm adding some amount of div based on the xml list which contain some data and url
Currently trying to use onClick but it doesn't seems right on the js that loads the div part.
//retrieve each of the data field from ITEM
var url = item.find('url').text();
var image = item.find('project-img').text();
var title = item.find('id').text();
var desc = item.find('desc').text();
var html;
//Embed them into HTML code
html = '<div class="project"><img src="' + image + '" alt="' + title + '" />';
html += '<div class="info">';
html += '<div class="title">'+title+'</div>';
html += '<div role="button" class="launch" onclick="window.open('+url+',"mywindow");">Launch Website</div>';
html += '<div role="button" class="more">View More</div>';
html += '</div></div>';
I think it somehow get mess up on the adding 'url' part with ' or "
Or there would be a much easier way to call a link on such situation?
as per your requirement correct syntax would be
html += '<div role="button" class="launch" onclick="window.open(\''+url+'\',\'mywindow\');">Launch Website</div>';
I think you have an error (the only one i could spot), so try the following:
onclick="window.open('+url+',\'mywindow\');"