Form redirect on checkbox selection - javascript

Here's what i'm trying to achieve: I want to create a HTML page with a form, when you submit the form it goes to 1 of 4 locations. There is a default hidden main option thats auto-selected on page load and 2 sub-options that are optional.
Oh, and it calculates the amounts on selection!
Here's my code so far:
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input id="myCheckbox1" name="myCheckbox1" type="checkbox" value="20" onClick="calcNow();" />Default option<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="30" onClick="calcNow();" />Add-on option 1<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="40" onClick="calcNow();" />Add-on option 2<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html"],["http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox1");
var cb = document.getElementById("myCheckbox2");
var cost1 = cb.checked ? parseInt(cb.value) : 0;
var cost2 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2;
document.getElementById("myTotal").value = costTotal;
var op1 = cb.checked ? 1 : 0;
if (op1 != undefined)
{
return pages[op1];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
alert(page);
// ---- To navigate ----
//location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>

Try this
EDIT:
function submitForm()
{
//The code goes inside here, you have to decide where to redirect from if or the else
window.location.assign("http://www.w3schools.com/");
var page = calcNow();
if (page != undefined)
{
alert(page);
}
else
{
alert("Please answer all questions.");
}
}

Related

Javascript form clears instantly and flashes one answer

I have an html page that uses a javascript as a statistical calculator, it just needs to print the results into the text boxes i have displayed, but when i hit my submit button, the screen displays the mean value for a split second. no other fields work or stay.
My html file is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<script src="script.js"></script>
<title>Script Calculator</title>
</head>
<body class="calculator">
<h2 class="stats">Statistical Calculator</h2>
<p> Enter 5-20 values within 0-100 inside the box below.<br>
Each value should be separated by one space.
</p>
<form>
<textarea id="numbers" name="numberarea" rows="4" cols="40"></textarea> <br>
<br>
<input type="submit" id="subbutton" onclick="performStatistics()"
value="Submit">
<input type="reset">
<br><br>
Max: <input type="text" id ="maxnum" name="max" readonly>
<br>
Min: <input type="text" id="minnum" name="min" readonly>
<br>
Mean: <input type="text" id="meannum" name="mean" readonly>
<br>
Median: <input type="text" id="mednum" name="med" readonly>
<br>
Mode: <input type="text" id="modenum" name="mode" readonly>
<br>
Standard Deviation: <input type="text" id="stddev" name="std" readonly>
<br>
Sum: <input type="text" id="sumnum" name="sum" readonly>
<br>
Variance: <input type="text" id="varinum" name="vari" readonly>
<br>
</form>
<hr>
ePortfolio
</body>
</html>
My javascript is as follows:
function performStatistics() {
var newarray = document.getElementById("numbers").value;
var array = newarray.split(" ");
for (var i = 0; i < array.length; i++) {
if (array[i] < 0 || array[i] > 100) {
alert("Enter positive values from 0-100")
return false;
}
}
if (array.length < 5 || array.length > 20) {
alert("Enter at least 5 values & no more than 20");
return false;
}
document.getElementById("meannum").value = calcMean(array);
document.getElementById("mednum").value = calcMedian(array);
document.getElementById("modenum").value = calcMode(array);
document.getElementById("stddev").value = calcStdDev(array);
document.getElementById("sumnum").value = calcSum(array);
document.getElementById("varinum").value = calcVariance(array);
document.getElementById("maxnum").value = findMax(array);
document.getElementById("minnum").value = findMin(array);
return false;
}
function calcMean(array) {
return calcSum(array) / array.length;
}
function calcMedian(array) {
var med = 0;
var arraylen = array.length;
arraylen.sort();
if (arraylen % 2 === 0) {
med = (array[arraylen / 2 - 1] + array[arraylen / 2]) / 2;
//takes average of an even array
} else {
med = array[(arraylen - 1) / 2];
//takes middle value of odd array
}
return med;
}
function calcMode(array) {
var mode = [];
var counter = [];
var i;
var holder;
var maxfreq = 0;
for (i = 0; i < array.length; i += 1) {
holder = array[i];
counter[array] = (counter[holder] || 0) + 1
if (counter[holder] > maxfreq) {
maxfreq = counter[holder];
}
}
for (i in counter)
if (counter.hasOwnProperty(i)) {
//returns boolean value^
if (counter[i] === maxfreq) {
mode.push(Number(i));
//pushes value into (end of) array
}
}
return mode;
}
function calcStdDev(array) {
return Math.sqrt(calcVariance(array)).toFixed(2);
}
function calcSum(array) {
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum += Number(array[i]);
}
return sum.toFixed(2);
}
function calcVariance(array) {
var avg = calcMean(array);
var newarray = [];
var vari;
for (i = 0; i < array.length; i++) {
newarray[i] = (array[i] - avg) * (array[i] - avg);
}
vari = calcSum(newarray) / newarray.length;
return vari.toFixed(2);
}
function findMax(array) {
var newarray = array;
var maxnum = Math.max(newarray);
return maxnum;
}
function findMin(array) {
var newarray = array;
var minnum = Math.min(newarray)
return minnum;
}
You need to prevent the submit button from submitting the form.
window.onload=function(){
document.getElementById('subbutton').addEventListener('click', function(ev){
ev.preventDefault(); // prevent the page submit
});
}
You can remove the onclick from the HTML, and add this to your script:
// When the DOM (HTML) is ready
addEventListener('DOMContentLoaded', function() {
// When the form gets submitted (click on submit or enter key)
document.forms[0].addEventListener('submit', function (event) {
performStatistics();
// Prevent the form from refreshing the page
event.preventDefault();
});
});
Note: your script is included in the <head> of your document. Waiting for DOMContentLoaded will ensure the document is ready no matter where your script is called. But you could skip that part if you include your script at the very bottom, before the closing </body> tag.

Maintain visibility of a form-textinput when checkbox is checked

In my HTML I have a form, where a user can select the checkbox "other" and a textbox appears. Otherwise the textbox is hidden. Below you can find my code. But if the user selects "other", types in his text und submits the form, the textbox is hidden again-although the checkbox maintain checked (saved in localStorage). I cannot find my mistake here.
Form:
<label class="form-check">
<input class="form-check-input" name="filetype" type="checkbox" id="other" value="" onclick="save()">
<span class="form-check-label"
<input placeholder="e.g. 'msg'" name="other" onsubmit="save();" class="form-control input-lg" type="text" id="otherValue" value="{{extension}}">
</span>
</label> <!-- form-check -->
Visible/Hidden
<!--"Other"-filter-->
<script type="text/javascript">
var otherCheckbox = document.querySelector('input[id="other"]');
var otherText = document.querySelector('input[id="otherValue"]');
otherText.style.visibility = 'hidden';
otherCheckbox.onchange = function(){
if(otherCheckbox.checked) {
otherText.style.visibility = 'visible';
otherCheckbox.value = otherText.value;
save();
} else {
otherText.style.visibility = 'hidden';
}
};
</script>
Tried to solve this Problem by saving the info in the sessionStorage but it still does not work.
<!--Save Checkbox-State-->
<script type="text/javascript">
const checkboxen = [...document.querySelectorAll("[type=checkbox]")].map(inp => inp.id); //list of all checkbox-IDs
function save(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checkbox = document.getElementById(id);
sessionStorage.setItem(id,checkbox.checked);
}
var other = document.getElementById('otherValue');
sessionStorage.setItem('otherValue',other.style.visibility);
}
function load(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checked =JSON.parse(sessionStorage.getItem(id));
document.getElementById(id).checked = checked;
}
var other = JSON.parse(sessionStorage.getItem('otherValue'));
document.getElementById('otherValue').style.visibility = other;
}
function deleteCheckbox(){
sessionStorage.clear();
}
</script>
Thanks for any help <3
with prop jquery:
<script>
$(function(){
var other = localStorage.input === 'true'? true: false;
$('input').prop('checked', other);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
this is my solution:
<script type="text/javascript">
var other = document.getElementById('other');
var otherText =document.querySelector('input[id="otherValue"]');
$(document).ready(function(){
if (other.checked){
otherText.style.visibility = 'visible';
otherText.value = "{{extension}}";
other.value = "{{extension}}";
} else {
otherText.style.visibility = 'hidden';
otherText.value = "";
}
});

How to create a link from button values for woocommerce order

I have to generate a add to cart link for a page from value inputed by our customer. For example, the customer wants to order 3 products from our site www.example.com, so the code generates a link to add these 3 product to cart on page www.example2.com/?add-to-cart=25&quantity=3″.
Any ideas? I would be very grateful.
Here is the qet quantity code which works like a charm.
<button class="plus" onclick="buttonClickUP();">+</button>
<input type="text" id="gumb2" value="1"></input>
<button class="plus" onclick="buttonClickDOWN();">-</button>
<input type="text" id="order" value="ORDER NOW"></input>
<script>
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
var i = 0;
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if(el.value == 1) return false;
el.value = Number(el.value) - 1;
}
</script>
Here is a code sample which I wrote for you which does the job:
JSBIN Snippet Link: https://jsbin.com/guborazuqu
function spremembax() {
document.getElementById("gumb2").value = "2";
}
function spremembay() {
document.getElementById("gumb2").value = "3";
}
var i = 0;
function buttonClickUP() {
var el = document.getElementById('gumb2');
el.value = Number(el.value) + 1;
}
var i = 0;
function buttonClickDOWN() {
var el = document.getElementById('gumb2');
if (el.value == 1) return false;
el.value = Number(el.value) - 1;
}
function generateAddToCartLink() {
var productID = document.getElementById('productID').value;
var quantity = document.getElementById('gumb2').value;
var generatedLink = `${location.protocol}//${location.hostname}/?add-to-cart=${productID}&quantity=${quantity}`;
window.location.href = generatedLink;
}
<button class="plus" onclick="buttonClickUP();">+</button>
<input id="productID" type="text" value="25">
<input id="gumb2" type="text" value="1">
<button class="plus" onclick="buttonClickDOWN();">-</button>
<button id="order" onclick="generateAddToCartLink()">ORDER NOW</button>

Delete row dynamically in JavaScript

I'm doing a form (a simple WEB form, based on the scripts from Tom Negrino, JavaScript 8, and w3Schools) where the user press the Submit button and some of the fields from the form are displayed in one table under the form.
This is the result
Form
Now, I want to delete the row , but only the row that the user wants to delete clicking on the corresponding row.
This is my JavaScript
window.onload = initForms;
function initForms() {
for (var i=0; i< document.forms.length; i++) {
document.forms[i].onsubmit = validForm;
}
document.getElementById("sunroof").onclick = doorSet;
document.getElementById("estado").selectedIndex = 0;
document.getElementById("estado").onchange = populateDays;
/***********/
//document.getElementsByTagName("form")[0].onsubmit = addNode;
/***********/
document.getElementById("env").onclick = function() {
myFunction()
};
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i=0; i<allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for (var j=0; j<allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
invalidLabel(thisTag.parentNode);
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch(thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "radio":
if (allGood && !radioPicked(thisTag.name)) {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "email":
if (allGood && !validEmail(thisTag.value)) classBack = "invalid ";
break;
case "isNum":
case "isZip":
classBack += thisClass;
break;
default:
if (allGood && !crossCheck(thisTag,thisClass)) {
classBack = "invalid ";
}
classBack += thisClass;
}
return classBack;
}
function crossCheck(inTag,otherFieldID) {
if (!document.getElementById(otherFieldID)) {
return false;
}
return (inTag.value != "" || document.getElementById(otherFieldID).value != "");
}
function validEmail(email) {
var re = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
return re.test(email);
}
function radioPicked(radioName) {
var radioSet = "";
for (var k=0; k<document.forms.length; k++) {
if (!radioSet) {
radioSet = document.forms[k][radioName];
}
}
if (!radioSet) {
return false;
}
for (k=0; k<radioSet.length; k++) {
if (radioSet[k].checked) {
return true;
}
}
return false;
}
/****Veamos si esto funciona****/
/*function checkboxPicked(checkboxName) {
var checkboxSet = "";
for (var k = 0; k < document.forms.length; k++) {
if (!checkboxSet) {
checkboxSet = document.forms[k][checkboxName];
}
}
if (!checkboxSet) {
return false;
}
for ( k = 0; k < checkboxSet.length; k++) {
if (checkboxSet[k].checked) {
return true;
}
}
return false;
}*/
/*****************************************/
function invalidLabel(parentTag) {
if (parentTag.nodeName == "LABEL") {
parentTag.className += " invalid";
}
}
}
}
function populateDays() {
var tamps = new Array("Ikon Hatch", "Fiesta", "Focus", "Mustang");
var nvoleon = new Array("Aveo", "Spark");
var slp = new Array("Gol", "CrossFox", "Clasico", "Jetta");
var estado = document.getElementById("estado");
var estadoStr = estado.options[estado.selectedIndex].value;
if (estadoStr != "") {
var valueEst = parseInt(estadoStr);
document.getElementById("ciudad").options.length = 0;
if (valueEst == 0) {
for (var i = 0; i < tamps.length; i++) {
document.getElementById("ciudad").options[i] = new Option(tamps[i]);
}
} else if (valueEst == 1) {
for (var i = 0; i < nvoleon.length; i++) {
document.getElementById("ciudad").options[i] = new Option(nvoleon[i]);
}
} else if (valueEst == 2) {
for (var i = 0; i < slp.length; i++) {
document.getElementById("ciudad").options[i] = new Option(slp[i]);
}
}
} else {
document.getElementById("ciudad").options.length = 0;
document.getElementById("ciudad").options[0] = new Option("Model");
}
}
function doorSet() {
if (this.checked) {
document.getElementById("twoDoor").checked = true;
}
}
/*****************************/
/*function addNode() {
var inText = document.getElementById("estado").value;
var inText1 = document.getElementById("ciudad").value;
var newText = document.createTextNode(inText);
var newText1 = document.createTextNode(inText1);
var newGraf = document.createElement("table");
newGraf.appendChild(newText);
newGraf.appendChild(newText1);
var docBody = document.getElementsByTagName("body")[0];
docBody.appendChild(newGraf);
return false;
}*/
function myFunction() {
var table = document.getElementById("myTable");
var email= document.getElementById("emailAddr").value;
var brand=document.getElementById("estado").value;
var model=document.getElementById("ciudad").value;
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = email;
cell2.innerHTML = model;
cell3.innerHTML = brand;
}
And my HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Formulario</title>
<link rel="stylesheet" href="css/script06.css">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">
<!--No se te olvide el css-->
<!--<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-3.2.0-dist/css/bootstrap-theme.min.css">-->
<script src="js/script08.js"></script>
<!--No se te olvide el js-->
</head>
<body>
<header></header>
<main>
<article>
<p>
<h1>Choose your car</h1>
</p>
</article>
<form action="#">
<p>
<label for="emailAddr">Email Address:
<input id="emailAddr" type="text" size="40" class="reqd email">
</label>
</p>
<p>
<label for="passwd1">Password:
<input type="password" id="passwd1" class="reqd">
</label>
</p>
<p>
<label for="passwd2">Repeat Pass:
<input type="password" id="passwd2" class="reqd passwd1">
</label>
</p>
<!--<p>
<label for="color">Colors:
<select id="color" class="reqd">
<option value="" selected>Choose a color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select> </label>
</p>-->
<p>
Options: <label for="sunroof">
<input type="checkbox" id="sunroof" value="Yes">
Sunroof (Two door only)</label>
<label for="pWindows">
<input type="checkbox" id="pWindows" value="Yes">
Power Windows</label>
</p>
<p>
Doors: <label for="DoorCt"><!--Doors: -->
<input type="radio" id="twoDoor" name="DoorCt" value="twoDoor" class="radio">
Two</label>
<label for="DoorCt">
<input type="radio" id="fourDoor" name="DoorCt" value="fourDoor" class="radio">
Four </label>
</p>
<p>
<label>Brand:</label>
<select id="estado" class="reqd">
<option value="">Brand</option>
<option value="0">Ford</option>
<option value="1">Chevrolet</option>
<option value="2">Volkswagen</option>
</select>
<select id="ciudad" class="reqd">
<option>Model</option>
</select>
</p>
<p>
<input type="submit" value="Enviar" id="env">
<input type="reset">
</p>
</form>
<br />
<!--Veamos si funciona-->
<table id="myTable">
<tr>
<td>Email</td>
<td>Model</td>
<td>ID Brand</td>
</tr>
<tr>
</tr>
</table>
</main>
<footer></footer>
</body>
</html>
I tried adding and extra cell in the JavaScript:
cell4.innerHTML = <button onclick="myDeleteFunction()">Del</button>;
where calls the function
function myDeleteFunction() {
document.getElementById("myTable").deleteRow();
}
to delete to row, but it didn't work.
I'll appreciate any help. Thanks.
var node = nodes[0];
if (univArray[z].ownership != "public") {
node.parentNode.removeChild(node)
}
If you want to delete a table row based on a click on the row, you can use something like:
<tr onclick="this.parentNode.removeChild(this)">
If you want to do that based on a button in the row, then:
<tr>
<td><button onclick="deleteRow(this)">Delete this row</button>
Then the deleteRow function is:
function deleteRow(element) {
var row = upTo(element, 'tr');
if (row) row.parentNode.removeChild(row);
}
A helper function
// Return first ancestor of el with tagName
// or undefined if not found
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
// Many DOM methods return null if they don't
// find the element they are searching for
// It would be OK to omit the following and just
// return undefined
return null;
}
The deleteRow function can be put anywhere inside a row, and the row can be in any type of table section element (head, body or foot). All you need to do is to pass a reference to any element inside the row (button, checkbox, cell, whatever).
The trouble with the table.deleteRow method is that you have to know the row index in the element that you're calling the method on. Rows have a rowIndex property that is their index in the table they are in, so you have to go up to the table to use that (i.e. row.parentNode.parentNode), whereas using the removeChild method doesn't require you to work out where in the table the row is, or to even know whether the parent is a head, body or foot section.
Edit
To add the listener dynamically, you can slightly modify the function and add a class to the buttons that will delete rows, e.g.
<!-- Sample markup -->
<table>
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
<tr>
<td><input type="button" class="rowDeleter" value="Delete Row">
</table>
Adding a class means you can easily identify the elements to add the listener to.
<script>
window.onload = function() {
// querySelectorAll and addEventListener require IE 8 or higher, use some other
// method if support for older browsers is required
var els = document.querySelectorAll('.rowDeleter');
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].addEventListener('click', deleteRow, false);
}
}
// When attached using addEventListener, this in the function
// will be the element that called the listener
function deleteRow() {
var row = upTo(this, 'tr');
if (row) row.parentNode.removeChild(row);
}
// Previously shown helper
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
return null;
}
</script>

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources