How to generate input fields dynamically - javascript

I have a form with input fields.
Once,I clicked on submit button I want to generate 2 input fields with a "plus / +" icon. So, when I click on "+" icon it will generate input fields.
Here is the html part:
<label>Name</label>
<input type="text" value="Jim" id="demo_1" name="demo_name" class="input-medium"/>
<label>Id</label>
<input type="text" value="123" id="demo_1" name="demo_name" class="input-medium">
<button id="demo_submit" class="btn" name="demo_submit" type="button">Submit</button>

I suggest to have a look at existing plugins (For example - Jquery SheepIt! Plugin) and see how that is coded.
To add dynamically form elements this can be done with the clone() method and DocumentFragment - http://ejohn.org/blog/dom-documentfragments/

Working example at http://plnkr.co/edit/szYoU4GCeLWX8b9DcsYT
<script type="text/javascript">
function addFields () {
var newNode1 = document.createElement('input'),
newNode2 = document.createElement('input');
newNode1.type = newNode2.type = "text"; document.forms[0].appendChild(newNode1);
document.forms[0].appendChild(newNode2);
}
</script>
<form>
<label>Name</label>
<input type="text" value="Jim" id="demo_1" name="demo_name" class="input-medium"/>
<label>Id</label>
<input type="text" value="123" id="demo_1" name="demo_name" class="input-medium">
<button id="demo_submit" class="btn" name="demo_submit" type="button" onclick="addFields()">Submit</button>
</form>

$(".addInput").click(function {
$("form").append( PUT INPUT ELEMNT HERE);
});

Check this out.
HTML
<label>Name</label>
<input type="text" value="Jim" id="demo_1" name="demo_name" class="input-medium" />
<label>Id</label>
<input type="text" value="123" id="demo_1" name="demo_name" class="input-medium">
<button id="demo_submit" class="btn" name="demo_submit" type="button">Submit</button>
<button id="demo_add" class="btn" name="demo_add" type="button">Add more</button>
<div id='add'></div>
jQuery
$('#demo_add').click(function () {
$inputName = "<input type='text' placeholder='Name'/>";
$inputId = "<input type='text' placeholder='Id'/>";
$br = "<br/>";
$('#add').append($inputName);
$('#add').append($inputId);
$('#add').append($br);
});
Hopefully it helps.

Related

Submit div content as textarea with hidden fields

Got a form and I need to submit the content of five divs. I read many solutions and I figured I could use hidden fields, but I don't know how. Javascript or jquery would be great
<form name="module" id="module" method="post" action="" title="postthis">
<div name="mytext" id="mytext">Here's something I want to pass</div>
<div name="mytext2" id="mytext2">Again, I want this div to act as a text area</div>
<div name="mytext3" id="mytext3">Another text</div>
<div name="mytext4" id="mytext4">Yet another</div>
<div name="mytext5" id="mytext5">Last one</div>
<input name="mytext" type="hidden" id="mytext" value="mytext" />
<input name="mytext2" type="hidden" id="mytext2" value="mytext3" />
<input name="mytext3" type="hidden" id="mytext3" value="mytext4" />
<input name="mytext4" type="hidden" id="mytext4" value="mytext5" />
<input name="mytext5" type="hidden" id="mytext5" value="mytext6" />
<input name="insert" type="submit" class="btn btn-primary" id="insert" value="Save my fields" onClick="return validate_login(module);" />
</form>
Please see below code snippet. to help you achieve your goals. This solution is broken into two parts, the HTML markup and the Javascript code. data-input is used to connect corresponding hidden fields ids. These is then submitted to the server for processing.
function augmentValues(divClass = "mytext") {
const divs = document.getElementsByClassName(divClass);
Array.from(divs).forEach(divElem => {
const inputId = divElem.getAttribute("data-input");
const hiddenInput = document.getElementById(`${inputId}`)
hiddenInput.value = divElem.textContent
})
}
function handleSubmit(event) {
event.preventDefault()
augmentValues();
const formData = new FormData(event.target);
const formValues = Object.fromEntries(formData.entries())
// Validate inputs
// Submit form
console.log(formValues)
event.target.submit()
}
<form name="module" id="module" method="post" action="" title="postthis" onsubmit="handleSubmit(event)">
<div class="mytext" data-input="mytext">Here's something I want to pass</div>
<div class="mytext" data-input="mytext2">Again, I want this div to act as a text area</div>
<input name="mytext" type="hidden" id="mytext" value="" />
<input name="mytext2" type="hidden" id="mytext2" value="" />
<button name="insert" type="submit" class="btn btn-primary">
Save my fields
</button>
</form>

Text display and gone again in JavaScript

I don't know what is happening. I'm inputting value for the operation to solve but when it displays the result it displays but in a brief time only.
function add(){
var num1 = document.getElementById('fnum').value;
var num2 = document.getElementById('snum').value;
var ans = parseFloat(num1) + parseFloat(num2);
document.getElementById('res').value = ans;
}
<form>
1st Number:<input type="text" id="fnum" name="Num1" /><br>
2nd Number:<input type="text" id="snum" name="Num2" /><br><br>
<input type="submit" value="Add" id="button1" name="button" onclick="add()"/>
The result is:<input type="text" id="res" name="res" readonly="true" /><br>
</form>
Because you are using the <form> tag with a <button type="submit">, the form is submitted.
So what's happening is that your onclick event is handled, but when that's done, the form is still submitted. You have multiple ways of fixing this:
Don't use <form>
Change the <button> type to button
Handle the form submit in JavaScript
Cancel the click event
Here's a working version without a <form> tag and <button type="button">:
function add() {
var num1 = document.getElementById('fnum').value;
var num2 = document.getElementById('snum').value;
var ans = parseFloat(num1) + parseFloat(num2);
document.getElementById('res').value = ans;
}
1st Number:<input type="text" id="fnum" name="Num1" /><br>
2nd Number:<input type="text" id="snum" name="Num2" /><br><br>
<input type="button" value="Add" id="button1" name="button" onclick="add()" />
The result is:<input type="text" id="res" name="res" readonly="true" /><br>
it's because your button is a submit component,
change :
<input type="submit" value="Add" id="button1" name="button" onclick="add()"/>
to
<button type="button" value="Add" id="button1" name="button" onclick="add()">add</button>
a submit component used to submit your form so you'll need a valid action in your form for that.
or you can use onsubmit event for your form to prevent default form action

Get inputs value in javascript using arrays

I am using HTML and javascript to getting some values from the user. I have one input text and two buttons on the page. first button for adding input text to form and the second button for sending data to javascript script. my code is like the following code :
function add_input_function() {
var html = "<input type='text' placeholder='Your text' id='text_input[]'/><br/>";
$("#container").append(html);
}
function send_function() {
var inputs = document.getElementById("text_input");
for (var i = 0; i < inputs; i++) {
console.log(inputs.value);
}
}
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<form method="post">
<div id="container">
<input class="input" type="text" placeholder="Your text" id="text_input[]" /><br/>
</div>
<br/>
<input onclick="add_input_function()" type="button" id="add" value="Add Input">
<br/>
<input onclick="send_function()" type="button" id="add" value="Send">
</form>
I want to get all of the values and show them in the console and separate with -. Can you help me?
(My for loop doesn't work now)
Add some class for each input, then when you click on send button, grab all element by class selector, and iterate loop on element to get value
<form method="post">
<div id="container">
<input class="input info" type="text" placeholder="Your text" /><br/>
</div>
<br/>
<input onclick="add_input_function()" type="button" id="add" value="Add Input">
<br/>
<input onclick="send_function()" type="button" id="add" value="Send">
</form>
<script>
function add_input_function() {
var html = "<input type='text' class='info' placeholder='Your text' /><br/>";
$("#container").append(html);
}
function send_function() {
var inputText = [];
var inputs = document.getElementsByClassName("info");
for (var i = 0; i < inputs.length; i++) {
console.log(inputs[i].value);
inputText.push(inputs[i].value)
}
var finalContent = inputText.join(' - ');
console.log(finalContent);
}
</script>
This is an alternative
function add_input_function() {
var html = "<input type='text' placeholder='Your text' id='text_input[]'/><br/>";
$("#container").append(html);
}
function send_function() {
let result = '';
$('input[type="text"]').each(function(index){
result += $(this).val() + '-';
});
alert(result);
}
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<form method="post">
<div id="container">
<input class="input" type="text" placeholder="Your text" id="text_input[]" /><br/>
</div>
<br/>
<input onclick="add_input_function()" type="button" id="add" value="Add Input">
<br/>
<input onclick="send_function()" type="button" id="add" value="Send">
</form>
i hope it helps...
var index=1;
var inpidarr=[];
inpidarr.push("text_input0")
function add_input_function() {
var html = "<input type=\"text\" placeholder=\"Your text\" id=\"text_input".concat(String(index))+"\"/><br/>";
$("#container").append(html);
inpidarr.push("text_input".concat(String(index)))
index++;
}
function send_function() {
;
for(i=0;i<inpidarr.length;i++)
{
console.log(document.getElementById(inpidarr[i]).value);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<form method="post">
<div id="container">
<input class="input" type="text" placeholder="Your text" id="text_input0"/><br/>
</div>
<br/>
<input onclick="add_input_function()" type="button" id="add" value="Add Input">
<br/>
<input onclick="send_function()" type="button" id="add" value="Send">
</form>

Javascript - Object reference returning null even though it shoudn't

I've got this:
var strBox = document.getElementById("txtSTR");
var strModBox = document.getElementById("txtSTRMod");
var refBox = document.getElementById("txtREF");
var refModBox = document.getElementById("txtREFMod");
var fortBox = document.getElementById("txtFOR");
var forModBox = document.getElementById("txtFORMod");
var intBox = document.getElementById("txtINT");
var intModBox = document.getElementById("txtINTMod");
These vars all point to text boxes (read only) in my HTML document.
They rely on populating their .value with the following array:
//0-STR, 1-REF, 2-FOR, 3-INT, 4-JUD, 5-CHA, 6-WIL, 7-TOU
var charAttsAR = ["8","8","8","8","8","8","8","8"];
They are populated with the relevant array entry manually from a function called popDefDat() like this:
strBox.value = charAttsAR[0];
strModBox.value = modSetter(charAttsAR[0]);
refBox.value = charAttsAR[1];
refModBox.value = modSetter(charAttsAR[1]);
fortBox.value = charAttsAR[2];
forModBox.value = modSetter(charAttsAR[2]);
intBox.value = charAttsAR[3];
intModBox.value = modSetter(charAttsAR[3]);
....and so on
My issue is that strBox, strModBox, refBox and refModBox all initialise their data fine. However, at fortBox, it throws "fortBox is null" and I have no idea why. The code is identical, I have my script loaded just before the end of my tag and I also have:
//initialise default data when page loads
window.onload = popDefDat()
Honestly, I'm stuck. Any advice appreciated.
Here's the html too:
<form id="form3" name="form3" method="post" onsubmit="return false" action="">
<p><label></label>
<label for="lblHeadATT"></label>
<input name="lblHeadATT" type="text" disabled="disabled" id="lblHeadATT" value="Points" readonly="readonly" />
<label for="lbHeadMOD"></label>
<input name="lbHeadMOD" type="text" disabled="disabled" id="lbHeadMOD" value="Mod" readonly="readonly" />
<label for="txtPointBuy"></label>
<input name="txtPointBuy" type="text" id="txtPointBuy" readonly="readonly" />
<p>Strength:
<label for="txtSTR"></label>
<input name="txtSTR" type="text" id="txtSTR" readonly="readonly" />
<label for="txtSTRMod"></label>
<input name="txtSTRMod" type="text" id="txtSTRMod" readonly="readonly" />
<input type="button" name="Btn_StrMinus" id="Btn_StrMinus" value="-" onclick="FNCstrSub()" />
<input type="button" name="Btn_StrPlus" id="Btn_StrPlus" value="+" onclick="FNCstrPlus()"/>
<p>Reflex:
<label for="txtREF"></label>
<input name="txtREF" type="text" id="txtREF" readonly="readonly" />
<label for="txtREFMod"></label>
<input name="txtREFMod" type="text" id="txtREFMod" readonly="readonly" />
<input type="button" name="Btn_RefMinus" id="Btn_RefMinus" value="-" onclick="FNCrefSub()" />
<input type="button" name="Btn_RefPlus" id="Btn_RefPlus" value="+" onclick="FNCrefPlus()"/>
<p>Fortitude:
<label for="txtREF"></label>
<input name="txtFOR" type="text" id="txtREF" readonly="readonly" />
<label for="txtFORMod"></label>
<input name="txtFORMod" type="text" id="txtFORMod" readonly="readonly" />
<input type="button" name="Btn_ForMinus" id="Btn_ForMinus" value="-" onclick="FNCforSub()" />
<input type="button" name="Btn_ForPlus" id="Btn_ForPlus" value="+" onclick="FNCforPlus()"/>
</p>
<p>Intellect:
<label for="txtINT"></label>
<input name="txtINT" type="text" id="txtINT" readonly="readonly" />
<label for="txtINTMod"></label>
<input name="txtINTMod" type="text" id="txtINTMod" readonly="readonly" />
<input type="submit" name="Btn_IntMinus" id="Btn_IntMinus" value="-" onclick="FNCintSub()"/>
<input type="submit" name="Btn_IntPlus" id="Btn_IntPlus" value="+"onclick="FNCintPlus()" />
I've yet to write the tags for the other text boxes and buttons as I was hoping to solve this before carrying on.
Thanks

Combo box for all control

I created a filterable drop Down List using JavaScript. This is the List Box Coding.
<select name="d1" class="leftselect" id="d1" size="5" ondblclick="DropDownTextToBox('d1','t1');" style="display:none;" >
<option>axcsus-COMMON STOCK</option>
<option>aces</option>
<option>bdfs</option>
<option>befs</option>
<option>behs</option>
<option>dfgh</option>
<option>dhes</option>
<option>dwww</option>
<option>pass</option>
<option>pass</option>
</select>
I created 4 Text Field and a arrow character. If i click the arrow character , I'll show the list at the bottom of the control.
<div id="div_name" style="float:left;z-index: 20;">
<input name="t1" type="text" id="t1" onkeyup="value_filtering('d1','t1');" onkeypress="onEnter(event,'d1','t1')" />
<input type="button" class="rightselect" onclick="displayList('d1','t1');" value="▼" />
</div>
<div class="inputbox">
<input name="t2" class="inputbox" type="text" id="t2" onkeyup="value_filtering('d2','t2');" onkeypress="onEnter(event,'d2','t2')" />
<input type="button" class="leftselect" onclick="displayList('d1','t2');" value="▼" />
</div>
<div style="float:left;text-align:center;" >
<input name="t3" type="text" id="t3" onkeyup="value_filtering('d3','t3');" onkeypress="onEnter(event,'d3','t3')" />
<input type="button" class="rightselect" onclick="displayList('d1','t3');" value="▼" />
</div>
<div class="inputbox">
<input name="t4" class="inputbox" type="text" id="t4" onkeyup="value_filtering('d4','t4');" onkeypress="onEnter(event,'d4','t4')" />
<input type="button" class="leftselect" onclick="displayList('d1','t4');" value="▼" />
</div>
In the display List function I'm getting the corresponded textbox position and displayed the List Control under the Text Box. Okie. Now my problem is If i select any option in the text box, I need to display the selected value to the textbox which the listbox shown under. After selecting the value from the list box, How i find in which text box showing the List ? Dynamically how can i find the text box id ?
This is my JS code for displaying the Listbox to the corresponding TextBox.
function displayList(ele,txt)
{
vis=document.getElementById(ele);
obj=document.getElementById(txt);
if (vis.style.display==="none")
vis.style.display="block";
else
vis.style.display="none";
vis.style.position = "absolute";
//alert(getElementPosition(txt).top + ' ' + getElementPosition(txt).left);
vis.style.top = getElementPosition(txt).top+obj.offsetHeight;
vis.style.left = getElementPosition(txt).left;
}
Note : I can call this function at the click event of arrow button. I can easily pass the text Field Id. But in the case ListBox action i can't send the particular ID of the Text Field.
If you have no opposition to using jquery you can using the jquery UI built-in autocomplete which will do pretty much what you're looking for. For more advanced and nicer plugins you can try chosen
Try this.
<script>
var targetInput=null;
function displayList(ele,txt) {
vis=document.getElementById(ele);
obj=document.getElementById(txt);
targetInput = obj;
if (vis.style.display==="none") {
vis.style.display = "block";
} else {
vis.style.display = "none";
vis.style.position = "absolute";
//alert(getElementPosition(txt).top + ' ' + getElementPosition(txt).left);
vis.style.top = getElementPosition(txt).top+obj.offsetHeight;
vis.style.left = getElementPosition(txt).left;
}
}
function selectList(txt) {
if (!targetInput) return;
targetInput.value = txt.value;
txt.style.display = 'none';
}
</script>
<div id="div_name" style="float:left;z-index: 20;">
<input name="t1" type="text" id="t1" onkeyup="value_filtering('d1','t1');" onkeypress="onEnter(event,'d1','t1')" />
<input type="button" class="rightselect" onclick="displayList('d1','t1');" value="▼" />
</div>
<div class="inputbox">
<input name="t2" class="inputbox" type="text" id="t2" onkeyup="value_filtering('d2','t2');" onkeypress="onEnter(event,'d2','t2')" />
<input type="button" class="leftselect" onclick="displayList('d1','t2');" value="▼" />
</div>
<div style="float:left;text-align:center;" >
<input name="t3" type="text" id="t3" onkeyup="value_filtering('d3','t3');" onkeypress="onEnter(event,'d3','t3')" />
<input type="button" class="rightselect" onclick="displayList('d1','t3');" value="▼" />
</div>
<div class="inputbox">
<input name="t4" class="inputbox" type="text" id="t4" onkeyup="value_filtering('d4','t4');" onkeypress="onEnter(event,'d4','t4')" />
<input type="button" class="leftselect" onclick="displayList('d1','t4');" value="▼" />
</div>
<select name="d1" class="leftselect" id="d1" size="5" ondblclick="DropDownTextToBox('d1','t1');" onclick="selectList(this)" style="display:none;">
<option>axcsus-COMMON STOCK</option>
<option>aces</option>
<option>bdfs</option>
<option>befs</option>
<option>behs</option>
<option>dfgh</option>
<option>dhes</option>
<option>dwww</option>
<option>pass</option>
<option>pass</option>
</select>

Categories