Add items to a list using jquery - javascript

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);

Related

How to add new <li> element each click?

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>

Buttons text not changing in JavaScript?

I'm trying to change the text of a button to that of a value stored in a variable. The button is currently blank and not even using a fixed value like .value = "test"; is working.
HTML:
<div id="addContainer">
<textarea id="listTitleInput" class="textarea" placeholder="Add the title of your list here, then click 'Add List'." rows="10" cols="50"></textarea>
<button id="addListBtn" data-role="button">Add List</button>
</div>
<div id="listDisplayContainer">
</div>
JS:
$(document).ready(function () {
//LISTS
var listTitleInput = document.getElementById("listTitleInput");
var addListBtn = document.getElementById("addListBtn");
var listCount = localStorage.getItem("listCount");
if (listCount === null) {
noteCount = 0;
}
//ADD LISTS
function addList() {
if ($("#listTitleInput").val() == "") {
alert("Please give your list a title, then click 'Add List'.");
} else {
listCount++;
var list = $("#listTitleInput").val();
console.log("List Count: " + listCount);
console.log(list);
var display = document.createElement("button");
document.getElementById("listDisplayContainer").appendChild(display);
display.className = "ui-btn";
display.id = "list" + listCount;
$("#list" + listCount).value = list;
}
}
//Lists
addListBtn.addEventListener("click", addList);
});
Looks like you need to change $("#list" + listCount).value = list; to $("#list" + listCount).text(list);
value is not a property and val() doesn't work for a button.
The problem is that you are confusing native DOM attributes with jQuery ones.
$("#list" + listCount).value = list;
$("#list" + listCount) is a jQuery object so it doesn't use the native javascript properties that you may be used to. (value=)
What you are looking for is:
$("#list" + listCount).html(list);
Or
$("#list" + listCount).text(list);
Since list is a string value, it will be best to use .text

jQueryUi Tabs isn't working when I use dynamically created divs

I'm currently working on a dealer search for my company. I want to add some tabs, so that the cutomers can filter the dealers per state. This means that the divs for the states are created dynamically, because the information comes from a CSV file.
I add the information like this:
function erzeugenTab() {
var $tabsDiv = $("#mapstabs");
var linkList ='';
var divRegion ='';
var linkZahl = 1
for (var i = 0; i < unique.length - 1; i++) {
linkList = linkList + "<li>" + unique[i] + "</li>" ;
divRegion = divRegion + "<div id =\"tabs"+linkZahl+"\">Test123</div>";
linkZahl = linkZahl + 1;
}
linkList = linkList + "</ul>";
$tabsDiv.append(linkList);
$tabsDiv.append(divRegion);
$(function() {
$('#mapstabs').tabs();
});
}
However, no tabs are apearring. You can se it here.
Any idea what I"m missing?
Can you try removing the $ on $tabsDiv turning it into just var tabsDiv?
Also, I do not see an open ul tag
Can you try by removing function()?
$(function() {
$('#mapstabs').tabs();
});
to
$('#mapstabs').tabs();

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

Using innerHTML to add ordered list fails in IE

I'm using the following Javascript code to populate a DIV with an ordered list:
// send script back in split list
var scriptList = script.split("\n");
var finalScript = "<ol>\n";
var count = 0;
while(scriptList.length >= count) {
if((scriptList[count]=="") || (scriptList[count] == undefined)) {
count ++;
continue;
}
finalScript = finalScript + "<li>" + scriptList[count] + "</li>\n";
count ++;
}
finalScript = finalScript + "</ol>";
scriptingDiv.innerHTML = finalScript;
In firefox, if i look in the DOM using Firebug, this correctly translates to the following and correctly displays an ordered list.
<ol>
<li>This is the first item in the list</li>
<li>This is the second item in the list</li>
</ol>
In IE, it displays as if the </li> tags are <br /> tags and ignores all the other tags, like this:
This is the first item in the list
This is the second item in the list
Do I need to dynamically add the ordered list to the DOM for this to work? As opposed to just setting the html code in the div using .innerHTML?
TIA
Do I need to dynamically add the ordered list to the DOM for this to work? As opposed to just setting the html code in the div using .innerHTML?
Yes
var scriptList = script.split("\n");
var count = 0;
var ol = document.createElement("ol");
for(var index=0; index<scriptList.length; index++) {
if(scriptList[index]!="") {
var li = document.createElement("li");
li.innerHTML=scriptList[index];
ol.appendChild(li);
}
}
scriptingDiv.appendChild(ol);
Why not use dom methods instead? IE:
myOL = document.createElement("ol");
myLI = document.createElement("li");
myTxt = document.createTextNode("My Text!");
myLI.appendChild(myTxt);
myOL.appendChild(myLI);
etc

Categories

Resources