for (var i = 0; i < animals.length; i++) {
btn = $("<button>");
btn.attr("class", "btn");
btn.attr("value", animals[i]);
btn.text(celebrities[i]);
console.log(btn.value);
$("#animals").append(btn);
}
Console logging btn.value returns undefined. What am I doing wrong?
Button don't have value attribute, use can use data-value to set attribute for button like this. Also you wrong format btn = $("<button>");
btn = $("button");
btn.attr("class", "btn");
btn.attr("data-value", "Test Value");
btn.text("Text");
console.log(btn.text());
console.log(btn.data("value"));
btn = $("button");
btn.attr("class", "btn");
btn.attr("data-value", "Test Value");
btn.text("Text");
console.log(btn.text());
console.log(btn.data("value"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button></button>
If you want to do this is pure JS follow the below steps.
1) Create an element using the createElement function of the document. this function through you can create any king of HTML/OWN element
2) user setAttribute function for setting the attribute
3) Append element into the parent element of the document
var animals = ['tiger','dingo','panther']
var celebrities = ['cel1 1','cel 2','cel 3']
for (var i = 0; i < animals.length; i++) {
btn = document.createElement('button');
btn.setAttribute("class", "btn");
//btn.setAttribute("onclick","clickfunction");
btn.setAttribute("value", animals[i]);
btn.innderText = celebrities[i];
console.log(btn.value);
document.getElementById("animals").append(btn);
}
Related
I am creating a series of buttons dynamically. How can I add a parameter to the Event Listener this.Purchase below as follows: this.Purchase(i)? Simply adding "(i)" does not work.
for (var i = 0; i < size; i++) {
var button = document.createElement('input')
button.setAttribute('type', 'submit')
button.setAttribute('value', 'Purchase')
button.addEventListener('click', this.Purchase)
}
var thing = {
Purchase: function() {
console.log(this.getAttribute('data-index'));
}
};
for (var i = 0; i < 3; i++) {
var button = document.createElement('input');
button.setAttribute('type', 'submit');
button.setAttribute('value', 'Purchase');
button.setAttribute('data-index', i);
button.addEventListener('click', thing.Purchase);
document.body.appendChild(button);
}
An example of using a data attribute with the event handler, as I mentioned in the comments.
Add a data attribute to each button, and call the purchase function in the onclick callback using the this keyword:
var size = 3
for (var i = 0; i < size; i++) {
var button = document.createElement('input')
button.setAttribute('type', 'submit')
button.setAttribute('value', 'Purchase')
button.dataset.idx = i
button.addEventListener('click', function() {
purchase(this.dataset.idx)
})
document.body.appendChild(button)
}
function purchase(idx) {
console.log(idx)
}
I'm trying to add and remove text boxes dynamically using javascript and HTML.
I can get it to add and remove but sometimes the remove button doesn't work. when I inspect the element it says that there is no onclick value for the remove button. I don't understand why when I set the onclick in the add function.
Heres my code:
<div id="reqs">
<h3 align = "center"> Requirements </h3>
<script>
var reqs_id = 0;
function removeElement(elementId,elementId2) {
// Removes an element from the document
var element2 = document.getElementById(elementId2);
var element = document.getElementById(elementId);
element2.parentNode.removeChild(element2);
element.parentNode.removeChild(element);
}
function add() {
reqs_id++;// increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class","w3-input w3-border");
input.setAttribute('id','reqs'+reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id','reqsr'+reqs_id);
remove.onclick = function() {removeElement('reqs'+reqs_id,'reqsr'+reqs_id);return false;};
remove.setAttribute("type","button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
This will work:
<div id="reqs">
<h3 align="center"> Requirements </h3>
</div>
<script>
var reqs_id = 0;
function removeElement(ev) {
var button = ev.target;
var field = button.previousSibling;
var div = button.parentElement;
div.removeChild(button);
div.removeChild(field);
}
function add() {
reqs_id++; // increment reqs_id to get a unique ID for the new element
//create textbox
var input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
var reqs = document.getElementById("reqs");
//create remove button
var remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e)
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove" + reqs_id;
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
}
</script>
<button type="button" value="Add" onclick="javascript:add();"> Add</button>
Fixed from my previous answer. Another option that may be necessary is to have each element know its exact place and be able to adjust itself based on what was added or removed. This enhancement will account for that by re-adjusting and ensuring your elements are always in order. (if desired)
See JSFiddle example.
Html
<div id="reqs">
<h3>Requirements</h3>
<button type="button" value="Add" onclick="javascript:add();">Add</button>
<br>
</div>
Javascript
function removeElement(e) {
let button = e.target;
let field = button.previousSibling;
let div = button.parentElement;
let br = button.nextSibling;
div.removeChild(button);
div.removeChild(field);
div.removeChild(br);
let allElements = document.getElementById("reqs");
let inputs = allElements.getElementsByTagName("input");
for(i=0;i<inputs.length;i++){
inputs[i].setAttribute('id', 'reqs' + (i+1));
inputs[i].setAttribute('value', (i+1));
inputs[i].nextSibling.setAttribute('id', 'reqsr' + (i+1));
}
}
function add() {
let allElements = document.getElementById("reqs");
let reqs_id = allElements.getElementsByTagName("input").length;
reqs_id++;
//create textbox
let input = document.createElement('input');
input.type = "text";
input.setAttribute("class", "w3-input w3-border");
input.setAttribute('id', 'reqs' + reqs_id);
input.setAttribute('value', reqs_id);
let reqs = document.getElementById("reqs");
//create remove button
let remove = document.createElement('button');
remove.setAttribute('id', 'reqsr' + reqs_id);
remove.onclick = function(e) {
removeElement(e);
};
remove.setAttribute("type", "button");
remove.innerHTML = "Remove";
//append elements
reqs.appendChild(input);
reqs.appendChild(remove);
let br = document.createElement("br");
reqs.appendChild(br);
}
I want to create buttons and add classes to those button after creation
I am working on below code !1 Please Help me out :)
Will this work?
$("#"+element.id).addClass(".btn");
Thank you in advance !!
for (var i = 0; i < 9; i++) {
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id = "btn" + i;
element.onclick = function() {
window.move(i);
};
var append = document.getElementById("append");
append.appendChild(element);
alert(element.id);
$("#" + element.id).addClass(".btn");
}
You can add classes in javascript like that:
element.className += 'className';
If you are using jQuery then what you did is correct, except the dot you put into addClass function. So instead of:
$(element).addClass('.className');
You do:
$(element).addClass('className');
I think you should use without dot.
$("#"+element.id).addClass("btn");
You can just use the classList.add method on the element you create.
for (var i = 0; i < 9; i++)
{
add(i);
}
function add(i) {
var element = document.createElement("input");
element.type = "button";
element.value = i;
element.name = i + 1;
element.id="btn"+i;
element.classList.add("btn");
element.onclick = function () {
window.move(i);
};
var append =document.getElementById("append");
append.appendChild(element);
}
You can add class directly by accessing "className" property.
var element = document.createElement("input");
element.type = "button";
element.className = "clr-red";
Refer here for more
you just type the class name only
addClass("btn"); instead of addClass(".btn");
// how to set id to this created buttons?
for(i=1;i<=3;i++)
{
var btn = document.createElement("BUTTON");// create button using java script
btn.className = "btnsize";
var txt = document.createTextNode(num++);//creat text on button
btn.appendChild(txt);//attached text on button
document.getElementById("xyz").appendChild(btn);//atache button with text in div
}
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON");
btn.setAttribute("class","btnsize");
btn.setAttribute("id","btnid"+i);
var txt = document.createTextNode("button");
btn.appendChild(txt);
document.getElementById("xyz").appendChild(btn);
}
btn.id = "btnid"+i
This will number them accordingly
html
<div id="xyz"></div>
js
for (i = 1; i <= 3; i++) {
var btn = document.createElement("BUTTON");// create button using java script
btn.className = "btnsize";
btn.id = "btnid"+ i;
var txt = document.createTextNode("aaasasa");//creat text on button
btn.appendChild(txt);//attached text on button
document.getElementById("xyz").appendChild(btn);//atache button with text in div
}
DEMO
In you code num is not defined. you should add i in btn.id = "btnid"+ i; for unique ids.
Im new to javascript and coding in general, I'm trying to make a simple to do list but cant get the delete button to delete all the checkboxes, it will only delete the first checkbox made. Thanks guys.
http://jsfiddle.net/fbct3oL7/1/
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
listItem.id = task;
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
checkbox.name = task;
checkbox.id = "checkbox";
document.getElementById('place').appendChild(listItem);
document.getElementById(task).insertBefore(checkbox, listItem.firstChild);
}
function deleteCheckBox() {
while (document.getElementById('checkbox').checked === true) {
var itemNode = document.getElementById(checkbox.name);
itemNode.parentNode.removeChild(itemNode);
}
}
I've modified your code, eliminating unnecessary id and name attributes, and updated the deleteCheckBox function to cycle through all the li in the ul.
function taskadd() {
taskNew = new objectTask();
}
function objectTask() {
var task = document.getElementById('textinput').value;
var listItem = document.createElement("li");
var checkbox = document.createElement("input")
checkbox.type = "checkbox";
listItem.appendChild(checkbox);
var itemText = document.createTextNode(task);
listItem.appendChild(itemText);
document.getElementById('place').appendChild(listItem);
}
function deleteCheckBox() {
var ul = document.getElementById('place');
var li = ul.children;
for (var i=0; i < li.length; i++) {
while(li[i] && li[i].children[0].checked) {
ul.removeChild(li[i]);
}
}
}
<div id="list">
<input type='text' id='textinput' />
<input type='button' onclick='taskadd()' value='Add to list' />
<input type='button' onclick="deleteCheckBox()" value='Delete' />
<ul id="place"></ul>
</div>
I also forked and updated your Fiddle: http://jsfiddle.net/JohnnyEstilles/gtpdLkLq/.
You give every checkbox the same id, and the getElementById method only returns the first matching element.
If you want to get all checkboxes and delete the checked ones you could start by doing like this. (Please notice that this code is written freehand and untested)
var inputs = document.getElementsByTagName("input");
for(i=o; i < inputs.length; i++){
if(inputs[i].type == "checkbox" && inputs[i].checked){
inputs[i].parentNode.removeChild(inputs[i]);
}
}
First get all element with the tag "input", then check if they are of checkbox type and checked.