How to POST additional values from inputs outside the form [duplicate] - javascript

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.
My HTML Code:
<input type="text" name="member" value="">Number of members: (max. 10)<br />
Fill Details
So, a user will enter an integer value (I'm checking the validation using javascript) in the input field. And on clicking the Fill Details link, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.
I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in input field through the link and displaying corresponding number of input fields.

You could use an onclick event handler in order to get the input value for the text field. Make sure you give the field an unique id attribute so you can refer to it safely through document.getElementById():
If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild() to append each of them to the container. You might be interested in outputting a meaningful name attribute (e.g. name="member"+i for each of the dynamically generated <input>s if they are to be submitted in a form.
Notice you could also create <br/> elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode() instead.
Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes() and removeChild() together.
<html>
<head>
<script type='text/javascript'>
function addFields(){
// Generate a dynamic number of inputs
var number = document.getElementById("member").value;
// Get the element where the inputs will be added to
var container = document.getElementById("container");
// Remove every children it had before
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=0;i<number;i++){
// Append a node with a random text
container.appendChild(document.createTextNode("Member " + (i+1)));
// Create an <input> element, set its type and name attributes
var input = document.createElement("input");
input.type = "text";
input.name = "member" + i;
container.appendChild(input);
// Append a line break
container.appendChild(document.createElement("br"));
}
}
</script>
</head>
<body>
<input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
Fill Details
<div id="container"/>
</body>
</html>
See a working sample in this JSFiddle.

Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div><input type="text" name="mytext[]"></div>
</div>

Related

How to select "input type" value dinamically created through JS

When i got an HTML page which has a form like this
<form name='form'>
<label>Title <input id = "larger_title" type='text' maxlenght="100" name='ticket_title' value=''></label>
i select its value by using
const form=document.forms['form'];
form.addEventListener('submit',create);
...
form.ticket_title.value
But when i do create an input type element through JS, so dinamically, for example as if i have an array of elements, each of them with a button that enables a function where are sent data that includes these input text, how do i select the values of these like i used to with form, but now without a form, straight from js itself?
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.value="";
This code is outside the function related to the button, but how do i select its values in the function?
How should i select the text inserted in the input area whenever the user submits the button?
Interacting with a dynamically created element is no different than interacting with a static one - - you access its properties and methods the same way.
Your problem is that although your code to create a new dynamic element isn't actually inserting the element into the document, so although it exists, it can't be found in the DOM. It should be appended to the document first:
const form=document.forms['form'];
form.addEventListener('submit',create);
function create(event){
form.ticket_title.value;
form.post_solution.value = "TEST";
}
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.value="";
// Now, insert the element into the document
document.querySelector("form > div").appendChild(input);
<form name='form'>
<div>
<label>Title <input id = "larger_title" type='text' maxlenght="100" name='ticket_title' value=''></label>
</div>
<button>Submit</button>
</form>
But, accessing your form fields through the use of document.forms[] is quite ancient and really should be retired and instead use the modern .querySelector() instead. .querySelector() accepts any valid CSS selector as a way of locating the first matching elment.
document.querySelector("form").addEventListener('submit',create);
function create(event){
form.ticket_title.value;
form.post_solution.value = "TEST";
}
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.value="";
// Now, insert the element into the document
document.querySelector("form > div").appendChild(input);
<form name='form'>
<div>
<label>Title <input id = "larger_title" type='text' maxlenght="100" name='ticket_title' value=''></label>
</div>
<button>Submit</button>
</form>
First you add an id or class property to the input:
var input = document.createElement("input");
input.type = "text";
input.name="post_solution";
input.id = "myInput";
input.value="";
Then you use document.getElementById:
const input = document.getElementById('myInput');
input.addEventListener('onchange', handleChange);

Keeping submit button disabled until dynamically created required fields are filled

I want to keep the submit button disabled until the required fields are being filled.
Firstly ,
I found some questions about this issue but the problem was i have some required fields and not required fields also i am creating these fields dynamically.
Here is an example:
<input type="text" id="releaseartist" name="releaseartist" required="true" placeholder="Required Field"/>
Also i have input like that , this is how i am creating them dynamically,
var trackartistinput = document.createElement('input');
trackartistinput.setAttribute('type', "text");
trackartistinput.setAttribute('id', "trackartist" + i);
trackartistinput.setAttribute('name', "trackartist");
trackartistinput.setAttribute("required", true);
trackartistinput.setAttribute("placeholder", "Required Field");
trackartistinput.setAttribute("class", "required");
And this is my submit button :
<input type="submit" class="btn btn-primary" value="Submit" id="form-submit" onclick="return myConfirm();" />
you can check the count of required fields added in the document so far and based on the counts you can set the property of submit button to disabled or enabled.
you can count required class components as follow:
var numItems = $('.required').length
EDIT
to check if all the required class elements are filled you can check as follow:
var required_ele = document.getElementsByClassName('required');
var allfilled=true;
for (var i = 0; i < required_ele.length; ++i) {
var item = required_ele[i];
if(item.value.length==0){
allfilled=false;
}
}
if(allfilled){
document.getElementById("form-submit").disabled = false;
}
else{
document.getElementById("form-submit").disabled = true;
}
Start with button having disabled attribute set.
Add change event listener to form element (assuming that is the parent of all input
elements)
in change handler check if all required fields are filled, if yes, enable submit button
This work well even if user remove value entered in required field later, submit button will become disabled again

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

Multi file upload

<?php $uploadNeed=3 ; for($i=0;$i<$uploadNeed;$i++) { ?>
<div class="smWidth">
<input type="file" name="upload_file" value="" id=" " OnClick="alert("
2 ");" />
<br />
<div class="clear">
</div>
</div>
<?php } ?>
I am able to create three file upload fields, but i want to add a new input file filed only when i select a file.... it should keep on increasing.... something like Facebook style file upload where you select a file for the first field, then the next popup's...
I am actually checking for click event of browse, but it does not work...
Here is a very basic pure-JS implementation - hopefully it will give you a nudge in the right direction...
<script type="text/javascript">
// This keeps track of how many inputs there are, because each one MUST have a unique name!
var inputCounter = 1;
function inputChange() {
// This function will add a new input element, in a div, as it is in your
// original code, every time it is called. We attach it to the onchange
// event of all the inputs
// Declare local variables and increment input counter (for input names)
var newContainerDiv, newClearDiv, newInput, newBr;
inputCounter++;
// Create the new elements and set their properties
newContainerDiv = document.createElement('div');
newContainerDiv.className = 'smWidth';
newInput = document.createElement('input');
newInput.type = 'file';
newInput.name = 'upload_file_'+inputCounter;
newInput.onchange = inputChange;
newBr = document.createElement('br');
newClearDiv = document.createElement('div');
newClearDiv.className = 'clear';
// Add the new elements to the DOM
newContainerDiv.appendChild(newInput);
newContainerDiv.appendChild(newBr);
newContainerDiv.appendChild(newClearDiv);
document.getElementById('uploads_container').appendChild(newContainerDiv);
}
</script>
<!-- just create one input at first, so we don't need the PHP loop any more -->
<div id="uploads_container">
<!-- we wrap it all in an outer container div with an id, to ease the task of adding more elements -->
<div class="smWidth">
<input type="file" name="upload_file_1" onchange="inputChange();" />
<br />
<div class="clear">
</div>
</div>
</div>
Try hooking some other events to your file field. As far as I know, jQuery has a very useful event called .change()
I think that would work in your case.

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources