How to create multiple textbox in javascript using for loop? - javascript

I want to add text to dynamically created textbox.
var dynamicTextBox= "";
for (var i = 0; i < vm.FitToWork.length; i++) {
dynamicTextBox+= '<input class="form-control" name = "DynamicTextBox" id= "DynamicTextBox" type="text" value = "'vm.FitToWork[i]'" /> ' +
'<button id="btnAdd" class="delete-decl">+</button>';
}
document.getElementById("TextBoxContainer").innerHTML=dynamicTextBox;
its not working..

You have syntax error. You are trying to concatenate a variable vm.FitToWork[i] but not using concatenation operator (+). Try the following code:
var dynamicTextBox= "";
// ignore this. just have this to get the code working
var vm = {FitToWork : ["test","rest","vest"]};
for (var i = 0; i < vm.FitToWork.length; i++) {
dynamicTextBox += '<input class="form-control" name = "DynamicTextBox" id= "DynamicTextBox" type="text" value = "' + vm.FitToWork[i] + '" />';
dynamicTextBox += '<button id="btnAdd" class="delete-decl">+</button></br>';
}
document.getElementById("TextBoxContainer").innerHTML = dynamicTextBox;
<div id="TextBoxContainer"></div>

You missed concat.
var dynamicTextBox= "";
for (var i = 0; i < vm.FitToWork.length; i++) {
dynamicTextBox+= '<input class="form-control" name = "DynamicTextBox" id= "DynamicTextBox" type="text" value = "'+vm.FitToWork[i]+'" /> ' + '<button id="btnAdd" class="delete-decl">+</button>';
}
document.getElementById("TextBoxContainer").innerHTML=dynamicTextBox;

You forgot to add pluses in value:
... value="' + vm.FitToWork[i] + '" ...

value should be in + + value = "' + value + '"
so value = "'+vm.FitToWork[i]+'"
or you can try this
'<input name = "DynamicTextBox" type="text" value = "' + value + '" />' +
'<input type="button" value="+" id="btnAdd" class="delete-decl" />'

Related

JavaScript post same name for multiple inputs

I want to upload in the database using pure javascript in my following input fields.
var i = 2;
var id=1;
function addkid() {
var div = document.createElement('div');
console.log('my id cj '+id)
div.innerHTML = 'Day' + id + ': <input type="text" name="child_' + id + '"/>' + '<input type="button" class="submit_but" id="rem_kid()_' + id + '" onclick="remkid(this)" value="-" />';
//div.innerHTML = 'Day' + id + ': <input type="text" name="child_' + id + '"/>' + ' <input type="button" id="add_kid()_' + id + '" onclick="addkid()" value="+" />' + ' <input type="button" id="rem_kid()_' + id + '" onclick="remkid(this)" value="-" />';
// event.stopPropagation();
document.getElementById('kids').appendChild(div);
id++;
}
function remkid(div) {
document.getElementById('kids').removeChild(div.parentNode);
i--;
}
/////////////////////////////////////////
var i = 1;
var idd = 1;
function addmen() {
var div = document.createElement('div');
console.log('my id cj '+idd);
//var id = i;
// alert(id);
div.innerHTML = 'img' + idd + ': <input type="file" name="child_' + id + '"/>' + '<input type="button" class="submit_but" id="rem_kid()_' + id + '" onclick="remmen(this)" value="-" />';
//div.innerHTML = 'Day' + id + ': <input type="text" name="child_' + id + '"/>' + ' <input type="button" id="add_kid()_' + id + '" onclick="addkid()" value="+" />' + ' <input type="button" id="rem_kid()_' + id + '" onclick="remkid(this)" value="-" />';
document.getElementById('menand').appendChild(div);
idd++;
}
function remmen(div) {
document.getElementById('menand').removeChild(div.parentNode);
i--;
}
Title:
<input type="text" name="name">
<br/>
<div id="kids">
Day/s:
<!--<input type="text" name="child_1">-->
<input type="button" class="submit_but" id="add_kid()_1" onclick="addkid()" value="Add tour day" /><br>
</div>
<div id="menand">
Img/s:
<!--<input type="file" name="img">-->
<input type="button" class="submit_but" id="add_kid()_1" onclick="addmen()" value="Add tour Image" /><br>
</div>
<div>
<input type="button" value="Save" name="Save" class="submit_but" onclick="saveroute()">
</div>
I want to know how to upload this multiple same name input field into the database. I'm never doing this type of code in before. please help solve my problem
The id is an unique identifier. The means that your 'id=add_kid()_1' can't repeat for more than one . The class attribute can repeat. In this case, you'll use the class="submit_but" to catch the two input tags.
Then, the first step is extract the info. There's only two inputs to extract info from and they have the tag in common: "submit_but".
const infoElements = document.querySelector('.submit_but');
infoElemnts contains all nodes with class="submit_but".
Here your answer pt1
If you wanna store the info of inputs in an array:
const infoValues = infoElements.map((element) => {
return element.value;
}
Now, infoValues has all inputs values. You can do all this process with yours childs inputs that will be created.
div.innerHTML = '<input class="dayTour"></input>'
div.innerHTML = '<input class="whatever"></input>'
const dayTourElements = document.querySelector('.dayTour');
const dayTourValues = dayTourElements.map((element) => {
return element.value;
}
Here your answer pt2
I don't how you wanna save this, but for simple approach you can simple write it to your local storage into a '.txt' file.
const fs = require('fs');
fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
if (err) throw err;
console.log('Saved!');
});
Here tutorial: https://www.w3schools.com/nodejs/nodejs_filesystem.asp

Modify form-data before post submit?

I have a really big form (too many values for a post request) and now I tried to minimy reduce the number of post parameters by summarizing the values line by line.
<form name="old_postform" method="post" action="https://example.com" />
<input type="text" name="1_firstname" />
<input type="text" name="1_lastname" />
<input type="text" name="1_age" />
<input type="text" name="2_firstname" />
<input type="text" name="2_lastname" />
<input type="text" name="2_age" />
<input type="text" name="3_firstname" />
<input type="text" name="3_lastname" />
<input type="text" name="3_age" />
</form>
I already tried to react on the submit event of the form by interrupting this and submitting another form instead, but this didnt work well because I have some other values which need to be submitted too:
$('form[name="old_postform"]').submit(function (e) {
let new_postform = '<form id="new_postform" method="post">';
for(var i = 0; i < 1000; i++) {
new_postform += '<input type="hidden" name="' + i + '" value="';
new_postform += $('input[name=' + i + '_firstname' + ']').val() + ';';
new_postform += $('input[name=' + i + '_lastname' + ']').val() + ';';
new_postform += $('input[name=' + i + '_age' + ']').val() + ';';
}
new_postform += '</form>';
$("#new_postform").submit();
});
Is there a simple way to remove all post parameters which start with a one, two or three digit from the old form and add my new post_form instead ?
I really would appreciate your help! ;)
you don't need to create another form to submit. Read all parameters and remove unwanted inputs from the form, add semicolon separated values as hidden input and submit the form.
See below code
$('form[name="old_postform"]').submit(function (e) {
var $form = $(this);
var $inputs = $form.find(":input");
var len = $inputs.length/3; // calculate number of firstname, lastname and age per index
for(var i=1; i<=len; i++){
var $fn = $('input[name=' + i + '_firstname]');
var $ln = $('input[name=' + i + '_lastname]');
var $age = $('input[name=' + i + '_age]');
var values = '<input type="hidden" name="' + i + '" value="';
values += $fn.val() + ';';
values += $ln.val() + ';';
values += $age.val() + ';">';
//remove read elements
$fn.remove();
$ln.remove();
$age.remove();
//append hidden input
$form.append(values);
};
$form.submit();
});

HTML not rendering tags positions as given in JS

I've been stuck on this for days now but I can't seem to figure out why the <form> element is ending automatically. Here's the JS that creates it
nextStep.innerHTML = '<div class="directions">' + directions + '</div><form action="php/login.php" method="post">';
for (i = 0; i < data.length; i++) {
if (data[i].toLowerCase() != 'password') {
nextStep.innerHTML = nextStep.innerHTML + '<input name="' + data[i].toLowerCase() + '" class="input" placeholder="' + data[i] + '" autocomplete="off">';
} else {
nextStep.innerHTML = nextStep.innerHTML + '<input name="' + data[i].toLowerCase() + '" class="input" type="password" placeholder="' + data[i] + '" autocomplete="off">';
}
nextStep.innerHTML = nextStep.innerHTML + '<br>';
}
nextStep.innerHTML = nextStep.innerHTML + '<input class="login" type="submit" value="Login"></form>';
It results in this HTML
<div id="currentStep" class="step">
<form action="php/login.php" method="post"></form>
<div class="directions">Please Login</div>
<input name="email" class="input" placeholder="Email" autocomplete="off">
<br>
<input name="password" class="input" type="password" placeholder="Password" autocomplete="off">
<br>
<input class="login" type="submit" value="Login">
<div class="back" onclick="back()">< Back</div>
</div>
The <form> tag ends on the same line instead of where the </form> is. I'd like it to start where is is and end right before the back button. If you need any more of the JS please tell me.
Don't set concatenate innerHTML, when you write innerHTML = "Something" it will assume that the HTML is the finished version and try to patch it.
let nextStepHTML = "";
nextStepHTML = '<div class="directions">' + directions + '</div><form action="php/login.php" method="post">';
for (i = 0; i < data.length; i++) {
if (data[i].toLowerCase() != 'password') {
nextStepHTML = nextStepHTML + '<input name="' + data[i].toLowerCase() + '" class="input" placeholder="' + data[i] + '" autocomplete="off">';
} else {
nextStepHTML = nextStepHTML + '<input name="' + data[i].toLowerCase() + '" class="input" type="password" placeholder="' + data[i] + '" autocomplete="off">';
}
nextStepHTML = nextStepHTML + '<br>';
}
nextStepHTML = nextStepHTML + '<input class="login" type="submit" value="Login"></form>';
nextStep.innerHTML = nextStepHTML;
Now it should render properly
P.S. i'll rewrite it to something prettier below
const nextStepStart = `<div class="directions">${directions}</div><form action="php/login.php" method="post">`;
const nextStepMiddle = data.map(current => {
const passwordString = current.toLowerCase() === 'password' ? `type="password"` : ``;
return `<input name="${current.toLowerCase()}" class="input" ${passwordString} placeholder="${current}" autocomplete="off">`;
}).join(`<br>`);
const nextStepEnd = `<input class="login" type="submit" value="Login"></form>`
nextStep.innerHTML = `${nextStepStart}${nextStepMiddle}${nextStepEnd}`;
Lets also do it using Element.appendChild() and negative coding
Starting with the last first
const createInput = name => {
const stepInput = document.createElement(`input`);
const isPassword = name.lowerCase() === `password`;
stepInput.name = name.toLowerCase();
stepInput.className = `input`;
stepInput.placeholder = name;
stepInput.autocomplete = `off`;
if(isPassword){
stepInput.type = `password`;
}
return stepInput;
}
const submitButton = () => {
const submitButton = document.createElement(`input`);
submitButton.className = `login`;
submitButton.type= `submit`;
submitButton.value= `Login`;
return submitButton;
}
const createForm = (dataList) => {
const form = document.createElement(`form`);
form.action = `php/login.php`;
form.method = `post`;
const fragment = new DocumentFragment();
dataList.forEach(data => {
fragment.appendChild(createInput(data));
fragment.appendChild(document.createElement(`br`));
}
fragment.appendChild(submitButton());
form.appendChild(fragment);
return form;
}
const directions = document.createElement(`div`);
directions.className = `directions`;
directions.appendChild(createForm(data));
nextStep.appendChild(directions);

dynamically removing textbox

I am dynamically adding and removing textboxes though I can successfully adds textbox but unable to remove textbox on clicking the remove button every time i have to reload the browser to remove the textboxes after clicking remove button.
here is my javascript for adding and removing textboxes.
<script type="text/javascript">
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
});
</script>
here is my html for textboxes.
<div id="TextBoxesGroup">
<div class="control-group">
<label class="control-label">answer_1: </label>
<div class="controls">
<input type="text" name="answer_1" id="answer_1" required="true" >
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1">Rank 1</label>
<div class="controls">
<input type="text" name="rank_1" id="rank_1" required="true">
</div>
</div>
<div class="control-group">
<label class="control-label">answer_2: </label>
<div class="controls">
<input type="text" name="answer_2" id="answer_2" required="true" >
<button class="btn btn-mini btn-danger" data-toggle="button" type="button" id="removeButton">
-
</button>
<button class="btn btn-mini btn-success" data-toggle="button" type="button" id="addButton">
+
</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1" required="true">Rank 2</label>
<div class="controls">
<input type="text" name="rank_2" id="rank_2" required="true">
</div>
</div>
</div>
can anyone what's wrong in it so that I am unable to remove textboxes on clicking the button ? Thanks
you need to modify 2 things here:
1- when appending the new elements, mark their holding div with the current COUNTER value at the end, so it's easy to target them later (like on step 2 below).
so adding new elements should be like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group'+COUNTER+'">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
...
...
instead of this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
2- when removing elements, we will target those with the current COUNTER value at the end of their class name,this way you will remove the last group, and still check if the groups are 3 or lower, no removal should happen.
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$(".control-group"+COUNTER).remove();
});
});
Update: check my updated fiddle http://jsfiddle.net/qqqyC/1/
note: considering that we are appending the COUNTER value at the end of the class name. if class is giving you any styles it will not work. in this case you should not use class name as the target property and consider marking the new group using another attribute/property, and target this attribute/property when removing your elements.
Use .on as you want to bind $("#removeButton").click(function () { to dynamically added elements. It should be
$("#removeButton").on("click", function () {
//.....
});
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#answer_" +COUNTER).parent('div').parent('div').remove();
$("#rank_" +COUNTER).parent('div').parent('div').remove();
});
});
Please update script or check this fiddle http://jsfiddle.net/Cne2Q/
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
What you're doing here, - you're trying to remove an element like $("#TextBoxesGroup1") which obviously doesn't exist. So what you need to do is modify your create new input like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div id="textBoxContainer'+COUNTER+'" class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
and your remove button
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#textBoxContainer" +COUNTER).remove();
});

How to insert <input> tag inside <div> tag using javascript?

I am new to javascript.
I just want to create a list with textbox and label in a row.
So that I created a ul tag with id cstList.
and called a function listData() on the onclick event
Inside that I am trying to create a input tag inside a div tag.
But i am getting error when trying to run this.
Here is my code:
function listData()
{
//var a = sessionStorage.getItem('id');
if(sessionStorage == null)
{
alert("Session storage not supported here");
}
else
{
var ss = sessionStorage.getItem('id');
alert("storage value is: "+ss);
}
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
var divID = 'div_' + i.toString();
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);"><div id = "'+ divID + '"> <input type= 'text' id= 'boltQTY' name= 'boltQTY' value = 'abc' size="5"/> </div></li>';
}
document.getElementById('cstList').innerHTML = listCode;
}
This is the above line where i am getting error: Unexpected Identifier
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);"><div id = "'+ divID + '"> <input type= 'text' id= 'boltQTY' name= 'boltQTY' value = 'abc' size="5"/> </div></li>';
You are using single quotes and that is breaking the string.
<input type= 'text' id= 'boltQTY' name= 'boltQTY' value = 'abc' size="5"/>
should be:
<input type= "text" id= "boltQTY" name= "boltQTY" value = "abc" size="5"/>
That has to be double-single-single-double
listCode += "<li id='" + listID + "' onclick='itemClicked(this.id);'><div id = '"+ divID + "'> <input type='text' id='boltQTY' name='boltQTY' value='abc' size='5'/> </div></li>";
variable = "string" + var1 + "string=' " + var2 +"' ";
Simply make sure plus sign (+) is in between double quotes ("")

Categories

Resources