Get index-name dynamically - javascript

So, I have an UL which is empty. By clicking on a button, list-items (li) will be added to the ul. All these items do have a header (h1). The header of each item, has to get it's index from the list. So the second li needs to have a header with the number 2, and the third with the number 3.
I've searched the internet for a while for proper solutions, but wasn't able to find one. Now I have created a small piece of code which, in my opinion, should work. But it doesn't. Below is the JavaScript (jQuery) code which adds the items to the list, but also sets it's header.
/*Give all list items a name*/
function AddName() {
var list = $("#jrn_form_input_list");
for (var i = 0; i < 5; i++) {
var index = $("li").index(list[i]);
var header = "Journey leg: " + index;
$(list[i]).find("h1").text(header);
}
};
/*Add journy leg*/
$("#jrn_add_leg_btn").click(function() {
var html = '';
html += '<li>';
html += '<div class="jrn_field">';
html += '<h1 class="jrn_field_header">"TEST_LEG_NAME"</h1>';
html += '<label for="jrn_location"><b>Traveling to</b></label>';
html += '<input type="text" name="jrn_location">';
html += '</div>';
html += '</li>';
$("#jrn_form_input_list").append(html);
AddName();
});
So the function AddName() doesn't work. Is there anyone who knows how to do this properly in JavaScript/jQuery?

In this example all 5 list items are added at once.
$( "#jrn_add_leg_btn" ).click(function()
{
for (var i = 0; i < 5; i++)
{
var j = i + 1;
var html = '';
html += '<li>';
html += '<div class="jrn_field">';
html += '<h1 class="jrn_field_header">Journey leg:'+ j +'</h1>';
html += '<label for="jrn_location"><b>Traveling to</b></label>';
html += '<input type="text" name="jrn_location">';
html += '</div>';
html += '</li>';
$("#jrn_form_input_list").append(html);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id = "jrn_add_leg_btn" >click</button>
<ul id='jrn_form_input_list'></ul>

Related

javascript scripts not working in electron

I am trying to work on electron and made a simple dashboard GUI. i am a beginner in node js and electron.
Problem:
in my main gui.html: i have a table is being loaded, and from that table i need to select the rows from checklist for which i have made a js script:
script in read_checklist.js, this is taking the input checkbox element and selecting the whole row, which will later be shown after some processing in the textarea.
var checkboxes = document.getElementsByTagName("input");
var select_all = document.getElementById("allcb");
var warn_code = Array();
var family_array = Array();
var fail_drive_array = Array();
var waiverMap = {};
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var Warn_Code = currentRow.getElementsByTagName("td")[0];
var Family = currentRow.getElementsByTagName("td")[1];
var failing_drive = currentRow.getElementsByTagName("td")[3];
warn_code.push(Warn_Code.textContent);
family_array.push(Family.textContent);
fail_drive_array.push(failing_drive.textContent);
console.log('server started!' + currentRow );
alert(currentRow.textContent);
};
}
I am trying to import this in my gui.html like this:
This is where the table is getting displayed (code for this is below and it is stored in the renderer.js)
<!--This is for the table-->
<div id="data_lib" class="table-responsive">
</div>
<script type="text/javascript" src="./read_checklist.js"></script>
<!--This is for the table-->
My table is coming from another file, renderer.js
$(document).ready(function(){
var data;
$.ajax({
type: "GET",
url: "/Users/mrimat01/Desktop/CODE/electron_QAB_GUI_main/GUI/data.csv",
dataType: "text",
success: function(response)
{
data = $.csv.toArrays(response);
generateHtmlTable(data);
}
});
function generateHtmlTable(data) {
var html = "<table id='big_tables' class='table table-striped table-bordered' method='GET'>";
if(typeof(data[0]) === 'undefined') {
return null;
} else {
$.each(data, function( index, row ) {
//bind header
if(index == 0) {
html += '<thead>';
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<th>';
html += colData;
html += '</th>';
});
html += '<th>';
html += "<input type='checkbox' id='allcb' name='allcb'/>Select";
html += '</th>';
html += '</tr>';
html += '</thead>';
html += '<tbody>';
} else {
html += '<tr>';
$.each(row, function( index, colData ) {
html += '<td>';
html += colData;
html += '</td>';
});
html += '<td>';
html += "<input id='name' type='checkbox' name='name' value='name' /> ";
html += '</td>';
html += '</tr>';
}
});
html += '</tbody>';
html += '</table>';
$('#data_lib').append(html);
}
}
});
I can see the table getting generated but read_checklist.js desn't work.
If i try to do the same thing in console, it works perfectly.
i have gone through many SO answers but couldn't seem to make this work.
Things i have tried:
making node_integration: true
using
module = undefined;}</script>
<script>if (window.module) module = window.module;</script>
adding the script directly below root <div>

How can I make this click counter work properly?

I'm making a Marvel API project. I added a Like button so it could count the likes, but everytime I click any like button the only counter adding numbers is the first one. Can anyone tell me how I do this properly?
The problem is because the ID is being made by a for, so how could I solve this?
This is my JS code (on the js file of my project) :
success: function(data)
{
footer.innerHTML = data.attributionHTML;
var string = "";
string += "<div class='row'>";
for (var i = 0; i < data.data.results.length; i++)
{
var element = data.data.results[i];
string += '<div class="col-md-3" align="center">';
string += "<img src='" + element.thumbnail.path + "/portrait_fantastic." + element.thumbnail.extension + "'/>";
string += '<button class="btn btn-success" onClick="testo()"><i class="fas fa-thumbs-up"></i> | <a id="likes">0</a></button>';
string += "<h3>" + element.title + "</h3>";
string += "</div>";
if ((i + 1) % 4 == 0)
{
string += "</div>";
string += "<div class='row'>";
}
}
marvelContainer.innerHTML = string;
}
And this is my onclick function (It is on my html file because it wont work on my js file)
<script>
var likes=0;
function testo()
{
likes += 1;
document.getElementById("likes").innerHTML = likes;
}
</script>
That is because all your buttons are being generated with the same id="likes" and then you are changing the HTML with document.getElementById("likes").innerHTML = likes;
for your code to work properly you will need to use a different approach, maybe adding a data-* attribute to your buttons and then change the likes by the data-* atribute using .getAttribute('data-id-something').innerHTML instead of document.getElementById("likes").innerHTML.
Or even better in this case you can give the buttons a class name and handle it with: document.getElementsByClassName("like-btn")
You can check the last option in this example:
var init = function(data){
var string ="";
string += "<div class='row'>";
for(var i = 0; i<4; i++)
{
// var element = data.data.results[i];
string += '<div class="col-md-3" align="center">';
string += "<img src='/portrait_fantastic.jgeg'/>";
string += '<button class="btn btn-success" onClick="testo('+i+')"><i class="fas fa-thumbs-up"></i> | <span class="like-btn">0</span></button>';
string += "<h3>Element title</h3>";
string += "</div>";
if((i+1) % 4 ==0)
{
string += "</div>";
string += "<div class='row'>";
}
}
document.getElementById("marvelContainer").innerHTML = string;
}
init();
<script>
var likes=0;
function testo(id) {
var btn = document.getElementsByClassName("like-btn");
likes = parseFloat(btn[id].innerHTML);
likes += 1;
btn[id].innerHTML = likes;
}
</script>
<div id="marvelContainer"></div>
I hope it will help you...
Gave the buttons a class, as that is what is going to be clicked.
Changed the link element to a span. Having a link in a button doesn't make much sense, as you can't "not" click the button and click the link.
Removed the inline onclick for the link and added an event listener logically on all the buttons.
The click logic finds the nested span in the button
It takes the data attribute on the span, turns it into an integer, and increments it
It then updates the data attribute value for the next click
And finally it updates the visible text that the user can see
EDIT
Changed it to bind the click event listener on the span as well and stop propagation on the click event. Actually clicking the span was causing the click event to register for the span, and not the button.
// fake out some data for the element generation
var data = { data: {
results: [
{ thumbnail: { path: '/path1', extension: 'jpg', title: 'Element1' } }
,{ thumbnail: { path: '/path2', extension: 'png', title: 'Element2' } }
,{ thumbnail: { path: '/path3', extension: 'gif', title: 'Element3' } }
]
} };
// fake out the container the elements are built to
var marvelContainer = document.querySelector('#container');
var string = "<div class='row'>";
for (var i = 0; i < data.data.results.length; i++) {
var element = data.data.results[i];
string += '<div class="col-md-3" align="center">';
string += "<img src='" + element.thumbnail.path + "/portrait_fantastic." + element.thumbnail.extension + "'/>";
// put a class on the button
// also removed the id and inline onclick
// change the id on the link to a class
// also initialized the data-likes on the link to zero
string += '<button class="btn btn-success likes-button"><i class="fas fa-thumbs-up"></i> | <span class="likes" data-likes="0">0</span></button>';
string += "<h3>" + element.title + "</h3>";
string += "</div>";
if ((i + 1) % 4 == 0) {
string += "</div>";
string += "<div class='row'>";
}
}
marvelContainer.innerHTML = string;
document.querySelectorAll('.likes-button, .likes').forEach(function(likeButton){
likeButton.addEventListener('click', incrementLikes);
});
function incrementLikes (e) {
e.stopPropagation();
// find the inner likes element of the button
var likes = e.target.querySelector('.likes') || e.target;
// increment the likes
var incrementedLikes = parseInt(likes.dataset.likes) + 1;
// update the data attribute for next click, and update the text
likes.dataset.likes = incrementedLikes.toString();
likes.innerText = incrementedLikes;
}
<div id="container">
</div>

print array of object in javascript and print in html tags

i am using storelocater.js for multiple location in google map and show the information according to the location with image. i can show only one image but i want to show multiple images inside the information panel. link this
Here is my code
var panelDiv = document.getElementById('panel');
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">The nearest outlet:</li>';
var Store = storeLocator.Store;
Store.prototype.generateFieldsHTML_ = function(fields) {
var html = '';
html += '<div class="store-data">';
if(this.props_['title']){
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
}
html += '</div>';
return html;
}
var data = new storeLocator.StaticDataFeed;
data.setStores([
new storeLocator.Store('store02', new google.maps.LatLng(27.67663,85.31093), null, {images: ["img/thapathalil.jpg","img/thapathalil.jpg","img/thapathalil.jpg"]})
]);
and it shows:
Uncaught SyntaxError: Unexpected token for...
how can i solve this?? how can i fetch location inside of "images"
THANKS in advance
Actually you got Uncaught SyntaxError: Unexpected token for... because you used the for..loop in the string concatenation statement, directly after the + sign.
Change this code :
html += '<div class="title"><div class="img-list clearfix">' +
for (var i = 0; i <= this.props_[images].length; i++) {
console.log(this.props_[images[i]]);
// <img src=' + this.props_['images'] + '>
}
+ '</div></div>'
To the following:
html += '<div class="title"><div class="img-list clearfix">';
for (var i = 0; i <= this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
html += '<img src=' + this.props_['images'][i] + '>';
}
html += '</div></div>'
Note:
You should separate the concatenation of strings to the html
variable and the for loop logic, using html += instead of just using concatenation with + sign on multiple lines.
Make sure to wrap the properties names between two '' while accessing your objects, like in this.props_[images] where it should be this.props_['images'] and in this.props_[images[i]] where it should be this.props_['images'][i].
And the first 2 lines of your html variable decalaration and the concatenation, var html = ''; html += '<div class="store-data">'; can be shortened to just var html = '<div class="store-data">';.
I think there is a typo. Change this:
console.log(this.props_[images[i]])
to
console.log(this.props_['images'][i])
And you should use
i < this.props_['images'].length
So try this:
for (var i = 0; i < this.props_['images'].length; i++) {
console.log(this.props_['images'][i]);
}

JSON date not showing in HTML

I have a problem with JSON data: I want make news feed via JSON URL, but the information not showing in HTML.
$(function() {
var entries = [];
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '<div class="panel-body"><h3 class="lead">${title}</h3>';
html += '<time datetime="${published}">';
html += '<span class="glyphicon glyphicon-time"></span> ';
html += '<span class="month">${monthName}</span> ';
html += '<span class="day">${day}</span>, ';
html += '<span class="year">${year}</span></time></div>';
$('#ticker').html
},
<div id="ticker"></div>
You could do something like this:
<script>
$(document).ready(function() {
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.news.length; i++){
html += '<div>';
html += data.news[i].title
html += '<br>';
html += data.news[i].published
html += '</div>';
}
// append all the html variable to the ticker div.
$("#ticker").append(html);
});
});
</script>
This will loop through the news node, and get the title and the published date and then append them to the page (an element with the id of ticker.

How to give ID to row dynamically?

I am generated a row dynamically in this fiddle.I want to give ID to that row .And Display that on header can we give this.I want to give ID like this 1,2,3...
But there is a problem Is that That rows are nested So can we give ID to inner row also .IF there is an row inside first his ID 1_1, 1_2....If some element is inside 1_1.then it ID id 1_1_1....So on
Can we do this ?
function buildNav(nodes) {
var result = '<div data-role="collapsible-set" id="stuff">';
var i = 0, len = nodes.length;
for(; i < len; i++) {
result += "<div data-role='collapsible' data-content-theme='c'><h3>test</h3>"+content;
if(nodes[i].testCaseList) {
result += buildNav(nodes[i].testCaseList) + "</div>";
}
result += "</div>";
}
return result + "</div>";
}
$(function(){
$('#test ').html(buildNav(testData.testCaseList)).trigger('create');
});
Try passing the value of the current level to your function and prepend it to the id.
function buildNav(nodes, level) {
var result = '<div data-role="collapsible-set" id="' + level + '">';
var i = 0, len = nodes.length;
for(; i < len; i++) {
var id = level + '_' + i;
result += "<div data-role='collapsible' data-content-theme='c'><h3>test</h3>"+content;
if(nodes[i].testCaseList) {
result += buildNav(nodes[i].testCaseList, id) + "</div>";
}
result += "</div>";
}
return result + "</div>";
}
$(function(){
$('#test ').html(buildNav(testData.testCaseList, 0)).trigger('create');
});

Categories