Javascript onClick doesn't work with button [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
Pretty Straight forward. My button is not creating the input I need after the click event. I need the fields populated where the class "household" is. I cannot edit HTML only Javascript. Any ideas?
HTML:
<ol class="household"></ol>
<div>
<button class="add">add</button>
</div>
JS:
document.getElementsByClassName("add").onclick = function() {
createinput()
};
count = 0;
function createinput() {
field_area = document.getElementsByClassName('household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}

document.getElementsByClassName gives you object of all child elements which have all of the given class names . You will have to attach the event on each element by iterating over the array or by using index.
Here you can use document.querySelector for your example which returns the first Element matching with the selector.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
document.querySelector(".add").onclick = function() {
createinput()
};
count = 0;
function createinput() {
field_area = document.querySelector('.household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
<ol class="household"></ol>
<div>
<button class="add">add</button>
</div>

It should be document.getElementsByClassName("add")[0].onclick
As Document.getElementsByClassName():
Returns an array-like object of all child elements which have all of
the given class names. When called on the document object, the
complete document is searched, including the root node. You may also
call getElementsByClassName() on any element; it will return only
elements which are descendants of the specified root element with the
given class names.
document.getElementsByClassName("add")[0].onclick = function() {
createinput()
};
count = 0;
function createinput() {
field_area = document.getElementsByClassName('household')
var li = document.createElement("li");
var input = document.createElement("input");
input.id = 'field' + count;
input.name = 'field' + count;
input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
li.appendChild(input);
field_area.appendChild(li);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function() {
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
li.appendChild(removalLink);
count++
}
<div>
<button class="add">add</button>
</div>

x.getElementsByClassName()
getElementByClassName returns a collection.
x.onclick
onclick is meant for single elements and cannot be directly applied to a collection. Thats why your code is not working.
If you wanted to use a collection then a loop would work as suggested by one of the other answers.
I would have a think about the approach you want to take see this answer on .getElementsByClassName().

Related

Hot to reverse the order of a html list from javascript? [duplicate]

This question already has answers here:
How to set DOM element as first child?
(9 answers)
Closed 1 year ago.
I currently have this code in JavaScript
function addTask() {
// Declaring Variables
var item = document.getElementById("text_field").value;
var text = document.createTextNode(item);
var list_element = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
list_element.appendChild(checkbox);
list_element.appendChild(text);
document.getElementById("todo-list").appendChild(list_element);
}
This works fine to create a list, but the list items are added at the bottom of the html list. How do I add the new user input to the top of the html list?
I think you can place them in an array then reverse them.
this will be an example below
function addTask() {
// Declaring Variables
var item = document.getElementById("text_field").value;
var text = document.createTextNode(item);
var list_element = document.createElement("li");
var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
list_element.appendChild(checkbox);
list_element.appendChild(text);
document.getElementById("todo-list").appendChild(list_element);
}
function reverseElement(){
var reversedElement = Array.from(document.getElementById("todo-list")).reverse()
}
Use prepend instead of append.
Here is the working example:
function addTask() {
// Declaring Variables
var date = new Date;
var item = document.getElementById("text_field").value;
var list_element = document.getElementById('tasks');
var li = document.createElement("li");
li.innerText = item + '\t|\t' + date.toISOString();
list_element.prepend(li);
}
<input id="text_field" />
<button onclick="addTask()">Add</button>
<div>
<h1>Tasks</h1>
<ol id="tasks"></ol>
</div>

Search function filter li's in pure Js

I'm trying to make an input that filters a <ul> based on the value in pure JavaScript. It should filter dynamically with the onkeyup by getting the li's and comparing their inner element name with the filter text.
Here is my function:
var searchFunction = function searchFeature (searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
stringValue.onkeyup = function () {
//toUpperCase to make it case insensitive
var filter = stringValue.toUpperCase();
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = eachStudent[i].getElementsByClassName('student-details')[1].innerHTML;
//display all the results where indexOf() returns 0
if (name.toUpperCase().indexOf(filter) == 0)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}}
My HTML for the search bar:
<div class="student-search">
<input id="inputSearch" placeholder="Type name here.." type="text"> <button>Search</button></div>
My HTML for one of the li's:
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="#">
<h3>John Doe</h3>
<span class="email">John.Doe#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 01/01/14</span>
</div>
</li>
I would like to filter all the elements (name, email, joined date) based on the value of the input.
Unfortunately, I don't get any errors and it's simply not working.
The function is correctly invoked because the console.log prints...
Here goes the codepen: http://codepen.io/Delano83/pen/qaxxjA?editors=1010
Any help or comments on my code is very appreciated.
There were several issues:
stringValue.onkeyup - stringValue is the value. You can't onkeyup it.
var eachStudent = document.querySelector(".student-item"); will fetch the first thing with student-item class. You need to use querySelectorAll or just use jquery's $('.find-item').
if (name.toUpperCase().indexOf(filter) == 0) indexOf returns 0 if the filter is found at the beginning of the name. 0 as match if found at index 0. You need to check against -1, which means it was not found at all.
Otherwise it more or less worked, good job.
I also added Jquery for me to fix it faster. If you insist on using pure javascript I am sure you will be able to edit it.
Check it out here: http://codepen.io/anon/pen/WGrrXW?editors=1010. Here is the resulting code:
var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");
//Recreate Search Element in Js
var searchBar = function createBar(searchString) {
var studentSearch = document.createElement("div");
var input = document.createElement("input");
var searchButton = document.createElement("button");
input.type = "text";
var txtNode = document.createTextNode("Search");
if (typeof txtNode == "object") {
searchButton.appendChild(txtNode);
}
studentSearch.setAttribute("class", "student-search");
input.setAttribute("id", "inputSearch");
//append these elements to the page
studentSearch.appendChild(input);
studentSearch.appendChild(searchButton);
input.placeholder = "Type name here..";
return studentSearch;
}
var searchFunction = function searchFeature(searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
inputString.onkeyup = function() {
//toUpperCase to make it case insensitive
var filter = $(this).val().toUpperCase()
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = $(eachStudent[i]).find('h3').text()
console.log(name, filter, name.toUpperCase().indexOf(filter))
//display all the results where indexOf() does not return -1
if (name.toUpperCase().indexOf(filter) != -1)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}
}
function addElements() {
console.log('Add search bar, trying to anyway...')
pageHeader.appendChild(searchBar());
// page.appendChild(paginationFilter());
onLoad();
}
window.onload = addElements;
window.onLoad = searchFunction;

To do list javascript-something is wrong with my code/order

I'm building a small to do list and everything worked fine so far until I included a checkbox. now when I click on the button, nothing happens and neither do I see a checkbox. There must be something wrong with the order of code-does someone know how I need to rearrange the code and WHY?
Html code:
<body>
<h1>To Do List</h1>
<p><input type="text" id="textItem"/><button id="add">Add</button></p>
<ul id="todoList">
</ul>
</body>
Javascript code:
function addItem() {
var entry = document.createElement("li");
var checkBox = document.getElementById("input");
checkBox.type = "checkbox";
var span = document.createElement("span");
span.innerText = entry;
var textItem = document.getElementById("textItem");
entry.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
}
var item = document.getElementById("add");
item.onclick = addItem;
UPDATED - I've spotted 4 issues . Follow Below :
1st : When you create the check box you should be using setAttribute method to specify input type : checkbox.setAttribute("type" , "checkbox")
2nd : Your checkbox variable should be creating an input element : var checkBox = document.createElement("input");
3rd : You should be using innerHtml instead of innerText as you are referencing a list ELEMENT stored in your entry variable : span.innerHtml = entry;
4th: Really minor but you should grab your item and attach an event to the item before your function :
var item = document.getElementById("add");
item.addEventListener("click" , addItem)
Just change your javascript to the following :
var item = document.getElementById("add");
item.addEventListener("click" , addItem)
function addItem() {
var entry = document.createElement("li");
var checkBox = document.createElement("input");
checkBox.setAttribute("type" , "checkbox");
var span = document.createElement("span");
span.innerHtml = entry;
var textItem = document.getElementById("textItem");
entry.innerText = textItem.value;
var location = document.getElementById("todoList");
entry.appendChild(checkBox);
entry.appendChild(span);
location.appendChild(entry);
}
Example Here : http://codepen.io/theConstructor/pen/pyPdgg
Good Luck!

PHP text boxes dynamic ID generating

i would be very thankful if anyone could help me with this
i am trying to use php uploader plugin and upload multiple files.
i want to assign unique ids to the generating text box fields.
but whenever I am using a for loop to assign id , the text boxes won't show up
here is my code
var input = document.createElement('input');
input.value = task.FileName;
input.id = "textBox_";
for(var i = 0; i<0; i++){
input.id = "textBox_'.i.'";
}
document.body.appendChild(input);
}
the help will be appreciated ..
You are not appending the value of i properly. In js concatenation is done using + operator not using .
input.id = "textBox_"+i;
Place
document.body.appendChild(input);
inside the for loop like shown below as it has to generate input each time until loop ends.
for(var i = 0; i<0; i++)
{
input.id = "textBox_"+i;
document.body.appendChild(input);
}
Change input.id = "textBox_'.i.'"; to input.id = "textBox_"+i;
Concatenation in js is cone using + operator
So your code will be:
var input = document.createElement('input');
input.value = task.FileName;
input.id = "textBox_";
for(var i = 0; i<0; i++){//Condition of this loop is wrong in the sence it wont execute even once so fix it as your needs
input.id = "textBox_"+i;
document.body.appendChild(input);
}
}

the best practice for assigning an ID automatically

I have a page that contains a link like this:
new user
When the user clicks the link, I add a new input field to the page. I would like to assign an ID to that input field. I can do this using Javascript:
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.setAttribute('ID',"input"+num);
}
This works; but my question is, is this the standard way, or is there a better way to do this, something that doesn't use num, JS or jQuery?
You don't need an ID on an input element. However you might be needing a name. If so, just use name = "input[]" - then on the server side you will get an array of values.
Since you're using jQuery:
$('<input id="input'+ num +'"/>').appendTo('#yourElement')
Just assign the id to the element:
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.id = "input" + num;
}
Since you tagged your question with jQuery, you can also do this:
function add(){
var input = $('<input id="input' + num++ +'" />')
// do something with the input.
}
Or:
function add(){
var input = $('<input>', {id = "input" + num++});
// do something with the input.
}
Update:
You can't create DOM elements without javascript (jQuery is javascript).
var num=0;
function add(){
num++;
var input = document.createElement('input');
input.id = "input"+num;
}
random ID without num :
function add(){
var input = document.createElement('input');
input.id = 'input'+parseInt(Math.random()*1354243242);
}

Categories