Create Checkbox with Javascript - javascript

I am trying to create a checkbox with javascript when a button is clicked. I am really struggling, I have searched the net for help and this is the closest I've got but it does not work.
What have I done wrong?
<p>Click the buttons to create a Checkbox.</p>
<button onclick="addCheckBox()">Create a button</button>
<input id="check" name="checkBoxes">
<script>
function addCheckBox() {
var ColorsAvailable = document.getElementById('checkBoxes');
var check_value = new Array( )
check_value[0] = "Yellow"
check_value[1] = "Red"
check_value[2] = "Green"
for(var count in check_value)
{
var color=document.createElement("input");
color.value=(check_value[count] + '</br>');
color.type="checkbox";
color.id="color" + count;
ColorsAvailable.appendChild(color);
}
}
</script>

After you add an element that has an id of checkBoxes and some semicolons ; the code actually works.
function addCheckBox() {
var ColorsAvailable = document.getElementById('checkBoxes');
var check_value = new Array();
check_value[0] = "Yellow";
check_value[1] = "Red";
check_value[2] = "Green";
var color, p, br;
for(var count in check_value)
{
color=document.createElement("input");
color.value=(check_value[count] + '</br>');
color.type="checkbox";
color.id="color" + count;
p =document.createElement("span");
p.innerHTML = check_value[count] + ": ";
br =document.createElement("br");
ColorsAvailable.appendChild(p);
ColorsAvailable.appendChild(color);
ColorsAvailable.appendChild(br);
}
}
input[type='checkbox']
{
margin-right:20px;
}
<p>Click the buttons to create a Checkbox.</p>
<button onclick="addCheckBox()">Create a button</button>
<input id="check" name="checkBoxes">
<div id="checkBoxes"></div>

The id of the input was check and not checkBoxes. I changed it and also you can't directly append in the input so I made it append in the parent node but you could change to be on another place.
<p>Click the buttons to create a Checkbox.</p>
<button onclick="addCheckBox()">Create a button</button>
<input id="checkBoxes" name="checkBoxes">
<script>
function addCheckBox() {
var ColorsAvailable = document.getElementById('checkBoxes');
var check_value = new Array( )
check_value[0] = "Yellow"
check_value[1] = "Red"
check_value[2] = "Green"
for(var count in check_value)
{
var color=document.createElement("input");
color.value=(check_value[count] + '</br>');
color.type="checkbox";
color.id="color" + count;
ColorsAvailable.parentNode.appendChild(color);
}
}
</script>

Make checkboxes a DIV.
<div id="check" name="checkBoxes"></div>
and change this
var ColorsAvailable = document.getElementById('check');

Related

Add and Delete text using 2 buttons in javascript (conditions : use div id 'divResult' , console log.)

I want to make a webpage with 2 buttons (Add, Delete). Conditions are using div id divResult , console log and after removing that div has to stay. It works almost correct, just last step (remove alinea) doesn`t work. Can you help me , how can i fix it? :-)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>2 buttons</title>
<script >
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement')
var alinea = oldDiv.querySelectorAll('p:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
oldDiv.removeChild(alinea);
console.log('verwijderd!');
};
};
</script>
</head>
<body>
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
</body>
</html>
I've tried a few things, moved stuff around. I think it's doing what you want now.
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement');
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
alinea.remove();
// divResult.removeChild(alinea);
console.log('verwijderd!');
};
};
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
If I understand you correctly, change the following section:
document.getElementById('Btn2').onclick = function () {
var alinea = document.getElementById('div'+ --index);
console.log(alinea.innerHTML + ' wordt verwijderd...');
alinea.remove(alinea);
console.log('verwijderd!');
};

How to clear all dynamically created SPAN elements

I've created some code that dynamically creates some fields within a SPAN element. One of the fields is a delete icon, that when click runs a function to remove the selected span. Now I want to create a function that simply wipes out all the spans, sounds simple but it breaks after the first one.
This is a sample of my code (modified it for simplicity):
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ip = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ip.setAttribute("type", "text");
ip.setAttribute("value", item)
ip.setAttribute("Name", "text_item_element_" + global_i);
ip.setAttribute("id", "id_item_" + global_i);
ip.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ip);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
In each line for the image I set the onclick event handler to run the function removeSpanElement(parentDiv, childDiv) and it works fine. So to clear them all I'd think I just run the function through an incremental loop, clearItems(), but it stops after removing the first one and I can't figure out why.
You can simply add a new class to the dynamically added span(to make it easy to select them), then remove all the elements with the added class like
var global_i = 0; // Set Global Variable i
function increment() {
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem() {
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ins = document.createElement("INPUT");
var im = document.createElement("IMG");
var el = document.createElement('SPAN');
ins.setAttribute("type", "text");
ins.setAttribute("value", item);
ins.setAttribute("Name", "text_item_element_" + global_i);
ins.setAttribute("id", "id_item_" + global_i);
ins.setAttribute("style", "width:80px");
im.setAttribute("src", "delete.png");
im.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(ins);
el.appendChild(im);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
el.className = 'dynamic'
document.getElementById("myForm").appendChild(el);
}
/* This function only clears 1st span */
function clearItems() {
var spans = document.getElementsByClassName('dynamic');
while (spans.length) {
spans[0].remove();
}
global_i = 0;
}
<form>
<input type='text' id='item' value='' />
<input type="button" value="Add" onclick="addItem()" />
<input type="button" value="Clear All" onclick="clearItems()" />
<span id="myForm"></span>
</form>
You were using a reserved keyword, and you were having a variable undefined. I've edited the code for you. Compare my code with yours to see where are the mistakes.
<form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem(){
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var ig = document.createElement("INPUT"); // "in" is a reserved keyword. It can't be used as a variable
var ip = document.createElement("IMG");
var el = document.createElement('SPAN');
ig.setAttribute("type", "text"); // modified
ig.setAttribute("value", item) //
ig.setAttribute("Name", "text_item_element_" + global_i); //
ig.setAttribute("id", "id_item_" + global_i); //
ig.setAttribute("style", "width:80px"); //
ig.setAttribute("src", "delete.png"); // "im" was undefined. You probably wanted to write "in", but it was wrong anyway
ig.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')"); // the same
el.appendChild(ig);
el.appendChild(ig);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
<code> <form>
<input type='text' id='item' value=''/>
<input type="button" value="Add" onclick="addItem()"/>
<input type="button" value="Clear All" onclick="clearItems()"/>
<span id="myForm"></span>
</form>
<script>
var global_i = 0; // Set Global Variable i
function increment()
{
global_i += 1; // Function for automatic increment of field's "ID" attribute.
}
function addItem()
{
try{
increment();
var item = document.getElementById("item").value;
var br = document.createElement('BR');
var in_e = document.createElement("INPUT");
var ip_e = document.createElement("IMG");
var el = document.createElement('SPAN');
in_e.setAttribute("type", "text");
in_e.setAttribute("value", item)
in_e.setAttribute("Name", "text_item_element_" + global_i);
in_e.setAttribute("id", "id_item_" + global_i);
in_e.setAttribute("style", "width:80px");
ip_e.setAttribute("src", "delete.png");
ip_e.setAttribute("onclick", "removeSpanElement('myForm','id_" + global_i + "')");
el.appendChild(in_e);
el.appendChild(in_e);
el.appendChild(br);
el.setAttribute("id", "id_" + global_i);
document.getElementById("myForm").appendChild(el);
}catch(e){alert(e)}
}
function removeSpanElement(parentDiv, childDiv)
{
if (childDiv == parentDiv){
return false;
}
else if (document.getElementById(childDiv)){
var child = document.getElementById(childDiv);
var parent = document.getElementById(parentDiv);
parent.removeChild(child);
return true;
}
else{
// Child div has already been removed or does not exist
return false;
}
}
/* This function only clears 1st span */
function clearItems()
{
var remove = true;
var i = 1;
while(remove){
remove = removeSpanElement("myForm","id_" + i);
i++;
}
global_i = 0;
}
</script>
</code>

javascript buttons firing another button

I want to create a button that creates another button. The other button get an id attribute by counting from 1 to infinity. This functionality should done on all buttons (original button and the news).
var btn = document.createElement("input");
btn.type = "button"
btn.value = "button"
btn.id = "btn_rv"
body.appendChild(btn);
function create_another_button(elm) {
var counter = parseInt(elm.getAttribute('data-counter'));
var button = document.createElement('button');
button.innerText = elm.id + '_' + counter;
button.id = elm.id + '_' + counter;
button.setAttribute('data-counter', '1');
button.setAttribute('onclick','create_another_button(this)');
document.body.appendChild(button);
elm.setAttribute('data-counter', ++counter)
}
<button id="btn_rv" onclick="create_another_button(this)" data-counter="1">Main Button</button>
http://jsbin.com/tuwoxe/edit?html,css,js
I do not get the use case, but this should be what you are looking for:
var btn = document.createElement("input");
var countBtn;
btn.type = "button";
btn.value = "button";
btn.id = "btn_rv";
document.body.appendChild(btn);
btn.addEventListener('click', function(){
if (!countBtn){
countBtn = document.createElement("input");
countBtn.type = "button";
countBtn.value = 0;
countBtn.id = "btn_rv";
document.body.appendChild(countBtn);
}
else{
countBtn.value++;
}
}, false);
Check it out at https://jsfiddle.net/ugyknfc0/
if you want to fire another button , try this code
<input type="button"
id="BtnId"
onclick="fireButton();addButton();" />
Function 1 for firing the Button
function fireButton()
{
document.getElementById('btn_rv_1').click()
}
Function 2 for adding the Button
function addButton()
{
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", type);
element.setAttribute("name", type);
var place= document.getElementById("SpanID");
//Append the element in page (in span).
place.appendChild(element);
}
In HTML
<span id="SpanID"> </span>
If you wish you can try this.
html
<body>
<div id="top">
<button id="button_1">Button 1</button>
</div>
<script type="text/javascript" src="func.js"></script>
</body>
func.js
var bid = 2;
document.getElementById("button_1").addEventListener("click", function () {
add_button(bid);
add_event_listener(bid);
bid += 1;
});
function add_button(button_id) {
var div = document.getElementById("top");
div.innerHTML = div.innerHTML + "<button id='button_" + button_id + "'>Button " + button_id + "</button>";
}
function add_event_listener(button_id) {
document.getElementById("button_" + button_id).addEventListener("click", function () {
add_button(bid);
add_event_listener(bid);
++bid;
});
}

How to display a number below each dynamically created images?

I want to display a particular image as many times as the number given by user.This part is accomplished. But i want to display a number below each image. For example if user input is 4, there should be 4 images with '1' below 1st image '2' below second. The image must also be clickable.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<div id="demo">
<script>
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var c="<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push(c);
document.getElementById("demo").innerHTML = arr.join("&nbsp&nbsp");
}
}
</script>
</body>
</html>
var imageSrc = "http://fc08.deviantart.net/fs71/f/2010/148/1/9/20x20_PNG_Icons_DOMO_by_JMcIvor.png";
function imag(c,x) {
var x = document.getElementById("myNumber").value;
var demo = document.getElementById("demo");
var container = document.createElement("div");
container.setAttribute("class", "container");
for(var i=0; i<x; i++) {
var image = document.createElement("img");
image.setAttribute("class", "image");
image.setAttribute("src", imageSrc);
container.appendChild(image);
var text = document.createElement("div");
text.innerHTML = i+1;
container.appendChild(text);
demo.appendChild(container);
}
}
#demo {
}
.container {
}
.image {
}
.text {
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to add a new element to the array.</p>
<input type="number" id="myNumber" value="">
<button onclick="imag()">Try it</button>
<div id="demo"></div>
</body>
</html>
I just use another image url to test the code, replace it with your one. I hope this helps.
You already have the number you're looking for in your loop. So you can simply add it to your array like this.
JS:
function imag() {
var x = document.getElementById("myNumber").value;
var c = "<img src='C:/Users/Akhil/Desktop/New folder/G.jpg'/>";
var arr = [];
for (var i = 0; i < x; i++) {
arr.push("<div class='image'>" + c + "<br />" + (i+1) + "</div>");
}
document.getElementById("demo").innerHTML = arr.join("&nbsp&nbsp");
}
CSS:
div.image {
display: inline-block;
}

Adding a Select Box Dynamically

I am creating an application using JSP.
In one of the Pages , the user needs to enter some Symptoms . Now i want to give a button. when the user clicks this button , a new select box is created .
I have searched a lot and can only find how to dynamically add options to select but i want new select box
Someone please help .
Here's a sample code:
<html>
<head>
<script type="text/javascript">
function addSelectBox ()
{
var parentDiv = document.getElementById ("main");
var selectElement = document.createElement ("select");
for (var i=0;i < 5;i++)
{
var option = new Option ("Text " + i, "Value" + i);
selectElement.options[selectElement.options.length] = option;
}
parentDiv.appendChild (selectElement);
}
</script>
</head>
<body>
<div id="main">
<input type="button" onclick="addSelectBox ()" name="clickme" value="Add Select Box" />
</div>
</body>
</html>
EDIT:
For JSP (if you have the options in an ArrayList):
<html>
<head>
<%
int totalElements = 5;
ArrayList r = new ArrayList (totalElements);
for (int i=1;i <= totalElements;i++)
{
r.add (String.valueOf (i));
}
%>
<script type="text/javascript">
function addSelectBox ()
{
var parentDiv = document.getElementById ("main");
var selectElement = document.createElement ("select");
var option;
<%
for (int i=0;i <= r.size();i++)
{
%>
option = new Option ('<%=r.get (i)%>', '<%=r.get (i)%>');
selectElement.options[selectElement.options.length] = option;
<%
}
%>
parentDiv.appendChild (selectElement);
}
</script>
</head>
<body>
<div id="main">
<input type="button" onclick="addSelectBox ()" name="clickme" value="Add Select Box" />
</div>
</body>
</html>
$(".your-button").click(function() {
var selectBoxHtml = ["<select>"];
var sourceItems = [4,5,6];
for (var sourceIndex = 0; sourceIndex < sourceItems.length; sourceIndex++) {
selectBoxHtml.push('<option value="' + sourceIndex + '">' + sourceItems[sourceIndex] + '</option');
}
$(this).after(selectBoxHtml.join("") + "</select>");
});
Once sourceItems is dynamic, be sure to escape it.

Categories

Resources