How to add new <li> element each click? - javascript

First attempt at any sort of Javascript so be gentle aha
Have managed to have the page add the new list item to the inner html of an unordered list, but each time after that it just replaces the initial.
I feel like I'm missing something really basic here?
Any advice would be greatly appreciated.
<script>
function addItem() {
var item = document.getElementById("task-field").value;
document.getElementById("task-list").innerHTML = "<li> " + item + " </li>";
}
</script>

Use
document.getElementById("task-list").innerHTML += "<li> " + item + " </li>";
instead of
document.getElementById("task-list").innerHTML = "<li> " + item + " </li>";
The += operator will use the current value of innerHTML and append your new content in this case. This as suggested by #Hassam Imam.
Another way of doing it is using appendChild() creating the new <li> item through JS. Like this:
function addItem() {
let item = document.getElementById("task-field").value;
let parent = document.getElementById("task-list");
// Create new node.
let li_item = document.createElement("li");
li_item.innerHTML = item;
// Append child.
parent.appendChild(li_item);
}
But this last method is probably too lengthy. The += solution seems good. Just another way of doing it.

<script>
function addItem(item) {
const li = document.createElement('li');
li.innerHTML = `${item}`;
li.id = 'task-field';
document.getElementById('task-list').appendChild(li);
}
</script>

Related

Why doesn't my innerHTML method work to list things in my contact form?

I am making a program, and I'm wondering why all I see on my html page is the form, but only a single . where the bulleted list for an unordered list should be. I input the user input in the fields, but it doesn't show me the data in the fields, like it's supposed to, when I click submit. Here's the code.
function getFormElements() {
var gather_form_elements = new Array(
$("#first_name").val(),
$("#last_name").val(),
$("email").val(),
$("#phone_number").val()
);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.getElementById("contact_info").innerHTML = "<li>" + gather_form_elements[i] + "</li>";
}
}
Because you are overiding it on every iteration. Try to accumulate the html before using innerHTML like this:
var html = "";
for(var i = 0; i < gather_form_elements.length; i++) {
html += "<li>" + gather_form_elements[i] + "</li>";
// ^^ the += is crucial. If you don't use it, it will just replace the content of html (the innerHTML in your code), we need to use += to append to html instead of overriding it.
}
document.getElementById("contact_info").innerHTML = html;
You can acheive the same result using only one line of code:
document.getElementById("contact_info").innerHTML =
'<li>' + gather_form_elements.join('</li><li>') + '</li>';

How to fire up a function when clicking on a link and then pass a class from that link

I have this HTML:
<li class="sshjd839djjd blahclass"><a onclick="doSomething()">Blah Blah</a></li>
So when I click my link doSomething() is triggered and I want to grab sshjd839djjd. I have many links with different keys like this one which I need to grab correct data.
I don't know much about Javascript and jQuery but I need it to make admin panel which I would use to manage my data in Firebase, just to explain what I'm doing.
I tried to avoid onClick and use .click but that didn't work.
Can somebody help me a bit please?
So what should go in:
function doSomething() {
// grab class which is actually a child key from Firebase which I already implemented
// do Firebase magic, I will know this once I get that key
}
Keys/classes are added like this:
var resultVetRef = new Firebase("https://myappname.firebaseio.com/data/users");
resultVetRef.on("child_added", function(snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
$("#results").append($("<li class=\"" + key + " blahclass\">" + "<a onClick=\"grabVet()\">" + name + ", " + city + "</a></li>"));
});
add the key as data to the li
var resultVetRef = new Firebase("https://myappname.firebaseio.com/data/users");
resultVetRef.on("child_added", function(snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
$("#results").append($("<li class=\"" + key + " blahclass\" data-key=\""+ key +"\">" + "<a onClick=\"grabVet()\">" + name + ", " + city + "</a></li>"));
});
Then get it like:
<li class="sepcialKey blahclass" data-key="sepcialKey"><a>Blah Blah</a></li>
$('a').click(function(){
alert($(this).closest('li').data('key'));
});
Here is the Demo: https://jsfiddle.net/ffyLgg3s/
Specifically for your example
<li class="sshjd839djjd blahclass"><a>Blah Blah</a></li>
$('a').click(function(){
alert( $(this).closest('li')[0].classList.item(0) );
});
using classList and item method.
or if you want to use your own doSomething
<li class="sshjd839djjd blahclass"><a onclick="doSomething(this)">Blah Blah</a></li>
function doSomething(thisObj)
{
alert($(thisObj).closest("li")[0].classList.item(0));
}
ClassList method gives you an array with all classes of the element.
In your case it will return array ["specialKey", "blahclass"] for your <li> element.
function doSomething() {
// get the firs element of classList array and asign it to a variable
var specialKey = this.parentElement.classList[0]; // "this" keyword is the reference to clicked element, "parentElement" give you "li" element reference
// do Firebase magic, I will know this once I get that key
}
Or modify your append code:
var resultVetRef = new Firebase("https://myappname.firebaseio.com/data/users");
resultVetRef.on("child_added", function (snapshot) {
var key = snapshot.key();
var data = snapshot.val();
var name = data.name;
var city = data.city;
// create li element
var li = $("<li class=\"blahclass\"></li>");
// create a element
var a = $("<a>" + name + ", " + city + "</a>");
a.on("click", function () {
// when a clicked execute "doSomething" passing key as parameter
doSomething(key);
})
// append a to li
li.append(a);
//append li to #results
$("#results").append(li);
});

How to style dynamically generated Select2 dropdowns after the page has loaded?

I am using Select2 for dropdown styling from http://ivaynberg.github.io/select2/ .
I have several dropdowns on the page which are styled correctly using the following:
<script>
$(document).ready(function() {
$("#dropdown1").select2();
$("#dropdown2").select2();
});
</script>
Now, I have another option on the page where it allows the user to add as many dropdowns as they want for additional options, the following way:
<img src="images/add.png" title="Add Row" border="0" onclick="addRowToCountryPrice('',''); return false;">
<input type="hidden" name="TotalLinesCountry" id="TotalLinesCountry">
<script>
var arr = new Array();
var ind=0;
function showCountryDrop(name1,sel, param){
var dval="";
dval = "<select name=\"" + name1 + "\" id=\"" + name1 + "\" class=\"countriesclass\">";
dval += "<option value=\"\">Select Country</option>\r\n";
selVal = (sel==0001) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0001\" " + selVal + ">United Kingdom</option>";
selVal = (sel==0002) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0002\" " + selVal + ">United States</option>";
selVal = (sel==0003) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0003\" " + selVal + ">Albania</option>";
selVal = (sel==0004) ? "selected=\"selected\"" : " " ;
dval += "<option value=\"0004\" " + selVal + ">Algeria</option>";
dval +="</select>";
return dval;
}
function addRowToCountryPrice(country,price) {
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
var cellVal = "";
var cellLeft;
var i=0;
arr[ind] = (iteration+1);
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = showCountryDrop("countryDrop_" + ind,country);
cellLeft = row.insertCell(i++);
var price = (price!=0) ? price : "0.00";
cellLeft.innerHTML = "<input type=\"text\" name=\"countryPrice_" + ind + "\" id=\"countryPrice_" + iteration + "\" value = \"" + price + "\" size=\"8\">";
cellLeft = row.insertCell(i++);
cellLeft.innerHTML = "<img src=\"images/delete.png\" title=\"Delete Row\" border=\"0\" onclick=\" removeRowFromTable(" + ind + "); return false;\">";
document.getElementById("TotalLinesCountry").value = (parseInt(ind)+1);
ind++;
}
function removeRowFromTable(src)
{
var tbl = document.getElementById("tblCountryCurrency");
var lastRow = tbl.rows.length;
if (arr[src]!="") tbl.deleteRow((arr[src]-1));
arr[src]="";
var counter = 1;
for( i=0; i<arr.length; i++) {
if (arr[i]!="") {
arr[i]= counter;
counter++;
}
}
return false;
}
</script>
While it generates the dropdowns correctly, they are not styled through the class "countriesclass", even if I do a:
$(".countriesclass").select2();
I also tried
dval +="</select>";
$(".countriesclass").select2();
return dval;
And that seems to be PARTIALLY working in a strange way. When I create the first dropdown, it doesn't get styled. When I create another second dropdown, then the first one gets styled but the second one doesn't. It then doesn't let me create further ones and shows an error.
Any ideas how I could get this working?
UPDATE: jsFiddle http://jsfiddle.net/y6af098z/2/
Your call to $('.countriesclass') goes off when the document is ready. But the select has not been added to the document yet, then. So no elements are found.
You should look up the added select after the user has clicked on the plus and you've added the select to the dom.
$('#plus').on('click', function () {
$tr = addRowToCountryPrice('Algeria', 0);
$('.countriesclass', $tr).select2();
});
The second argument $tr tells jquery only to look in the recently added table row, so that you only select the newly added select which is a child of the newly added tr. Not the selects in the other rows.
Like #dreamweiver already noted, you should make better use of jquery when creating the dom elements. That's what jquery is good at. I've updated the jsfiddle to show how you can create the select and table row the jquery way.
DEMO
Instead of using getelementbyId use getelementbyClass and give each dropdown a class, you can only have one getelementbyid.
Hope this helps. if you want i could send you the code for what you require?
The select2 when called was not able to find the dropdown list boxes,because they were added dynamically and hence the those were not visible for the jQuery class selector $(".countriesclass").select2();.
This type of behaviour can be overcome by referencing the selector from the document element, rather than referring the element directly like above. so the new selector should be like this
$(document).find("select.countriesclass").select2();
Also I have done few tunings in your code.
Live demo:
http://jsfiddle.net/dreamweiver/y6af098z/8/
Note: one more thing, when using jQuery lib make sure you make the most of it, don't use raw JS code instead use the jQuery equivalent syntax for the same, which would be simple and easy to use.

Add items to a list using jquery

I had a quick question that I can't figure out. I am working with this code:
http://jsfiddle.net/spadez/ZTuDJ/32/
// If JS enabled, disable main input
$("#responsibilities").prop('disabled', true);
// $("#responsibilities").addClass("hidden");
// If JS enabled then add fields
$("#resp").append('<input placeholder="Add responsibility" id="resp_input" ></input><input type="button" value="Add" id="add"> ');
// Add items to input field
var eachline='';
$("#add").click(function(){
var lines = $('#resp_input').val().split('\n');
var lines2 = $('#responsibilities').val().split('\n');
if(lines2.length>10)return false;
for(var i = 0;i < lines.length;i++){
if(lines[i]!='' && i+lines2.length<11){
eachline += lines[i] + '\n';
}
}
$('#responsibilities').text($("<div>" + eachline + "</div>").text() );
$('#resp_input').val('');
});
The idea is that you type something in the responsibility field and it gets inserted into a text area. What I also want to do is that when an item is inserted into the text area it also prints it out above it in a list format like this:
<li>inserted item 1</li> <li>inserted item 2</li>
I'm really new to javascript but this was my best stab at it based on information found online:
$("#resp").append('<li> +eachline </li> ')
$('#responsibilities').text($("<div>" + eachline + "</div>").text() ).before("<li>"+lines+"</li>");
Demo ---> http://jsfiddle.net/ZTuDJ/34/
http://jsfiddle.net/pjdicke/ZTuDJ/35/
You will need to create a <ul> then add this below
$('#responsibilities').text( $("<div>" + eachline + "</div>").text() );
// add this line after above
$('<li>' + lines + '</li>').appendTo('#list');
I already fixed that for you in your previous question.
Jquery adding items to a list without reloading page
http://jsfiddle.net/blackjim/VrGau/15/
var $responsibilityInput = $('#responsibilityInput'),
$responsibilityList = $('#responsibilityList'),
$inputButton = $('#addResp'),
rCounter = 0;
var addResponsibility = function () {
if(rCounter < 10){
var newVal = $responsibilityList.val()+$responsibilityInput.val();
if(newVal.trim()!==''){
var newLi = $('<li>');
$('ul#respList').append(newLi.text(newVal));
$responsibilityList.val('');
rCounter+=1;
}
}
}
$inputButton.click(addResponsibility);

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

Categories

Resources