Trying to add the text dynamically to the same span. Have generated an index to the id so that based on index thought to add the text.
This is what i have tried.
Expected output is I need to create one more span with same id but different index and append my array values to the span with index values.
Expected Output Example:
<span id="test-0">test</span>
<span id="test-1">Demo</span>
HTML:
<span id="test-{{$index}}"></span>
JS:
var arr = [{"Name":"test"},{"Name":"Demo"}];
for(var i=0; i<arr.length;i++){
txt = arr[i].Name;
$('#test-'+i).text(txt);
}
Tried Demo:
Demo Link
Try this:
$('#test-'+i).text(txt);
Assign value in text() function
$('#test-'+i).text();
to
$('#test-'+i).text(txt);
You can use string builder, such as:
var arr = [{ "Name": "test" }, { "Name": "Demo" }];
for (var i = 0; i < arr.length; i++) {
txt = arr[i].Name;
document.write("<span id=test-" + i + ">" + txt + "</span>");
}
Try this : You can have a div to add span which will have dynamic id and text from array.
HTML-
<div id="test"></div>
javascript: -
var arr = [{"Name":"test"},{"Name":"Demo"}];
var $text = $('#test');
for(var i=0; i<arr.length;i++){
$text.append('<span id="test-'+i+'">'+arr[i].Name+'</span>');
}
JSFiddle DEMO
The fiddle you had given is wrong. which has been edited as follows.
check fiddle here
var arr = [{"Name":"test"},{"Name":"Demo"}];
for(var i=0; i<arr.length;i++){
//append existing text to new value from array
var txt = $('#test'+i).text() + arr[i].Name;
$('#test'+i).text(txt);
}
If you actually want to use angular, you are going about it all wrong. Angular doesn't play well with html elements added elsewhere, they have to be compiled first so angular can bind to them. In this instance you could use ng-repeat to bind a list to a series of spans:
<span ng-repeat="item in [100, 200, 300, 400]" id="test-{{$index}}">
Index is {{$index}}<br/>
</span>
You also need to include angular in your fiddle and have an element with the ng-app tag (fiddle). Using angular you would also have a named controller and set a property on the scope to your array, but that is outside the bounds if this question.
Related
Using a for loop in javascript to create multiple html div's.
for(var i = 0; i < lines.length; i++){
document.getElementById("rotate").innerHTML+="<div><div><a href='' id='idWithIndex_i'>";
document.getElementById("idWithIndex_i").innerHTML+=lines[i];
document.getElementById("rotate").innerHTML+="</a></div></div>";
}
The html should look like this for index 0:
<div>
<div>
<a href='' id='idWithIndex_0'>
line1
</a>
</div>
</div>
I want to define the index in the id of the anchor. How can I change the javascript? Thanks.
The problem is in this line:
for(var i = 0; i < lines.lenght; i++){
lenght does not exists in javascript. Use length instead.
Also, for concatenation, use this:
document.getElementById("rotate").innerHTML+='<div><div><a href="" id="idWithIndex_'+i+'">';
or using string templates from ES6 in order to obtain a cleaner solution.
document.getElementById("rotate").innerHTML+=`<div><div><a href="" id="idWithIndex_${i}">`;
Right now your i is just a part of a string, here's what you want:
for(var i = 0; i < lines.length; i++){
document.getElementById("rotate").innerHTML+="<div><div><a href='' id='idWithIndex_" + i + ">";
document.getElementById("idWithIndex_" + i).innerHTML+=lines[i];
document.getElementById("rotate").innerHTML+="</a></div></div>";
}
id='idWithIndex_"+i+"'
You need to break out of the string and then concatenate with + the variable.
In steps:
"idWithIndex_" is the first part of your fixed string
with + you append something to the former part
we append the variable i
after the variable we append the rest of the fixed string using another +.
Also type in your for loop: length instead of lenght
There is a way nicer way to do this:
var counter = 0;
//method 1 - createElement
document.querySelector("#add_method1").addEventListener("click", function(){
//add a click event to the add button
var node = document.createElement("div"); //create a new element
var innernode = document.createElement("div"); //create second node
var linknode = document.createElement("a");
linknode.setAttribute("href", '');
linknode.setAttribute("id", "idWithIndex_" + counter) //set id
linknode.innerHTML += "test"+counter; //lines[i] in your code;
counter++;
//time to append
innernode.appendChild(linknode);
node.appendChild(innernode);
document.getElementById("rotate").appendChild(node);
},true);
//method 2 - cloneNode
document.querySelector("#add_method2").addEventListener("click", function(){
//add a click event to the add button
var cloned = document.querySelector(".copynode").cloneNode(true); //true for deep cloning
cloned.removeAttribute("class"); //remove class
var a = cloned.querySelector("div > a"); //select link
a.setAttribute("id", "idWithIndex_" + counter) //set id
a.innerHTML += "test"+counter; //lines[i] in your code;
counter++;
//time to append
document.getElementById("rotate").appendChild(cloned);
},true);
/*css for method 2 */
.hidden {
display: hidden;
}
<div id="rotate"></div>
<button id="add_method1">add using document.createElement</button>
<button id="add_method2">add using element.cloneNode</button>
<!-- html for method 2 -->
<div class="copynode hidden">
<div>
</div>
</div>
for(var i = 0; i < lines.length; i++){
document.getElementById("rotate").innerHTML+="<div><div><a href='' id='idWithIndex_"+i+"'>";
document.getElementById("idWithIndex_"+i).innerHTML+=lines[i];
document.getElementById("rotate").innerHTML+="</a></div></div>";
}
First off, you have a type at .lenght.
Also, The "i" is not a part of the string, its a variable, so you need to add the value of i as the id od the div, not the string "i".
Try this
for(var i = 0; i < lines.lenght; i++){
document.getElementById("rotate").innerHTML+="<div><div><a href='' id='idWithIndex_"+i+"'>";var id = "idWithIndex_"+i;
document.getElementById(id).innerHTML+=lines[i];
document.getElementById("rotate").innerHTML+="</a></div></div>";
}
var lines = [1,2,3,4]
var i;
for(i = 0; i < lines.length; i++){
document.getElementById("rotate").innerHTML+="<div><div><a href='' id='idWithIndex_"+i+"'> " + lines[i]+"</a></div></div>";
}
<div id="rotate">Hi</div>
As others have mentioned you need to either concatenate the values into the string or use a template string to inject them into the string.
I wanted to suggest a little refactoring. DOM access is relatively expensive, with 3 getElementById queries and 3 changes to the DOM via innerHTML per loop, that creates a lot of unnecessary overhead. In most cases it probably doesn't matter, but if there were a lot of items in lines, it could bring the browser to its knees. It would be better to build a string of the HTML you are injecting and just inject once:
let lines = ['a', 'b', 'c'];
let linesHtml = ''; // buffer for the HTML we are building
for(let i = 0; i < lines.length; i++) {
// there is no need to create the link and then inject content into it,
// we can just inject the content right into the element in the HTML
linesHtml += `<div>
<div>
<a href='' id='idWithIndex_${i}'>
${lines[i]}
</a>
</div>
</div>`;
}
// now that we know what we are injecting, make a single DOM update
document.getElementById("rotate").innerHTML += linesHtml;
div {
border: 1px solid #000;
padding: 3px;
}
<div id="rotate"></div>
I used a template literal instead of a normal string because it allows you to easily create multi-line strings, for easily readable embedded HTML. This can help a lot with the maintainability of your code. Any recent browser supports them (IE isn't recent; if you have to support it, you have my condolences).
I have this array:
var names = [
"Name1",
"Name2",
"Name3"
];
I converted this to Unorder List for HTML:
for(i = 0; i < names.Length; i++){
text += "<li>" + names[i] + "</li>";
}
text += "</ul>";
document.getElementById("choices").innerHTML = text;
Now, I got this:
Name1
Name2
Name3
And I am happy with the result. But now I want if someone click on Name2 so it alert me the index of the value. What I want is it should in Mobile App (Cordova) so that when user click on List Item it will show details on other activity (Some other page).
PS:
I checked:
var index = $( "li" ).index( this );
and
var index = $("ul li.active").index();
But seems like these are not made for me.
May be I should Dynamically assign ID's to each <li> item? What should I do now?
You can directly get index using index method.
$("li").click(function () {
alert($(this).index());
});
If you have multiple ul elements on page and you want to bind click event to some specific element you can do this.
To bind click on element by id
$("#YourUlId li").click(function () {
alert($(this).index());
});
To bind click event by class
$(".YourUlClass li").click(function () {
alert($(this).index());
});
$( "li" ).index will return elements index with respect to all li elements in DOM.
You need to use .index() with jquery object of clicked element. It will return the elements index in its parent container:
var index = $(this).index();
Pass the id dynamically in for loop
for(i = 0; i < names.Length; i++){
text += "<li id="+i+">" + names[i] + "</li>";
}
assign the click event, u will get the id by below code
$(li).click(function(){
alert($(this).attr("id"));
});
use this for getting the current element
<ul>
<li>Male</li>
<li>Female</li>
</ul>
<script>
$("li").click(function(){
alert($(this).index())
})
</script>
See below working snippet
var names = [
"Name1",
"Name2",
"Name3"
];
var text='<ul>';
for(i = 0; i < names.length; i++){
text += "<li>" + names[i] + "</li>";
}
text += "</ul>";
document.getElementById("choices").innerHTML = text;
$('li').on('click',function(){
alert($(this).index())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="choices"></div>
Using native javascript, you can just create a function that will alert the index of the array value corresponding the li element value/id
First you attach the function on the choices
document.getElementById('Name2').setAttribute('onclick','checkIndex(this)');
then loop through the array and hunt for the matching array value
function checkIndex(item){
for(i=0;i<names.length;i++){
if(names[i] == item.innerHTML){ //or item.id
alert(names.indexOf(names[i]));
}
}
}
I would handle it in a declarative way, using html data-attributes, handled by jquery. see here
Here's an example.
var names = ["jack", "mary", "lou", "andrew"];
var text = "<ul>";
for (var i = 0; i < names.length; i++) {
text += "<li data-id='" + i + "'>" + names[i] + "</li>";
}
text += "</ul>";
document.getElementById("choices").innerHTML = text;
$("li").click(function(e){
alert($(this).data("id"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
My Choice
<div id="choices"></div>
</body>
</html>
Of course you can change data-id with whatever you want, or either add other attributes (data-page ? data-txt ? ) and handle all this in a proper way.
Also, dynamically assign ids to your list is a possibility, but I prefer this because I find it more flexible.
I have to add an id to an element. An engine generates the HTML... I have no access to it. It generates random IDs as such:
<input id="5352Adkdie4929888a">
I want to grab the first instance of "<input id=" and replace the ID it has with
the ID it has + DatePicker.
Example:
<input id="5352Adkdie4929888a DatePicker">
How would I go about doing this?
My code so far:
function addID(){
var html= document.documentElement.innerHTML;
var start= '<input id="';
var end= '"'
var htmlIWant=html.substring(html.indexOf(start) + start.length), html.indexOf(end)-1 + 'DatePicker';
}
Am I on the right track? How do I actually replace the HTML? Thanks!
This is a pure javascript solution as per your requirements.
Assuming that your page will have many input tags and some of them will be without ID attribute below is a solution you can try.
var elements = document.getElementsByTagName("input");
for (var i = 0; i < elements.length; i++)
{
if (elements[i].type == "text" && elements[i].hasAttribute("id"))
{
var id = elements[i].getAttribute("id");
elements[i].setAttribute("id", id + "10");
break;
}
}
Grab the first input inside the element using
$('input:first-child').attr('id','whateverIdName');
If you have to catch first input box that has id attribute, you should do :
$("input[id]")[0]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have an indeterminate number of span and input tags with random IDs.
The user has the ability to change the HTML inside of <span> but not <input>.
It looks like this:
<span id="0">235</span>
<input id="5239aac3" value=235>
<span id="1">12</span>
<input id="123abc2" value=12>
<span id="2">235</span>
<input id="5res345" value=235>
I have put all the IDs of <input> into an array called arrayOfIDs and through JavaScript given all matching <span> tags and Id of the index.
for (var i = 0, l = arrayOfIDs.length; i < l; ++i) {
$('#' + i).on("change", function(){
var txt = $(this).find().text();
var $idval = $(arrayOfIDs[i]);
$idval.val(txt)
}).trigger("change");
}
What I need help with in the code above is how to monitor the change in the innerHTML of all spans and update the corresponding input.
I think that you need to change your first selector from $('#i') to $('#' + i)
otherwise you're selecting the element with the literal id of 'i' , which doesn't exist
Also, is the function firing at all? If so, what output do you get?
Finally, I think that you'll want to change var $idval = $(arrayOfIDs[i]); to var $idval = $('#' + arrayOfIDs[i]);
I have 4 <div> tag and <a> tag for each <div> tags.
In each and every div tag i have inserted 2 span tag and a a tag.
When the a tag is clicked i need to get the product name and the price of that div
Here is the demo http://jsfiddle.net/8VCWU/
I get the below warning message when i use the codes in the answer ...
Try this:
$(".get").click(function(e) {
e.preventDefault();
var $parent = $(this).closest(".item");
var itemName = $(".postname", $parent).text();
var itemPrice = $(".price", $parent).text();
alert(itemName + " / " + itemPrice);
});
Example fiddle
Note that you had a lot of repeated id attributes which is invalid code and will cause you problems. I've converted the #item elements and their children to use classes instead.
jQuery
$(".get").click(function(event){
event.preventDefault(); /*To Prevent the anchors to take the browser to a new URL */
var item = $(this).parent().find('#postname').text();
var price = $(this).parent().find('#price').text();
var result = item + " " + price;
alert(result)
});
DEMO
A Quick Note about id:
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
A unique identifier so that you can identify the element with. You can use this as a parameter to getElementById() and other DOM functions and to reference the element in style sheets.
solution is below
use the blow code and try it
<a data-role="link" href="javascript:linkHandler('<%= obj.productname %>', '<%= obj.price %>')" class="get" >Add <a>
function linkHandler(name, price)
{
alert(name);
alert(price);
var name = name;
var price = price;
var cartItem = new item(name, parseFloat(price));
// check duplicate
var match = ko.utils.arrayFirst(viewModel.cartItems(), function(item){ return item.name == name; });
if(match){
match.qty(match.qty() + 1);
} else {
viewModel.cartItems.push(cartItem);
var rowCount = document.getElementById("cartcontent1").getElementsByTagName("TR").length;
document.getElementById("Totala").innerHTML = rowCount;
}
}
with jQuery
$('a.get').on('click',function(){
var parent = $(this).parent();
var name = $(parent+' #postname').text();
var price = $(parent+' #price').text();
});
Or again:
$('a').click(function(e){
e.preventDefault();
var $price = $(this).siblings('#price').text();
var $postname = $(this).siblings('#postname').text();
alert($price);
alert($postname);
});
Try
function getPrice(currentClickObject)
{
var priceSpan = $(currentClickObject).parent("div:first").children("#price");
alert($(priceSpan).html());
}
and add to your a tag:
...
I'd suggest to use classed instead of id if you have more than one in your code.
The function you're looking for is siblings() http://api.jquery.com/siblings/
Here's your updated fiddle:
http://jsfiddle.net/8VCWU/14/
Hi I cleaned up the HTML as mentioned using the same Id more than once is a problem.
Using jQuery and the markup I provided the solution is trivial.
Make a note of the CSS on the below fiddle
http://jsfiddle.net/8VCWU/27/
$(document).ready(function(){
$("#itmLst a.get").click(function(){
var $lstItm = $(this).parents("li:first");
var pName = $lstItm.find("span.postname").html();
var price = $lstItm.find("span.price").html();
alert("Product Name: " + pName + " ; Price: " + price);
});
});
I have made some changes in your html tags and replace all repeated Ids with class, because you have repeated many ids in your html and it causes trouble so it is wrong structure. In HTML, you have to give unique id to each and every tag. it will not be conflicted with any other tag.
Here i have done complete bins demo. i have also specified all alternative ways to find tag content using proper jQuery selector. the demo link is as below:
Demo: http://codebins.com/bin/4ldqp8v
jQuery
$(function() {
$("a.get").click(function() {
var itemName = $(this).parent().find(".postname").text().trim();
var itemPrice = $(this).parent().find(".price").text().trim();
//OR another Alternate
// var itemName=$(this).parents(".item").find(".postname").text().trim();
// var itemPrice=$(this).parents(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).closest(".item").find(".postname").text().trim();
// var itemPrice=$(this).closest(".item").find(".price").text().trim();
//OR another Alternate
//var itemName=$(this).siblings(".postname").text().trim();
//var itemPrice=$(this).siblings(".price").text().trim();
alert(itemName + " / " + itemPrice);
});
});
Demo: http://codebins.com/bin/4ldqp8v
You can check above all alternatives by un-commenting one by one. all are working fine.