EDIT:
Currently using this javascript code, it works for the plus box but not the minus. (changed code fragment from the below.
// Create buttons for creating and removing inputs
var newAddButton = document.createElement('input');
newAddButton.id= "submit2";
newAddButton.type = "button";
newAddButton.value = " + ";
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = " - ";
newAddButton.id= "submit2";
I've got a javascript form, two buttons and a form is created when the plus is clicked, I was just wondering if the buttons that appear can be set to the same CSS style as the button next to the drop down lists.
So in short a css style attached to the buttons made through a javascript
HTML
<div id="mainContainer">
<div>
<select name="text[]">
<option value="t1">t1</option>
<option value="t2">t2</option>
<option value="t3">t3</option>
</select>
<input name="none" type="button" id="submit2" onClick="addNew();" value=" + ">
</div>
</div>
JAVASCRIPT
var counter = 0;
function addNew(e) {
var countAll = document.getElementsByTagName("select").length - 1;
var lastSelectBox = document.getElementsByTagName("select")[countAll];
var items = lastSelectBox.innerHTML;
// Get the main Div in which all the other divs will be added
var mainContainer = document.getElementById('mainContainer');
// Create a new div for holding text and button input elements
var newDiv = document.createElement('div');
// Create a new text input
var newText = document.createElement('select');
newText.type = "select";
newText.setAttribute("name", "text[]");
newText.innerHTML = items;
//for testing
// Create buttons for creating and removing inputs
var newAddButton = document.createElement('input');
newAddButton.type = "button";
newAddButton.value = " + ";
var newDelButton = document.createElement('input');
newDelButton.type = "button";
newDelButton.value = " - ";
// Append new text input to the newDiv
newDiv.appendChild(newText);
// Append new button inputs to the newDiv
newDiv.appendChild(newAddButton);
newDiv.appendChild(newDelButton);
// Append newDiv input to the mainContainer div
mainContainer.appendChild(newDiv);
// Add a handler to button for deleting the newDiv from the mainContainer
newAddButton.onclick = addNew;
newDelButton.onclick = function() {
mainContainer.removeChild(newDiv);
};
};
There are a number of things wrong with the fiddle.
To get your question out of the way, the CSS has an extraneous }, which causes the style for #submit3 to be ignored. Remove it.
The Javascript in the fiddle should not be wrapped in an onload handler; set it to "No wrap - in head" or "No wrap - in body". Otherwise clicking the button won't work.
The newly created buttons all have the same IDS. This is a no-no. Make the Javascript remember how many buttons there are and give them a unique ID based on the count. (Something like ++numberofbuttons; id = 'submit'+(numberofbuttons*2); for the one, and same plus +1 for the other.)
Oh, and your fiddle differs from the example code in the question. Don't do that.
Related
Having trouble getting the a label dynamically assigned to a radio button. all of the code is working except the innerHTML. Cannot spot why. Thanks in advance for any help.
<!DOCTYPE html>
<html>
<body>
<form id="myForm">
</form>
<br>
<button onclick="addRadio()">Add radio buttons!</button>
<script>
// This function will add a new Radio buttons to the above
count = 0;
function addRadio()
{
count++;
//Create input type
var myRadio = document.createElement("input");
var myName = document.createElement("testRadio");
var myBreak = document.createElement("br");
var myLabel = document.createElement("label");
var labelMessage = "Radio Button: " + count;
var labelId = "l" + count;
myRadio.setAttribute("type", "radio");
myRadio.setAttribute("name", "testRadio");
myRadio.setAttribute("value", "Radio Button: " + count);
myLabel.setAttribute("for", labelId);
myRadio.setAttribute("id", labelId);
document.getElementById('myForm').appendChild(myRadio);
document.getElementById('myForm').appendChild(myLabel);
document.getElementById('myForm').appendChild(myBreak);
document.getElementById('labelId').innerHTML = 'labelMessage';
}
</script>
</body>
</html>
The label element might not be inserted by the next line itself. It is better to do
myLabel.innerHTML = 'labelMessage';
As you have the element already in a variable.
There is a tiny error in the code.
Before the .innerHTML you get the element by id 'labelId' as a string.
You need to select with the labelID as a var so:
document.querySelector(`label[for="${labelId}"]`).innerHTML = labelMessage;
I am very new to javascripts and trying to create a dynamic html form where there are multiple button, and each button click map to a corresponding form input. Here is my code:
<html>
<head>
<title>Create Group</title>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(){
$("#generate_form").click(function(){
var number = document.getElementById("number_of_groups").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var i;
for (i=1;i<=number;i++){
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
}
})
});
</script>
</head>
<body>
<h2>Create some group(s)</h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"/>
</body>
</html>`
So, the user would input number of groups to create and click 'Go' button, then the code should dynamically generate the form with the number the user choose. Each group of the form includes a input textbox and a 'Generate' button. When the button is clicked, the input textbox will show "hello world". However, the "hello world" only show up in the last input textbox no matter which 'Generate' button I click. So I changed the onclick function of the button to:
button.onclick = function(){ alert(thisID);};
Then I found that thisID is always the id of the last input textbox no matter which 'Generate' button I click. I guess that is because the binding of the click event does not happen till the script is done when 'thisID' would always be its latest value.
Would anyone please help me to realize the functionality I want? Thank you very much!
You would need to wrap the code within the for loop in a separate function, passing in the value of i as a parameter. This would create a closure, creating a new execution scope for your code. Otherwise what is happening is that your var is being hoisted, and is not exclusive to each iteration of the for loop, so your DOM is reflecting only the last value it was assigned.
for (i=1;i<=number;i++){
(function (i) {
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
})(i);
}
You can check out an article on closures here:
https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36
EDIT: As one of your commenters mentioned, you can also set your vars to 'let' to achieve a similar effect. This is because let scopes the variable to the current code block, rather than being hoisted to the scope of the function, so each for loop iteration has a private let variable. It is still recommended to get a good understanding of closures and how they work, however.
Since you are already using JQuery, you can reduce some of the logic.
Let me know if this helps-
<html>
<head>
<title>Create Group</title>
</head>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(()=>{
var txtGroup='<input type="text" id="txt_group_{0}" value="">';
var btnGroup='<button id="btn_group_{0}" type="button">Click Me</button>';
var container=$('#container');
$('#generate_form').click((e)=>{
var groupCount=parseInt($('#number_of_groups').val());
var idToStart=$('#container').children('div').length+1;
for(let i=idToStart;i< idToStart+groupCount;i++){
var divGroup=`<div id="div_group_${i}">`+
txtGroup.replace('{0}',i)+
btnGroup.replace('{0}',i)+`</div>`;
container.append(divGroup);
$('#btn_group_'+i).on('click',(e)=>{
console.log('#txt_group_'+i);
$('#txt_group_'+i).val('Hello World');
});
}
});
});
</script>
<body>
<h2></h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"></div>
</body>
</html>
I am a still a newbie so sorry for any mistakes. I have searched a lot and couldn't solve my problem. I dynamically created this radio input:
var radio_input = document.createElement('input');
radio_input.type = "radio";
radio_input.name = "test_input"
radio_input.value = "teeest";
radio_input.appendChild(my_form);
However I can't get the input value to show up. I get something similar to this:
(but one instead of 3)
I want to have "test" written in the left side of the input... Can someone help me?
As #RobertoLinare said in his comment, you can create a div and append the label:
var radio_input = document.createElement('input');
var label = document.createElement('label');
var div = document.createElement('div');
radio_input.type = "radio";
radio_input.name = "test_input"
radio_input.value = "teeest";
label.innerHTML = "Label";
document.getElementById("my_form").appendChild(div);
div.appendChild(label);
div.appendChild(radio_input);
<form id="my_form">
</form>
Html :
<form id="my_form"></form>
JS :
var myForm = document.getElementById("my_form");
// Clear previous contents of the container
while (myForm.hasChildNodes()) {
myForm.removeChild(myForm.lastChild);
}
var radio_input = document.createElement("input");
radio_input.type = "radio";
radio_input.name = "test_input";
radio_input.value = "teeest";
var label = document.createElement('label');
label.innerHTML = "Label Title ";
myForm.appendChild(radio_input);
myForm.appendChild(label);
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!
I'm currently trying to add a jQuery function to a row of radio buttons. The problem is that I need to add dynamically many rows. Now For this example I only added 2 elements into the array of newNodes, but in my application newNodes can potentially have many different sizes.
So basically I want to add the Query function something like this:
$('#rowID input').on('change', function() {
alert($('input[name=i]:checked', '#rowID').val());
});
Where it exists inside the forloop and is added for each new row. "rowID" is a variable assigned to the unique row identifier and then use the loop iterator "i" as a way to distinguish the radio buttons for each row.
Here is the HTML:
<form id="createEdges" method="POST>
<fieldset>
<legend class="title">Modify the graph!</legend>
<table id="createEdgesTable">
</table>
<input type="button" class="btn btn-default" id="backToThirdForm" onclick="goBackToForm3()" value="Back"/>
</fieldset>
And Here is the Javascript:
newNodes = [];
newNodes.push(0);
newNodes.push(1);
//get HTML Table to add rows in
var edgeTable = document.getElementById("createEdgesTable");
//Create a table row for each node
for (var i in newNodes) {
var row = edgeTable.insertRow();
row.id = "node" + i;
//Show name of the node
var td = document.createElement('td');
var text = document.createTextNode(newNodes[i]);
td.appendChild(text);
row.appendChild(td);
//Choice for showing node
var td2 = document.createElement('td');
var radioButton1 = document.createElement('input');
radioButton1.type = "radio";
radioButton1.name = i;
radioButton1.value = "showNode";
td2.appendChild(radioButton1);
row.appendChild(td2);
//Choice for creating edge
var td3 = document.createElement('td');
var radioButton2 = document.createElement('input');
radioButton2.type = "radio";
radioButton2.name = i;
radioButton2.value = "createEdge";
td3.appendChild(radioButton2);
row.appendChild(td3);
//Choice for deleting node
var td4 = document.createElement('td');
var radioButton3 = document.createElement('input');
radioButton3.type = "radio";
radioButton3.name = i;
radioButton3.value = "removeNode";
td4.appendChild(radioButton3);
row.appendChild(td4);
var rowID = row.id;
}
$('#node0 input').on('change', function() {
alert($('input[name=0]:checked', '#node0').val());
});
JSFiddle: https://jsfiddle.net/nxexrq9y/
Any example on how to make this work for each row? I'm relatively new to JQuery and have been stuck on this problem for quite some time now. Thank you for your time and help!
Just change your script with following code.
$('tr[id^=node] input').on('change', function() {
alert(this.value);
});
Explanation:
Scripts find any tr whose id starts with node. this covers all your dynamically generated TRs. Further selection narrows down to only input element in each TR, and registers change event for that element. On that change event your have already got that element so you can easily access its value there.
Here is Js Fiddle Link
Further if you want to know clicked radio falls in which node, you can check out this js fiddle.
$('tr[id^=node] input').on('change', function() {
var row = $(this).parents('tr:first').get(0);
alert('Node: '+ row.id+ ' value:' + this.value);
});