Dynamic html form elements as array - html

I have a dynamic section in my html form. When clicking on a button, user can add a tag name and tag type. At a point, imagine that there are 3 set of tag names and tag types, the data should be submitted in the following format.
Array[0][name] = tag1 name, Array[0][type] = tag1 type
Array[1][name] = tag2 name, Array[1][type] = tag2 type
Array[2][name] = tag3 name, Array[2][type] = tag3 type
Can someone help me on this ?

I think you are looking to have a multidimensional array that can store an array within each position of the array. Assuming you have already a form, html should look something like this:
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
For the functionality, you could have something like this to store the information and then submit the form:
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
You can check in the console in the developer tools for the information you are about to submit.
Let me know if this helps,
Leo.
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>

here is another possibility for how to make this work. a simple form with a div to contain the tags and a small input field to add a new tag.
var tagid = 1;
function addTag() {
var div = document.getElementById("tags");
var name = document.getElementById("tname").value;
var type = document.getElementById("ttype").value;
div.innerHTML += "tag" + tagid + "<br><input type='text' name='tag[" + tagid + "][name]' value='" + name + "'><br><input type='text' name='tag[" + tagid + "][type]' value='" + type + "'><hr>";
tagid++;
}
<html>
<body>
<form id="form">
tags:<br>
<div id="tags">
</div>
<input type="submit" value="Submit">
</form>
<hr> tag name: <input id="tname" type="text" name="tname"><br> tag type: <input id="ttype" type="text" name="ttype"><br>
<button onclick="addTag()">add tag</button>
</body>
</html>

Related

Using javascript to create a for loop which loops over text fields, and concatenates the input, and has an add input button

This program has 6 text fields and when a user inputs into the text fields, the text result box will concatenate the input text. I am struggling to get a button to work which will add a 7th text field and then also add the user input together. I have tried to append it but not sure where I am going wrong.
<html>
<body>
<form>
<div class="textFields">
<label for="text1">text1:</label><br>
<input type="text" class="text" name="text1"><br>
<label for="text2">text2:</label><br>
<input type="text" class="text" name="text2"><br>
<label for="text3">text3:</label><br>
<input type="text" class="text" name="text3"><br>
<label for="text4">text4:</label><br>
<input type="text" class="text" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" class="text" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" class="text" name="text6"><br>
<input type="button" name="button" value="Get"><br>
<input type="button" name="button" value="Add">
<br>
<label for="textResult">Text Result</label><br>
<input type="text" id="textResult" name="textResult"><br>
</div>
</form>
<script>
let x = document.querySelectorAll('.textFields .text');
let button = document.querySelector('.textFields input[type="button"]');
let result = document.querySelector('#textResult');
button.onclick = function() {
result.value = '';
for (i = 0; i < x.length; i++) {
result.value += x[i].value + ' ';
}
}
button.onclick = function() {
var textField = document.createElement("INPUT")
textField.setAttribute("id", id)
textField.setAttribute("name", id)
textField.classList.add("textInput")
container.appendChild(textField)
}
</script>
</body>
</html>
When you run this in a browser, the following error is reported in the console when you click the Get button:
Uncaught ReferenceError: id is not defined
at HTMLInputElement.button.onclick (test.html:53)
Ignore the error for now, you can see that the error in actually in the second function, but for Get you were probably expecting the first funtion. To fix this issue, do not assign the second function, at least not to the button you have selected.
Notice how you have named both buttons the same name, this will make them hard to target, but also you are not using that name in the querySelector. So lets change that first, give each button a unique name and use it to select each button:
<input type="button" name="getButton" value="Get"><br>
<input type="button" name="addButton" value="Add">
let getButton = document.querySelector('.textFields input[name="getButton"]');
let addButton = document.querySelector('.textFields input[name="addButton"]');
...
getButton.onclick = ...
...
addButton.onclick = ...
Now, when you click on the Get button there is no error, and it appears to function as you have described, clicking Add still raises the original error.
You have used a variable called id but you have not yet declared what that variable is yet. I would assume you probably want to make it 'textX' where x is the next number.
So add the following lines inside the button click function to declare the Id:
You need to put this logic inside the function because you need it to be re-evaluated each time the button is clicked. Other valid solutions would include incrementing the value instead or re-querying for x, but this will work.
let x = document.querySelectorAll('.textFields .text');
let id = 'text' + (x.length + 1);
Save and Run, you will see the next issue in the console:
Uncaught ReferenceError: container is not defined
at HTMLInputElement.addButton.onclick
As with id, you have not defined the variable container, here I will again assume you meant to reference the .textFields div, so following your querySelector style, we can create a variable called container:
let container = document.querySelector('.textFields');
That will start appending your text boxes to the page, but they are still not being picked up by the Get button.
Another assumption here, but you have assigned a class .textResult to the new texboxes. If instead you assigned the class .text to them, then you would almost pick them up in the selector
textField.classList.add("text");
The reason that they aren't picked up is back to where the value of x is evaluated that the Get button is using. Because it is evaluated the first time in the main script, but never re-evaluated when the button is clicked the new text boxes are not included in the array stored in x.
As with the advice above for requerying x to get the updated count, Simply fix this by moving the line to initialise x into the first function.
Overall, your page with the embedded script could not look something like this:
<html>
<body>
<form>
<div class="textFields">
<label for="text1">text1:</label><br>
<input type="text" class="text" name="text1"><br>
<label for="text2">text2:</label><br>
<input type="text" class="text" name="text2"><br>
<label for="text3">text3:</label><br>
<input type="text" class="text" name="text3"><br>
<label for="text4">text4:</label><br>
<input type="text" class="text" name="text4"><br>
<label for="text5">text5</label><br>
<input type="text" class="text" name="text5"><br>
<label for="text6">text6</label><br>
<input type="text" class="text" name="text6"><br>
<input type="button" name="getButton" value="Get"><br>
<input type="button" name="addButton" value="Add">
<br>
<label for="textResult">Text Result</label><br>
<input type="text" id="textResult" name="textResult"><br>
</div>
</form>
<script>
let getButton = document.querySelector('.textFields input[name="getButton"]');
let addButton = document.querySelector('.textFields input[name="addButton"]');
let result = document.querySelector('#textResult');
let container = document.querySelector('.textFields');
getButton.onclick = function() {
let x = document.querySelectorAll('.textFields .text');
result.value = '';
for (i = 0; i < x.length; i++) {
result.value += x[i].value + ' ';
}
}
addButton.onclick = function() {
let x = document.querySelectorAll('.textFields .text');
var textField = document.createElement("INPUT")
let id = 'text' + (x.length + 1);
textField.setAttribute("id", id)
textField.setAttribute("name", id)
textField.classList.add("text")
container.appendChild(textField)
}
</script>
</body>
</html>
Have a look at some of the guidance in this post for further simple examples: How do I add textboxes dynamically in Javascript?

HTML - Button on click display value of textfield

I use a textfield with code:
<input type = "text" size = "2" maxlength = "2" name = "myname">
and a button with:
<button type = "button" onclick = "alert('Clicked!')">Print</button>
Now, as I click on it, a message/alert pops saying Clicked!. How can I make it just display whatever value was on the textfield instead? Ty
Try this solution:
<input type="text" id="test" size="2" maxlength="2" name="myname">
<button type="button" onclick="alert(document.getElementById('test').value);">Print</button>
A working example you can find here: http://jsfiddle.net/sebastianbrosch/x8zzvd5s/
Explanation
You have to add a id to your textfield (here test). On the alert() you can get the value of the textfield with document.getElementById('test').value.
if you are doing this to print a person's name or something using PHP then it should be like this:
add this in your body of html:
<form name="form1" action="registration.php" method="POST" onsubmit="myFunction()" >
<input type="text" name="name" id="name">
<input type="submit" value="submit">
</form>
you can validate this field using javascript on submit as:(write this in head tag of html)
<script>
var name=document.getElementById("name").value;
myFunction()
{
if(name!="")
{
return true;
}
else
{
//show alert.
return false;
}
}
</script>
In PHP you can print the name user entered in the text by(reg.php):
<?php
$name=$_POST['name'];//it is the name of the control field
echo $name;
?>

Add form information in to URL string and submit

I need to get information from my online form added in to my URL string and get it submitted to the dialler.
I have a working URL string that submits data to our dialler ok.
I need to get the first name, last name and phone number from the form submission in to the URL string.
This is how the URL string looks;
http://domain.com/scripts/api.php?user=admin&pass=password&function=add_lead&source=MobileOp&phone_number=07000000000&phone_code=44&list_id=3002&first_name=NAME&last_name=SURNAME&rank=99&campaign_id=campaign&callback=Y&callback_datetime=NOW
This is the form I have;
<form id="contact_form" method="post" action="">
<div class="contactform">
<fieldset class="large-12 columns">
<div class="required">
<label>Your First Name:*</label>
<input name="first_name" type="text" class="cms_textfield" id="first_name" value="" size="25" maxlength="80" required="required" />
</div>
<div class="required">
<label>You Last Name:*</label>
<input name="last_name" type="text" class="cms_textfield" id="last_name" value="" size="25" maxlength="80" required="required" />
</div>
<div class="required">
<label>Phone Number:*</label>
<input name="phone_number" type:"number" id="phone_number" size="25" maxlength="11" required="required"></input>
</div>
</fieldset>
<p class="right"><strong>Call us now on 01656 837180</strong></p>
<div class="submit"><input type="submit" value="Submit" class="button small radius"></div>
</div>
</form>
I am struggling to get anywhere with this. I have a basic knowledge of PHP.
If you change your form to method="GET" and the action to your url action="http://domain.com/scripts/api.php" it will include it in the URL string. That said, showing a user's password as a query string variable is probably a bad idea in the long run.
Instead, you can process the input from the form in PHP by referring to the $_POST array in your code. For example, to get the first name you'd just use $_POST['first_name']
Change
<form id="contact_form" method="post" action="">
to
<form id="contact_form" method="GET" action="">
(notice the method 'GET'). GET sends form variables through the URL.
You can use PHP for this.
if you have an input field of name attribue 'first_name', It'll be stored in the variable $_POST['first_name'] in case of POST as method and $_GET['first_name'] in case of GET method
If you have a url
http://domain.com/scripts/api.php?user=admin&pass=password&function=add_lead&source=MobileOp&phone_number=07000000000&phone_code=44&list_id=3002&first_name=NAME&last_name=SURNAME&rank=99&campaign_id=campaign&callback=Y&callback_datetime=NOW,
notice the x=y pattern repeating in it, like user=admin. Here, the first element, x becomes the key to tha PHP array and the second becomes the value.
You can use this function. on your submission page
<script type="text/javascript">
function iter() {
var str = "";
$("#contact_form .contactform .required :input").each(function () { // Iterate over inputs
if ($(this).attr('id')) {
str += $(this).attr('id') + "=" + $(this).val() + "&"; // Add each to features object
}
});
str = str.substring(0, str.length - 1);
$.ajax({
type: "GET",
url: "http://domain.com/scripts/api.php",
data: str,
async: true,
error: function (error) {
},
success: function (data) {
}
});
}
</script>
just attach it to the submit button as shown below
$("#contact_form .submit").on("click", function () {
iter();
return false;
});

Form value creates a URL

I am trying to create a very simple form with a little bit of extra code to get the results as described below: the problem is I don't know how to go about doing it.
What I am trying to achieve:
I have a form which has one text input box with the name 'url'. I want the user to be able to input a number into the box. When the user submits the form they should be redirected to a new website. The new website's URL will be based on the number inputted into the form.
The first part of the URL will always be: http://name.com/
Then the number that the user inputted will be attached to the end. So if 123456 is entered into the form then on submission of the form the user would be taken to http://name.com/123456
How can I get this working? I am guessing it will require JavaScript or something.
<script>
function process()
{
var url = "http://name.com/" + document.getElementById("url").value;
location.href = url;
return false;
}
</script>
<form onSubmit="return process();">
URL: <input type="text" name="url" id="url">
<input type="submit" value="go">
</form>
You can add onsubmit="this.action='http://google.com/'+this.fieldName.value;" to your tag.
This should do it:
<script type="text/javascript">
function goToPage() {
var page = document.getElementById('page').value;
window.location = "http://name.com/" + page;
}
</script>
<input type="text" id="page" />
<input type="submit" value="submit" onclick="goToPage();" />

Dynamic HTML Form Entry

Is it possible to make an HTML form that responds to the number of things the user wants to send over?
That is, what I have now is:
<form ...>
<select ...>
<option>1</option>
<option>2</option>
...
</select>
***
</form>
When the user selects one of the options, *** should have
<input type="text" ...>
appear the number of times the user selected.
That is, if the user selected 5 from the options, then the user should see 5 input options. If he changes his mind selected 2 instead, then the page should update accordingly to show only 2 input options.
=====[EDIT]=====
I've changed the code to have the input just be text. The code I have does not work. It doesn't update the number of input fields.
<script type="text/javascript">
<!--
function updateOptions(nvars)
{
var n = nvars;
while(n>0) {
var newdiv1 = "<div>Var name: <input type=\"text\" name=\"var-name\"><br></div>";
var newdiv2 = "<div>Var type: <input type=\"text\" name=\"var-type\"><br></div>";
newdiv1.appendTo("#bloo");
newdiv2.appendTo("#bloo");
n--;
}
}
//-->
</script>
<h3>Create a table in the test db!<h3>
<form name="f1" method="POST" action="createTable.php">
Name of Table: <input type="text" name="table-name"><br>
No of vars: <input type="text" name="numvars" onChange="updateOptions(this.value)"><br>
<div id="bloo"></div>
</form>
It worked when I had a document.write instead of an appendTo, but I essentially want the page the remain the same save for the extra input fields after the user changes the value in the numvars field.
That's a good idea when you want the user to be able to upload an arbitrary number of files or something like that. You can do it with Javascript:
Have an empty DIV near the SELECT
Bind a function to the "onchange" event on the select element
In the function, read the value of the SELECT element and:
Empty the DIV
Create an equivalent number of <INPUT type="text"> inside the DIV
Do you need code? If you do, is Prototype OK?
OK, sorry for the delay, lots of work to do lately.
The following should be enough for you to get an idea. You'll have to study JS though, I don't even know what you're doing with the appendTo stuff in your question.
<html>
<head>
</head>
<body>
<form>
<select id="num" value="1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<div id="container">
<p>
<input type="text" name="var-name" />
<input type="text" name="var-type" />
</p>
</div>
</form>
<script type="text/javascript">
var selectElm = document.getElementById('num');
var containerElm = document.getElementById('container');
var update = function () {
containerElm.innerHTML = '';
for (var i = 0, l = selectElm.value; i < l; ++i) {
containerElm.innerHTML += '<p><input type="text" name="var-name" /><br /><input type="text" name="var-type" /></p>';
} // add a number of couples of <input> equal to selectElm.value
}
//the following stuff says that when <select> changes the function called "update" must fire. Most of the code is for compatibility across browsers.
var listen, evt;
if (document.attachEvent) {
listen = 'attachEvent';
evt = 'onchange' ;
} else {
listen = 'addEventListener';
evt = 'change';
}
try {
selectElm[listen](evt, update);
} catch (e) {
selectElm[listen](evt, update, false);
}
// You do the same in Prototype with a single line:
// selectElm.observe('change', update);
// jQuery also requires only a single line of code.
</script>
</body>
</html>
Yes use onChange event of your dropdown input field and show/hide your input fields.