Reading Text From Dynamic Input Field JavaScript - javascript

I have a website where you can enter text into an input field, and press "Add new row" to add another input field.
When the user presses the submit button, I want to be able to read all of the text inside of the text field, but I can't seem to figure out how to access the text within the text fields.
Here is my code:
<head>
<script src = "https://code.jquery.com/jquery-3.3.1.min.js"
crossorigin="anonymous"> </script>
</head>
<script type ="text/javascript">
var array = []
var track = 0;
$(document).on("click", ".btn-add-row", function(){
var row = $(".row").eq(0).clone().show();
$(".element-wrapper").append(row);
var ye = $(".element-wrapper")
})
$(document).on("click", ".btn-remove-row", function(){
var index = $(".btn-remove-row").index(this);
$(".row").eq(index).remove();
})
</script>
<body>
<h1>upload file</h1>
<form method = "post" enctype="multipart/form-data" action = "/">
<input type = "file" name = "filename">
<input type = "submit" value = "upload">
</form>
<div class = "element-wrapper">
<div class = "row" style = "display: none;">
<input type = "text" placeholder = "Attribute" id = "ye">
<button class = "btn-remove-row">
Remove Row
</button>
</div>
</div>
<button class = "btn-add-row"> Add New Row </button>
</body>
</html>
And here is a CodePen to go along with it:
https://codepen.io/etills/pen/qBdEKPV
Would appreciate it if someone could tell me how to read all the text from the input rows when the user presses submit.
I ultimately want to put the text into an array and make a .txt file with that text that is entered.
Thanks

You need this selector to capture only the visible textboxes:
div.row:not([style='display: none;']) input[type=\"text\"]"
Something like this:
$("form").on("submit", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("div.row:not([style='display: none;']) input[type=\"text\"]");
var len = inputs.length;
for (var i = 0; i < len; i++) {
array.push({
input: i,
value: inputs[i].value
});
}
console.log(array);
});
You'll get this result:
See in this example:
$(function() {
var array = [];
var track = 0;
$(document).on("click", ".btn-add-row", function() {
var row = $(".row").eq(0).clone().show();
$(".element-wrapper").append(row);
var ye = $(".element-wrapper")
});
$(document).on("click", ".btn-remove-row", function() {
var index = $(".btn-remove-row").index(this);
$(".row").eq(index).remove();
});
$("form").on("submit", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("div.row:not([style='display: none;']) input[type=\"text\"]");
var len = inputs.length;
for (var i = 0; i < len; i++) {
array.push({
input: i,
value: inputs[i].value
});
}
console.log(array);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>upload file</h1>
<form method="post" enctype="multipart/form-data" action="/">
<input type="file" name="filename">
<input type="submit" value="upload">
</form>
<div class="element-wrapper">
<div class="row" style="display: none;">
<input type="text" placeholder="Attribute">
<button class="btn-remove-row">
Remove Row
</button>
</div>
</div>
<button class="btn-add-row"> Add New Row </button>
Remember: Element Id must be unique in a page. Avoid using the same id="ye" in <input type="text" placeholder="Attribute" id="ye">.

On submit check for all the inputs that you want and collect their values.
$(document).on("click", "input[type=submit]", function(e){
e.preventDefault()
$('input[type=text]').each((i, input) => {
console.log(input.value)
})
})
Example: https://codepen.io/jzabala/pen/vYOErpa?editors=1111

Related

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.

I am trying to make a checklist where I can click on the button attributed to each "task" and the single line is removed when it is clicked.

Like the question says. I have been able to rid the entire list with a click of a single button (not what I want), I have been able to click a button and rid just the button but not the text - this is what is giving me the biggest issue.
Any help would be greatly greatly appreciated.
//create the initial todocount variable
var toDoCount = 0;
window.onload = function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("#to-dos").prepend(linebreak);
$("#to-dos").prepend(value);
$("#to-dos").prepend(todoclose);
toDoCount++;
//to remove item from checklist
$(document.body).on("click", ".checkbox", function() {
var toDoNumber = $(this).attr("data-to-do");
$("#to-dos").remove();
});
});
HTML below
<div class ="col-4">
<!-- To Do List -->
<form onsubmit= "return false;">
<span id = "todo-item" type = "text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
This should work.
//create the initial todocount variable
var toDoCount = 0;
$(function() {
//user clicked on the add button in the to-do field add that text into the to-do text
$('#add-to-do').on('click', function(event) {
event.preventDefault();
//assign variable to the value entered into the textbox
var value = document.getElementById('to-do').value;
//test value
console.log(value);
var todoitem = $("#to-dos");
todoitem.attr("item-");
//prepend values into the html and add checkmark, checkbox, and line break to make list
var linebreak = "<br/>";
var todoclose = $("<button>");
todoclose.attr("data-to-do", toDoCount);
todoclose.addClass("checkbox");
todoclose.text("☑");
//prepend values to html
$("<div/>", {
"class": "to-do-item"
})
.append([todoclose, value, linebreak])
.appendTo($("#to-dos"));
toDoCount++;
//to remove item from checklist
$(document.body).on("click", ".to-do-item", function() {
var toDoNumber = $('.checkbox', this).attr("data-to-do");
$(this).remove();
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-4">
<!-- To Do List -->
<form onsubmit="return false;">
<span id="todo-item" type="text">
<h4>Add your Agenda Here</h4>
<input id ="to-do" type = "text">
<input id ="add-to-do" value = "Add Item" type = "submit">
</span>
</form>
<div id="to-dos"></div>
</div>
I found the root issue to be related to how you remove the item. If it is based on the button click, then $(this).remove() simply removes the button.
Consider the following code.
$(function() {
function makeTask(todo) {
var c = $("#to-dos .todo-item").length + 1;
console.log(c, todo);
var item = $("<div>", {
class: "todo-item",
id: "todo-item-" + c
});
$("<button>", {
class: "checkbox todo-item-close",
id: "todo-item-close-" + c
}).html("☑").click(function(e) {
console.log("Remove", $(this).parent().attr("id"));
$(this).parent().remove();
}).appendTo(item);
item.append(todo);
return item;
}
$('form').submit(function(e) {
e.preventDefault();
var task = makeTask($("#to-do").val());
task.appendTo("#to-dos");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-4">
<!-- To Do List -->
<form>
<h4>Add your Agenda Here</h4>
<input id="to-do" type="text" />
<input id="add-to-do" value="Add Item" type="submit" />
</form>
<div id="to-dos"></div>
</div>
Here we add the button and assign a click event to that button. Since the button is inside the <div> we need to traverse to the parent element and then remove the entire element.
Since it is in a form, and many users may try to submit the data with Enter, I prefer to use .submit() callback.
Hope that helps.

Get multiple user inputs in one form field

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() );
});

Get form values through JavaScript

This is my HJTML code. I don't know how to get values stored in filtertime[] using JavaScript and make them show on my screen.
<form action="index.php" method="post" >
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Morning"></div> <div class="f-txt-r">Morning</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Afternoon"></div> <div class="f-txt-r">Afternoon</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Evening"></div> <div class="f-txt-r">Evening</div></div>
<div class="col-lg-6"><div class="f-txt-l"><input id="test" type="checkbox" name="filtertime[]" class="morning" value="Night"></div> <div class="f-txt-r">Night</div></div>
<div class="col-lg-12"><input type="submit" name="button" class="apply-filter" value="Apply Filter"></div>
</form>
<script>
var new = document.getElementsById("test").innerhtml
</script>
How can I get input values in JavaScript through value is stored in array as filtertime[]?
try
in your form
<form action="index.php" id="myform" method="post" >
in jQuery
var datastring = $("#myform").serialize();
By JS
var params = '';
for( var i=0; i<document.FormName.elements.length; i++ )
{
var fieldName = document.FormName.elements[i].name;
var fieldValue = document.FormName.elements[i].value;
// use the fields, put them in a array, etc.
// or, add them to a key-value pair strings,
// as in regular POST
params += fieldName + '=' + fieldValue + '&';
}
Add id in your form tag.
<form action="index.php" id="form_name" method="post" >
Use below code to get all form element by JS :-
document.forms["form_name"].getElementsByTagName("input");
Note:- Above Code will work only if you don't have selects or textareas in your form.
If you have assigned id in DOM element like below,
<input type="text" name="name" id="uniqueID" value="value" />
Then you can access it via below code:-
Javascript:-
var nameValue = document.getElementById("uniqueID").value;
If you have Radio button in your form, then use below code:-
<input type="radio" name="radio_name" value="1" > 1
<input type="radio" name="radio_name" value="0" > 0<br>
Javascript:-
var radios = document.getElementsByName('radio_name');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
Hope it will help you :)
this is the easiest way to get array of your form items
var arrValues = [];
for (var x =0; x < document.getElementsByClassName("morning").length ; x++)
{
arrValues.push(document.getElementsByClassName("morning")[x].checked);
}
To do that, the easiest way is to select all input with the "morning" class and after, foreach look if is checked :
var item = document.getElementsByClassName("morning"); // get all checkbox
var checkboxesChecked = []; // result array with ckecked ckeckbox
for (var i=0; i<item.length; i++) {
// if is checked add the value into the array
if (item[i].checked) {
checkboxesChecked.push(item[i].value);
}
}
console.log(checkboxesChecked);
In the "checkboxesChecked" array you have all the values of the checked box.

implementing insertbefore() in loop

I am trying to show error messages below an array of textboxes that I have selected using Javascript. The error messages are being put by creating a new span element and using the insertBefore() method. The span element is created in the function since I don't want to hard code it into the DOM. The span messages do show but each time I submit the form, they are appended over and over again. I'd like to show the span messages only once and each time the form is submitted, they are shown once only. Below is my code.
HTML
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" />
<input type="text" name="2" class="textbox" />
<input type="text" name="3" class="textbox" />
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
JAVASCRIPT
<script>
var slideshow = document.querySelector('.slideshow');
// var span = document.createElement('span');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function(e)
{
e.preventDefault();
for( var i=0; i<inputs.length; i++ )
{
var span = document.createElement('span');
(function(index)
{
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
</script>
Each time I submit, I'd like the error messages to be shown below the textbox and not appended over and over again. They should be shown just once and I'd like to do this without using jQuery or any sort of library.
I rewerite your example to create available 3 span tags instead of crate them in code. If there are some errors, populate them to span rather than creating/deleting the spans in code.
var slideshow = document.querySelector('.slideshow');
var form = document.querySelector('#form');
var inputs = form.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
(function (index) {
document.getElementsByTagName('span')[index]
.innerHTML = 'error ' + index;
})(i);
}
}, false);
<div class="slideshow">
<form id="form">
<input type="text" name="1" class="textbox" /><span></span>
<input type="text" name="2" class="textbox" /><span></span>
<input type="text" name="3" class="textbox" /><span></span>
<input type="submit" name="submit" value="submit" id="submit" />
</form>
</div>
Hope this help.
Just do a check before you insert. Here is one way to do it.
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
if (inputs[index].nextElementSibling.tagName !== 'SPAN')
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
You have to wait for page to be load, the you should run JavaScript.
PageLoad Event : window.onload=function(){}
Code :
<script type="text/javascript">
window.onload = function () {
var slideshow = document.querySelector('.slideshow');
var form = document.getElementById('form');
var inputs = document.querySelectorAll('.textbox');
form.addEventListener('submit', function (e) {
e.preventDefault();
for (var i = 0; i < inputs.length; i++) {
var span = document.createElement('span');
(function (index) {
span.innerHTML = 'error ' + index;
inputs[index].parentNode.insertBefore(span, inputs[index].nextElementSibling);
})(i);
}
}, false);
}
</script>
Put your code in window.onload event.

Categories

Resources