Get multiple user inputs in one form field - javascript

I am trying to make a form field that asks the user which countries it has visited, and limit this to 10. So the user has to give ten inputs in one form field.
But when I click on the submit button it won't let the user enter a second time. It just calls the function that displays the first country that the user has entered.
How do I keep the values the user is entering in the form field and when the user has entered all the ten countries, then click on submit to call the function that would display all the countries?
function validateForm() {
var repeat = new Array();
for (i = 0; i < 10; i++) {
var x = document.forms["form1"]["countries"].value;
repeat.push(x);
}
document.write(repeat);
}
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" onclick="validateForm()" value="Click Me!">
It keeps on displaying that one country the user has entered 10 times, instead of letting user enter ten countries and then displaying then when clicking on submit.

This will do what you sketched out. I don't think it's a very good way of asking a user for 10 items, as there's no feedback as to how many they've entered, nor the ability to edit the items once entered, nor a way of clearing the list to enter 10 more. Also, this will never actually submit the list. But this meets the requirements as stated:
var repeat = [];
function validateForm() {
var countries = document.getElementById("countries");
if (repeat.length < 10) {
var x = countries.value;
repeat.push(x);
countries.value = "";
countries.focus();
}
if (repeat.length === 10) {
var hid = document.getElementById("list");
hid.value = repeat.join('|');
console.log(hid.value);
var ul = document.getElementById("display");
ul.innerHTML = "";
for (var i = 0; i < 10; i++) {
ul.innerHTML += `<li>${repeat[i]}</li>`;
}
document.getElementById("done").style.display = "block";
}
}
window.onload = function() {
document.getElementById("click").addEventListener("click", validateForm);
};
<form id="form1">
Enter the countries:
<input type="text" id="countries"><br><br>
<input type="button" id="click" value="Click Me!">
<input type="hidden" id="list" name="listOfCountries">
</form>
<br>
<div id="done" style="display:none">
Countries entered:
<ul id="display"></ul>
</div>
Note that the hidden fields listOfCountries will contain the list of 10 countries, delimited by a pipe symbol "|". It's up to you to post that to a server.

You could use a global array for the countries and store until ten countries in the array.
function enterCountry() {
var input = document.getElementById('country');
if (input.value && countries.length < 10) {
countries.push(input.value);
input.value = '';
input.placeholder = 'insert ' + (10 - countries.length);
}
if (countries.length === 10) {
input.placeholder = 'ready';
document.getElementById('allCountries').innerHTML = countries.join(', ');
}
}
var countries = [];
<form id="form1">
Enter the countries:
<input type="text" id="country" placeholder="insert 10"><br><br>
<input type="button" onclick="enterCountry()" value="Click Me!">
</form>
<div id="allCountries"></div>

Hey you can get multiple input value on submit with jquery
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});

Related

How to remove oninvalid for every input except one using javascript?

I created a form with some input fields and the user needs to fill at least one field and if the user doesn't select any then the error will be shown. I achieve that goal but I need to show my custom require message as invalid. Because of the oninvalid on every input, My code is not working properly but I want this message to show so how can I remove oninvalid from the rest of the input fields rather than the filled one?
<form>
<input name="youtube" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input name="vimeo" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input name="pinterest" oninvalid="this.setCustomValidity('Please fill out at least one social media field')" required/>
<input type="submit" name="submit" value="Submit" id="ls-submit">
</form>
document.addEventListener('DOMContentLoaded', function () {
const inputs = Array.from(document.querySelectorAll('input[name=youtube], input[name=vimeo], input[name=pinterest]'));
const inputListener = e => inputs.filter(i => i !== e.target).forEach(i => i.required = !e.target.value.length, i => i.oninvalid = !e.target.value.length);
inputs.forEach(i => i.addEventListener('input', inputListener));
});
I really don't have an idea what to do. We can also use alert as an error message and I tried that too but didn't get any success.
You could remove oninvalid and required from all inputs and check it instead with javascript:
var inputs = document.querySelectorAll('input');
document.querySelector('button').addEventListener('click', function() {
var valid = false;
for(i = 0; i < inputs.length; i++) {
if ( inputs[i].value != "" ) {
valid = true;
break;
}
}
if (valid) {
document.querySelector("form").submit();
}
else {
alert('Please fill out at least one social media field');
}
});
Working example (with 'alert' instead of 'setCustomValidity'):
var inputs = document.querySelectorAll('input');
document.querySelector('button').addEventListener('click', function() {
for(i = 0; i < inputs.length; i++) {
var valid = false;
if ( inputs[i].value != "" ) {
valid = true;
break;
}
}
if (valid) {
document.querySelector("form").submit();
}
else {
alert('Please fill out at least one social media field');
}
});
<form action="https://stackoverflow.com" method="GET">
<input name="youtube" value="">
<input name="vimeo" value="">
<input name="pinterest" value="">
<button type="button">submit</button>
</form>

how to get an array post values

In my script, I have input fields which are added dynamically. I have to get all input values using php but the problem in that $_POST['poids'] give me just the first value of input array, so just the first element of the array poids. This is my code:
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]", $wrapper).map(function() {
return +this.value
}).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item", $wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
var err_msg = 'limit riched';
//alert(err_msg);
window.alert(err_msg);
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<div class="container1" style="min-height:200px">
<button class="add_form_field">Add New Field ✚</button>
<form method="post" action="postForm.php">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
<button type="submit" name="" class="btn btn-danger btn-responsive "> Send </button></center>
</a>
</form>
</div>
to get post (postForm.php):
$poids = $_POST['poids'];
foreach($poids as $poid) {
echo " -->" .$poid;
}
I hope that you undestand what I mean.
Thank you in advance
The problem is that you're appending the div with the new input fields to $wrapper, but that's outside the form. You need to put it inside the form.
Change
$wrapper.append($form_colis); //add input box
to
$('.item', $wrapper).last().after($form_colis); //add input box
I'm no PHP expert, but by just browsing the code provided, it seems you're just searching for inputs with a name value of poids.
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
Then when you create a bew input, you do not append poids to the input name.
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis);
Therefore, you will only find one with your method, and that's this one:
<input type="text" placeholder="Poids" name="poids[]">
So to solve this, inside the $form_colis method, add poids to it I do believe.

How to validate all inputs which exists on page?

All inputs from page
I have this html page which is dynamical created, which contains some divs. Every div-question(0,1,2, etc) contain an input based on which answer type the user chose. I want to validate every single inputs from page and:
If value of one input type number,text,date is != "" alert("something")
else send the value in an array;
If checkbox/radio is not checked alert("something");
I tried something like this:
let nrDiv = document.getElementsByClassName("div-question");
let existInput = nrDiv[0].querySelector("input[type='text']");
let numberInput = nrDiv[0].querySelector("input[type='number']");
if (document.body.contains(existInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container[0].querySelector("input[type='text']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
It's working but if I come with another for loop, for input type="number" is not working anymore. I'm getting value null. So if I come with this:
if (document.body.contains(numberInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container.querySelector("input[type='number']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
And for the checkbox and radio inputs I don't have any idea. I want something like this:
If all inputs are not empty and minimum one checkbox/radio is checked, send the answer and question in an array else alert("error");
I feel like this is simple once you add the required attribute and/or a pattern.
This is a simple POC:
<form action="">
<input type="text" required>
<input type="number" required>
<input type="checkbox" required>
<input type="radio" required>
<input type="date" required>
<button type="submit">Submit</button>
</form>
Notice that when you click the submit button, it does the verification you want, in this case != "".

How to dynamically keep track of user inputs in JavaScript?

Does anyone have any idea to dynamically keep track of user inputs in a form? I learned how to disable a button and if users want to enable it, they would just have to fill in the input fields. While this works, if a user decides to backspace and go back to a clear field, the button is still enabled. I wanted to get some insight or ideas to keep track of user inputs dynamically.
I'm a bit new to JS so I just wanted some ideas. Is it possible to use for loops/forEach methods to iterate through the input fields? Or what approach do you recommend on taking?
HTML:
<form class="container">
<input type="text" class="input" />
<input type="email" class="input" id="input" />
<button type="submit" id="submitButton" href="index.html" disabled>
Submit
</button>
</form>
JavaScript:
document.getElementById("input").addEventListener("keyup", function() {
var inputs = document.querySelectorAll("input");
if (inputs != "") {
document.getElementById("submitButton").removeAttribute("disabled");
} else if ((inputs = "")) {
document.getElementById("submitButton").setAttribute("disabled", null);
}
});
Here is the solution of your problem.
document.addEventListener("keyup", function() {
var inputs = document.querySelectorAll("input");
var emptyFillExists = false;
for (let index = 0; index < inputs.length; index++) {
if (inputs[index].value.length === 0) {
emptyFillExists = true;
break;
}
}
if (!emptyFillExists) {
document.getElementById("submitButton").removeAttribute("disabled");
} else {
document.getElementById("submitButton").setAttribute("disabled", null);
}
});
<form class="container">
<input type="text" class="input" />
<input type="email" class="input" />
<button type="submit" id="submitButton" href="index.html" disabled>
Submit
</button>
</form>
There are a few things wrong with your codes:
You assume inputs as strings. It isn't. It's an array.
You track keyup event for only 1 input. You should track keyup event for all inputs instead.
Here's what I'd suggest you do:
Add event listener keyup for the form.
Interate through each input and check.
function areInputsValid() {
// Iterate through every input and check its value
var inputs = document.querySelectorAll('input');
for (var i = 0; i < inputs.length; i++)
if (inputs[i].value == '')
return false;
return true;
}
// Get the form element
var form = document.getElementsByTagName('form')[0];
// Add event listener
form.addEventListener('keyup', function() {
// Are the inputs valid?
if (areInputsValid())
document.getElementById("submitButton").removeAttribute("disabled");
else
document.getElementById("submitButton").setAttribute("disabled", null);
})
EDIT: as charlietfl pointed out, there are bugs in my previous answer.

Fill data in input boxes automatically

I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"

Categories

Resources