html – Use javascript to alter submit link – Education Career Blog

ok so i have a script that when you click a link it dynamicly adds a form field is it possible to make it so when it is submitted it goes to “example.com?7” (7 because of 7 files)
what i mean is if i click it 5 times and there are 5 file fields and i choose 5 files can i make the action link mysite.php?5

here is the script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="application/javascript">

function add(){
var field = document.createElement('input');
field.setAttribute("type", "file");
field.setAttribute("name", "yo");
document.getElementById('myform').appendChild(field);
}

</script>
</head>

<body>
<form id="myform" name="form1" enctype="multipart/form-data" method="post" action="">
  <p>File:
  <input type="file" name="hello" id="hello" />
  </p>
  <p>
    <input name="submit" type="submit" value="Submit" />
  </p>
</form>

<a href="#" onclick="add()">Click Here</a>
</body>
</html>

Thanks a lot!

,

I suggest giving the new added fields class = “classX” and when you submit the form count the no of elements with the specified class with getElementsByClassName

I find it simpler than incrementing a value each time a field is added

,

I would keep it simple and keep track of how many file fields you have added. Just update the url every time you add a new file field.

var numFileElements = 1; 
function add(){
  var field = document.createElement('input');
  field.setAttribute("type", "file");
  field.setAttribute("name", "yo");
  var myForm = document.getElementById('myform');
  myForm.appendChild(field);
  ++numFileElements;
  myForm.setAttribute('action', '?'+ numFileElements);
}

,

Just keep an extra hidden field in the form (call it “count”), and have the script increment its value whenever it adds another file input.

,

Something like?

function doSubmit() {
    var myForm = document.getElementById('myForm'); //Get myForm
    var childNodes = myForm.childNodes; //Count child nodes
    var fields = 0;
    for ( var node in childNodes ) {
        if ( childNodesnode.tagName == 'P' ) fields++;
    }
    myForm.setAttribute('action', 'mysite.php?'+fields);
}

It counts all P elements directly below myForm. Not perfect, but it ought to work! Just add an onsubmit='doSubmit();

Leave a Comment