How to dynamically create a form using javascript? - javascript

Below code adds text-content to the list dynamically,
window.onload = function()
{
//alert("Window is loaded");
var numberList = document.getElementById("numberList");
//for every number between 100 and 200
for(var i = 0; i > 100 && i < 200; i++)
{
if ( i % 17 == 0 && i % 2 == 0) //if number evenly divisible by 17 and 2
{
//create new li element
var newNumberListItem = document.createElement("li");
//create new text node
var numberListValue = document.createTextNode(i);
//add text node to li element
newNumberListItem.appendChild(numberListValue);
//add new list element built in previous steps to unordered list
//called numberList
numberList.appendChild(newNumberListItem);
}
}
}
Now, instead of adding the text content like "i" to list, I want to add a form with one textfield and one submit-button.
Thanks in advance.

Just an example, you can change as per your requirement
Inside script tag
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input");
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input");
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
document.getElementsByTagName('body')[0].appendChild(f);

try something like this in javascript ...
/*Form creation*/
var form = document.createElement("form");
var input = document.createElement("input");
form.action = "FileNameHere";
form.method = "post";
input.name = "name";
input.value = "testname";
form.appendChild(input);
form.submit();

Related

Using onclick in javascript to create a new div inside a div created using onclick itself?

I created a div consisting of radio button inputs using onclick from a radio button input inside a form in php and then i again attempted to create another div using onclick from inside this created div but only the outer div is being created. Would like to know where i am wrong..
<input id="sub" type="radio" name="opt1" value="2" onclick="createDiv4()"> Academic User<br/>
function createDiv4() {
if(document.getElementById("acad_")==null)
{
var divi = document.createElement("div");
divi.id="acad_";
divi.style.height="100px";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.onclick="createDiv4_1()";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("Technical Institute");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
ip2.onclick="createDiv4_1()";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("School");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("acad_");
divi1.parentNode.removeChild(divi1);
}
}
</script>
<script>
function createDiv4_1() {
if(document.getElementById("school")==null)
{
var divi = document.createElement("div");
divi.id="school";
//divi.style.marginTop="200px";
var cont = document.getElementById('contain');
cont.appendChild(divi);
var p = document.createElement("label");
var disp = document.createTextNode("Please select the type of User for Workshop :");
p.appendChild(disp);
p.style.textSize="16px";
p.style.textAlign="left";
divi.appendChild(p);
var b1 = document.createElement("BR");
divi.appendChild(b1);
var ip = document.createElement("input");
ip.name="wo";
ip.value="1";
ip.type="radio";
ip.style.marginRight="4px";
divi.appendChild(ip);
var labe = document.createElement("label");
var labe_val = document.createTextNode("School Student");
labe.appendChild(labe_val);
divi.appendChild(labe);
var b = document.createElement("BR");
divi.appendChild(b);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe2 = document.createElement("label");
var labe_val2 = document.createTextNode("Teacher");
labe2.appendChild(labe_val2);
divi.appendChild(labe2);
var b2 = document.createElement("BR");
divi.appendChild(b2);
var ip2 = document.createElement("input");
ip2.name="wo";
ip2.value="2";
ip2.type="radio";
ip2.style.marginRight="4px";
divi.appendChild(ip2);
var labe3 = document.createElement("label");
var labe_val3 = document.createTextNode("Parent");
labe3.appendChild(labe_val3);
divi.appendChild(labe3);
if(document.getElementById("govt")!=null)
{
var de = document.getElementById("govt");
de.parentNode.removeChild(de);
}
}
else
{
var divi1 = document.getElementById("school");
divi1.parentNode.removeChild(divi1);
}
}
</script>
You arent calling the functions properly. Instead of :
ip.onclick= "createDiv4_1()";
This is only a string, it won't call it. You put it in quotes in the HTML but in JavaScript you don't need to. Also get rid of the parenthesis in JS. So use this :
ip.onclick= createDiv4_1;
Working fiddle : https://jsfiddle.net/thatOneGuy/xgvqwcq4/2/
I added a div with ID contain for this to work too.
according to your question title you have two option.
forget about onclikc inside the html and use normal js
document.getElementById("secondDiv").addEventListener("click", function () {
newFunctionI();
})
/*JQ version*/
$("#secondDiv").on("click", function () {
newFunctionI();
})
second way is: use jquery append() or html();
function yourFunctionI() {
$("#ID").append("<div id='secondDiv' onclick='newFunction()'> new </div>")
}

Extracting values from a table in Javascript

Please I tried getting the values imputed by the user but when I input the value and cluck submit, the page reloads without showing the values. any help please. Thank you
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '2px solid yellow';
var n = 10
for (var i = 0; i < n; i++) {
var tr = tbl.insertRow();
var td = tr.insertCell(0);
var tf = tr.insertCell(0);
var input = document.getElement('input');
input.name = "input2";
input.id = "input2";
input.value = "";
var clone = input.cloneNode();
clone.name = "input1";
clone.id = "input1";
td.appendChild(clone);
tf.appendChild(input);
td.style.border = '2px solid yellow';
tf.style.border = '2px solidyellow';
}
var form = document.createElement("form");
form.appendChild(tbl);
body.appendChild(form);
var submit = document.createElement("input");
submit.type = "submit";
Submit.on click = 'show()'
function show() {
var c = document.getElementById("input2").value;
document.write(c.value);
}
form.appendChild(submit)
tableCreate();
var c = document.getElementById("input2");
document.write(c);
I don't think doing things like myElement.onclick='show()' makes sense, since you are doing things in JS anyway. Why not just add an event listener to the form, which would listen for submit? Preventing the default action (which includes refreshing the page) should be what you are looking for, if I got you correctly.
form.addEventListener('submit', function(event){
event.preventDefault(); // <-- prevents page reload
//
// Here goes your code, that should
// execute when the form is submitted
});
EDIT:
Here's a JSFiddle. Enter some values, press submit and then check your console. You will see 2 arrays - one with the left values, one with the right ones.

Creating an object with 4 button on javascript

I created an object on js with 4 buttons, but it's not showing,
this is my code:
function Keyboard() {
this.plus = document.createElement("input");
this.plus.type = "submit";
this.plus.value = "A";
this.minus = document.createElement("input");
this.minus.type = "submit";
this.minus.value = "B";
this.multi = document.createElement("input");
this.multi.type = "submit";
this.multi.value = "C";
this.divide = document.createElement("input");
this.divide.type = "submit";
this.divide.value = "D";
}
var k = new Keyboard();
document.body.appendChild(k);
I will add the onClick later, but why is this not showing?
Thanks!
Your Keyboard constructs a simple JavaScript object with 4 properties, but not a DOM object. Later, you try to append a simple JavaScript object to your document.
First, you need to create DOM element using document.createElement.
Second, you don't need new keyword here at all.
Third, you don't need to set subitems as properties. You append them to a parent object, and it is enough.
Try the following code:
function CreateKeyboard() {
var t = document.createElement("div");
var plus = document.createElement("input");
plus.type = "submit";
plus.value = "A";
t.appendChild(plus);
var minus = document.createElement("input");
minus.type = "submit";
minus.value = "B";
t.appendChild(minus);
var multi = document.createElement("input");
multi.type = "submit";
multi.value = "C";
t.appendChild(multi);
var divide = document.createElement("input");
divide.type = "submit";
divide.value = "D";
t.appendChild(divide);
return t;
}
document.body.appendChild(CreateKeyboard());
By the way, you can avoid code repetition. For example, by utilizing Array.prototype.forEach:
function CreateKeyboard() {
var t = document.createElement("div");
['A', 'B', 'C', 'D'].forEach(function(l) {
var elem = document.createElement("input");
elem.type = "submit";
elem.value = l;
t.appendChild(elem);
});
return t;
}
document.body.appendChild(CreateKeyboard());
This should work:
<script type="text/javascript">
function createSubmitButton(val) {
var el = document.createElement("input");
el.type = "submit";
el.value = val;
document.body.appendChild(el);
}
createSubmitButton("A");
createSubmitButton("B");
createSubmitButton("C");
createSubmitButton("D");
</script>
Make sure you place the script tag at the bottom of the html code, right before the ending body tag.
k is not type of Node. Append only Node elements you have created.
var k = new Keyboard();
document.body.appendChild(k.plus);
document.body.appendChild(k.minus);
document.body.appendChild(k.multi);
document.body.appendChild(k.divide);

Unable to generate Unique IDs and access them in document.getElementById()

function printPerson(nop) {
if (nop == null || nop == 0) {
document.getElementById("div1").innerHTML = "";
}
else {
for (var i = 0; i < nop; i++) {
var element = document.createElement("input");
var label = document.createElement("Label");
var button1 = document.createElement("input");
var button2 = document.createElement("input");
var br = document.createElement("br");
label.innerHTML = "User Name :";
// addition text box
element.setAttribute("type", "text");
element.setAttribute("name", "addition");
element.setAttribute("id", "cal");
// button 1
button1.setAttribute("type", "button");
button1.setAttribute("value", "+");
button1.setAttribute("onclick", "document.getElementById('cal').value += '+' ");
// button 2
button2.setAttribute("type", "button");
button2.setAttribute("value", "=");
button2.setAttribute("onclick", "document.getElementById('cal').value = eval(document.getElementById('cal').value)");
var para = document.getElementById("div1");
para.appendChild(label);
para.appendChild(element);
para.appendChild(br);
para.appendChild(button1);
para.appendChild(button2);
para.appendChild(br);
count++;
}
}
}
Here I am trying to create text boxes and buttons based on the user input but I was not able to give unique IDs for each and every dynamically generated fields so the actions are being performed only one first created text box
Try with -
element.setAttribute("id", "cal" + i);
The ids will be cal1, cal2 and so on.. And hope you will do the same for the name attribute.

Changing input values after row has been removed

I'm trying to create a tool where the user clicks on a button and it adds a label,input and remove button. I have it all working for the most part but there is only couple things missing. If the user had let's say adds "4" items and he/she deleted item "2"; I want the label value to subtract
"-1" of its value and the id of that item to subtract "-1" of its value. Any help would be appreciated!
I have created a jsFiddle below:
http://jsfiddle.net/ryanverdel/fUhL8/
HTML
<input type="input" value="0" id="theValue" />
<div id="myDiv">
</div>
Javascript
function addItem() {
if ($('#theValue').val() < 10){
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value -1)+ 2;
numi.value = num;
var newdiv = document.createElement('form');
var newlabel = document.createElement('input');
var newinput = document.createElement('input');
var newbutton = document.createElement('input');
var divIdName = 'Address'+num;
newdiv.setAttribute('id',divIdName);
newbutton.setAttribute('type','button');
newbutton.setAttribute('onclick','onclick=confirmDelete("'+divIdName+'"); return false;');
newbutton.setAttribute('value','Delete');
//newlabel.innerHTML ='Address('+num+')';
newlabel.setAttribute('value','Address '+num+':')
newlabel.setAttribute('size','8');
newlabel.setAttribute('class','label');
newlabel.setAttribute('readonly','true');
newinput.setAttribute('type','text');
newinput.setAttribute('id',divIdName+'_input');
ni.appendChild(newdiv);
newdiv.appendChild(newlabel);
newdiv.appendChild(newinput);
newdiv.appendChild(newbutton);
}
else{
return false;
};
}
function confirmDelete(divNum){
if (confirm("Are you sure you want to delete " +divNum+"?"))
{
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
var getLabel = olddiv.getElementsByClassName("label");
var counter= $('#theValue').val();
$('#theValue').val( (counter-1<0)?counter:--counter );
//$(getLabel).nextAll().css( "color", "red" );
$(olddiv).nextAll().css('background-color', 'red').css('color','red');
d.removeChild(olddiv);
}
else{};
}

Categories