Javascript add multiple form fields dynamically - javascript

I am new in javascript and PHP. I am creating a form where I need an option that user clicks on add fields then some fields add.
I am using this script:
<script type="text/javascript">
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
Entry 1
and it's working but I need this code in the inner HTML
<label>Category <strong>*</strong></label>
<font id=catname>
<select name='catname'>
<option value='0'>============</option>
</select></font>
<label>Item<strong>*</strong></label><font id=itemname>
<select disabled='disabled' name='itemname'>
<option value='0'></option>
</select></font>
So how can I put these fields ?
Complete Code
<script type="text/javascript">
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
<div class="form-style-5" style="margin-left: 360px;">
<form name="form1" method="post" action="outgoingstocksave.php">
<fieldset>
<legend><span class="number"> </span> Outgoing Stocks Entry</legend>
<label>Ref. No.</label>
<input type="text" readonly="readonly" name="refno" value="<?php echo $refno; ?>">
<div id="dynamicInput">
<label>Category <strong>*</strong></label>
<font id=catname>
<select name='catname'>
<option value='0'>============</option>
</select></font>
<label>Item<strong>*</strong></label><font id=itemname>
<select disabled='disabled' name='itemname'>
<option value='0'></option>
</select></font>
<input type="number" name="quantity" maxlength="10" placeholder="ITEM QUANTITY *" required>
</div>
<input type="text" name="date" readonly="readonly" id="datepicker" placeholder="DATE *" required>
</fieldset>
<input type="submit" value="Save" />
</form>
</div>
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val) {
var req = Inint_AJAX();
req.onreadystatechange = function () {
if (req.readyState==4) {
if (req.status==200) {
document.getElementById(src).innerHTML=req.responseText; //retuen value
}
}
};
req.open("GET", "itemsfill.php?data="+src+"&val="+val); //make connection
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=iso-8859-1"); // set Header
req.send(null); //send value
}
window.onLoad=dochange('catname', -1); // value in first dropdown
</script>

I did a test on something similar a couple years back. See if you can hack this up for your needs.
Script...
<script type = "text/javascript">
var cnt = 0;
function addFile() {
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + cnt + '" name="file' + '' + '" type="file" />' +
'<input id="Button' + cnt + '" type="button" ' + 'value="X" onclick="deleteFile(this)" />';
document.getElementById("uploadControls").appendChild(div);
cnt++;
buttonText();
}
function deleteFile(div) {
document.getElementById("uploadControls").removeChild(div.parentNode);
cnt--;
buttonText();
}
function buttonText() {
if (cnt > 0) {
document.myform.add_button.value = 'Add Another Attachment';
} else {
document.myform.add_button.value = 'Add Attachment';
}
}
</script>
HTML...
<form name="myform" action="<your thing>" method="post" enctype="multipart/form-data" style="display:inline;">
<input id="add_button" type="button" value="Add Attachment" onclick="addFile()" />
<br /><br />
<div id="uploadControls"></div>
<br/>
<input type="submit" value="Submit" name="action">
</form>

Related

Multiple Checkbox Clear or Reset option Jquery

i want to consult issue about javascript jquery
i want this value > 20 && < 40 clear or reset option in jquery suggestion please.
It looks function error in javascript and function no clear and reset option. but function show display block wrong position .
<script>
function Checkbox() {
var length = document.tester.selection.length;
var $result = "";
var chked = 0;
for (i = 0; i < length; i++) {
if (document.tester.selection[i].checked) {
$result += document.tester.selection[i].value;
}
}
var getdata = $result;
}
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function(e) {
var selectedtext = ($(this).next().text());
if ($(this).is(':checked')) {
$("#showdatacheckbox").append('<option value="' + selectedtext + '">' + selectedtext + '</option>');
} else {
$('option[value*="' + selectedtext + '"]').remove();
}
});
function range(val) {
document.getElementById('number').value = val;
}
prefer = document.getElementById("number").value;
if (prefer > 20 && prefer < 40) {
document.getElementById("wordingprogrammer").style.display = "none";
document.getElementById("wordingsenior").style.display = "none";
} else {
document.getElementById("wordingprogrammer").style.display = "block";
document.getElementById("wordingsenior").style.display = "block";
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="tester" name="tester">
<input type="checkbox" class="iconDirector" name="selection" id="Director" value="1" onclick="Checkbox()">
<label id="wordingdirector">Director</label>
<input type="checkbox" class="iconProgrammer" name="selection" id="Programmer" value="2" onclick="Checkbox()">
<label id="wordingprogrammer">Programmer</label>
<input type="checkbox" class="iconSenior" name="selection" id="Senior" value="3" onclick="Checkbox()">
<label id="wordingsenior">Senior</label>
<input type="range" name="rangeInput" min="0" max="100" onchange="range(this.value);">
<input type="text" id="number" value="">
</form>
<a id="showdatacheckbox"></a>
function Checkbox() {
var length = document.tester.selection.length;
var $result = "";
var chked = 0;
for (i = 0; i < length; i++) {
if (document.tester.selection[i].checked) {
$result += document.tester.selection[i].value;
}
}
var getdata = $result;
}
var checked, checkedValues = new Array();
$("input[type=checkbox]").change(function (e) {
var selectedtext = ($(this).next().text());
if ($(this).is(':checked')) {
$("#showdatacheckbox").append('<option value="' + selectedtext + '">' + selectedtext + '</option>');
} else {
$('option[value*="' + selectedtext + '"]').remove();
}
});
function range(val) {
document.getElementById('number').value = val;
if (val > 20 && val < 40) {
$("input[type='checkbox']:checked").click();
}
}
prefer = document.getElementById("number").value;
if (prefer > 20 && prefer < 40) {
document.getElementById("wordingprogrammer").style.display = "none";
document.getElementById("wordingsenior").style.display = "none";
} else {
document.getElementById("wordingprogrammer").style.display = "block";
document.getElementById("wordingsenior").style.display = "block";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="tester" name="tester">
<input type="checkbox" class="iconDirector" name="selection" id="Director" value="1" onclick="Checkbox()" />
<label id="wordingdirector">Director</label>
<input type="checkbox" class="iconProgrammer" name="selection" id="Programmer" value="2" onclick="Checkbox()" />
<label id="wordingprogrammer">Programmer</label>
<input type="checkbox" class="iconSenior" name="selection" id="Senior" value="3" onclick="Checkbox()" />
<label id="wordingsenior">Senior</label>
<input type="range" name="rangeInput" min="0" max="100" onchange="range(this.value);" />
<input type="text" id="number" value="" />
</form>
<a id="showdatacheckbox"></a>

Dynamic add multi fields in javascript

I am beginner in javascript. I need to dynamic add multifields in existing form that have same id.
first fields has this name :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
And when clicking "Add another text input" I want a new fields with
<input type="text" name="myInputs[1][address]">
<input type="text" name="myInputs[1][whitelist]">
and clicking again on "Add another text input"
<input type="text" name="myInputs[2][address]">
<input type="text" name="myInputs[2][whitelist]">
When submit post only the first fields are posted :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
Here the code :
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs["+ (counter + 1) +"][address]'><input type='text' name='myInputs["+ (counter + 1) +"][whitelist]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
<div id="dynamicInput">
Entry 1<br>
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">

How to only allow 10 dynamic fields to be added javascript

I have a dynamic form that add fields dynamically. I don't know where to create the rule for "maxdynamicfields: 10,"
Here is the javascript:
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum++;
var row = '<p id="rowNum' + rowNum + '">Item quantity: <input type="text" name="qty[]" size="4" value="' + frm.add_qty.value + '"> Item name: <input type="text" name="name[]" value="' + frm.add_name.value + '"> <input type="button" value="Remove" onclick="removeRow(' + rowNum + ');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum' + rnum).remove();
}
</script>
Although you already are having a count rowNum, you could just use that in your function to check the count. Alternatively you could use something like this :
var count = $('p[id^=rowNum]').length;
if(count >= 10) {
// meaning there are atleast 10 dynamic elements created
}
You could avoid polluting global namespace with rowNum variable, and use this condition:
$('#itemRows > p > input').length >= 10
or a simple way:
rowNum >= 10
Secondly, your answer - the best place would be inside addRow function:
<script type="text/javascript">
var rowNum = 0;
function canAddRow(){
return $('#itemRows input').length >= 10 / /max row count is 10 here.
}
function addRow(frm) {
if(canAddRow())
return;
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
You can add an "if" statement to the function:
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
if (rowNum <10) {
rowNum++; //only increase rowNum up to 10
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
}
//Other functions
</script>
You can use rowNumber variable for this purpose
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
if(rowNumber == 10)
return;
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
You can define a maximum value and test for it, as follows:
<script type="text/javascript">
var rowNum = 1;
var MAX = 10;
function addRow( frm ) {
if (rowNum > MAX ) {
resetQtyName( frm );
return;
}
else
{
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'"> Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
// prepare for next invocation
resetQtyName( frm );
rowNum++;
}
}
function removeRow(rnum) {
rowNum -= 1;
jQuery('#rowNum' + rnum).remove();
}
function resetQtyName( frm ){
frm.add_qty.value = '';
frm.add_name.value = '';
}
</script>

Form field: Adding new <inputs> to the inside of a <form> via Javascript

I'm trying to add new fields via a button into my form. However, it adds it to the outside of the form. Any ideas on what to edit to accomplish this? Thanks.
My HTML:
<div id="page">
<h1>Quick Order</h1>
<div id="dynamicInput">
<form method="post" name="QuickOrderMulti">
<input type="hidden" name="formName" value="dmiformQuickOrderMulti">
<p>Product # <input type='Text' name="ProductNumber" title="Enter Product #"></p>
<p>Product # <input type='Text' name="ProductNumber" title="Enter Product #"></p>
<input type="submit" value="Add"><input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
</form>
</div>
</div> <!-- page -->
My JavaScript:
<script type="text/javascript">
var counter = 0;
var limit = 3;
function addInput(dynamicInput){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Product # " + (counter + 1) + " <br><input type='text' name='ProductNumber[]'>";
document.getElementById(dynamicInput).appendChild(newdiv);
counter++;
}
}
</script>
You're appending to the DIV surrounding the form thus the fields won't be inside the child form.
Either put the form around your "dynamicInput" div... or insert inside the form instead.
Option A:
<form method="post" name="QuickOrderMulti">
<div id="dynamicInput">
...
</div>
</form>
Option B:
<div id="dynamicInput">
<form method="post" name="QuickOrderMulti" id="QuickOrderMulti">
...
</form>
</div>
<script type="text/javascript">
...
document.getElementById('QuickOrderMulti').appendChild(newdiv);
^^^^^^^^^^^^^^^
...
</script>
You're adding the input to the div, not the form. Just give the form an id and add the input fields to that.
document.getElementById("formId").innerHTML = "Product # " + (counter + 1) + " <br><input type='text' name='ProductNumber[]'>";
Try:
<script type="text/javascript">
var counter = 0;
var limit = 3;
function addInput(dynamicInput){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var parent = document.getElementById('myform')
var element = null;
try { // IE
element = document.createElement('<input type="text" name="ProductNumber[]">');
}
catch (e) { // W3C
element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("name", "ProductNumber[]");
}
parent.appendChild("Product # " + (counter + 1) + element);
counter++;
}
}
</script>

is it possible to make accordion title navigate to a new page?

i was wondering if i can make the title of an accordion a button as well without the button feeling?
here is a picture of the accordion title and some data inside it?
i want to click on the text that is in the title to navigate to a page...
using phonegap/cordova v1.9. Visual studio 2010 express for windows phone/html,CSS,javascript (c#)
any help will be appreciated :) im open to a solution in anyway, including jquery's
title is
inboxentry1 POS556445
I have made the accordion in a bunch of div's that stacked into eachother...
tell me if i must add anything else to help with the solution!
here is some html for the accordion!
<div id="AccordionContainer" class="AccordionContainer"></div>
<div onclick="runAccordion(1)">
<div class="Accordiontitle" onselectstart="return false;">
<input type="button" href="ItemPages.html">inbox entry1</input>
<br/>
<a>POS556446x</a>
</div>
</div>
<div id="Accordion1Content" class="AccordionContent" style="background-color:white; color:grey;">
<form>
<p>
<label for="create" >Created by :</label>
<input type="text" style="margin-left:60px;" size="22" id="create"/>
</p>
<p>
<label for="createdate" >Created Date :</label>
<input type="text" style="margin-left:43px;" size="22" id="createdate"/>
</p>
<p>
<label for="process" >Process name :</label>
<input type="text" style="margin-left:36px;" size="22" id="process"/>
</p>
<p>
<label for="transtype">Transaction type :</label>
<input type="text" style="margin-left:20px;" size="22" id="transtype"/>
</p>
<p>
<label for="lastact">Last action :</label>
<input type="text" style="margin-left:61px;" size="22" id="lastact"/>
</p>
<p>
<label for="lastuser">Last user :</label>
<input type="text" style="margin-left:73px;" size="22" id="lastuser"/>
</p>
<p>
<label for="lastupd">Last update :</label>
<input type="text" style="margin-left:55px;" size="22" id="lastupd"/>
</p>
<p>
<label for="duration">Duration :</label>
<input type="text" style="margin-left:78px;" size="22" id="duration"/>
</p>
<p>
<label for="saved">Saved :</label>
<input type="text" style="margin-left:93px;" size="22" id="saved"/>
</p>
<p>
<label for="adhoc">Ad hoc user :</label>
<input type="text" style="margin-left:53px;" size="22" id="adhoc"/>
</p>
</form>
</div>
here is my .js file
var ContentHeight = 200;
var TimeToSlide = 250.0;
var openAccordion = '';
function runAccordion(index) {
var nID = "Accordion" + index + "Content";
if (openAccordion == nID)
nID = '';
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
openAccordion = nID;
}
function animate(lastTick, timeLeft, closingId, openingId) {
var curTick = new Date().getTime();
var elapsedTicks = curTick - lastTick;
var opening = (openingId == '') ? null : document.getElementById(openingId);
var closing = (closingId == '') ? null : document.getElementById(closingId);
if (timeLeft <= elapsedTicks) {
if (opening != null)
opening.style.height = ContentHeight + 'px';
if (closing != null) {
closing.style.display = 'none';
closing.style.height = '0px';
}
return;
}
timeLeft -= elapsedTicks;
var newClosedHeight = Math.round((timeLeft / TimeToSlide) * ContentHeight);
if (opening != null) {
if (opening.style.display != 'block')
opening.style.display = 'block';
opening.style.height = (ContentHeight - newClosedHeight) + 'px';
}
if (closing != null)
closing.style.height = newClosedHeight + 'px';
setTimeout("animate(" + curTick + "," + timeLeft + ",'" + closingId + "','" + openingId + "')", 33);
}
You probably want to make some changes here. A few classes have been added and the button tag changed as it wasn't correct. Your want to remove the inline event you have for the accordion and stick it where commmented below.
<div class="AccordionRun">
<div class="Accordiontitle" onselectstart="return false;">
<input class="AccordionLink" type="button" href="ItemPages.html" value="inbox entry1">
<br/>
<a>POS556446x</a>
</div>
</div>
Then you can get it and add a click event to it...
var goToPage = function(elem) {
elem.onclick = function() {
alert('Go to page...');
window.location = elem.href;
};
};
var runAccordion = function(elem) {
elem.onclick = function() {
alert('Run Accordion...');
// Your accordion code goes here...
};
};
var buttons = document.getElementsByTagName('input');
for(var i=0; i < buttons.length; i++) {
if (buttons[i].className == 'AccordionLink') {
goToPage(buttons[i]);
}
}
var divs = document.getElementsByTagName('div');
for(var i=0; i < divs.length; i++) {
if (divs[i].className == 'AccordionRun') {
runAccordion(divs[i]);
}
}
jsfiddle.net/FKt4K/2
If you'd like to navigate to an other page on click of an input field, here's a simpe work-around.. Just bind it to a mouseup-event like so (needs a jQuery implemention):
UPDATED CODE
HTML:
<input class="followThisRel" type="button" rel="http://yoursite.com/">
JS:
$(function() {
$('input.followThisRel').on('click', function() {
var url = $(this).attr('rel');
window.location = url;
});
})

Categories

Resources