Create dynamic text boxes then write to text file - javascript

So there must be an easier way to create this. I have a form with the following HTML:
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then added some JS to create new text boxes if a user needs to add more names:
Taken from: http://www.sanwebcorner.com/2017/02/dynamically-generate-form-fields-using.html
$(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="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(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="Name"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
function check() {
var temp = document.getElementsByClassName("formElem");
if (document.getElementById("ckbox").checked) {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = false;
}
} else {
for (var e = 0; e < temp.length; e++) { // For each element
var elt = temp[e];
elt.required = true;
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Names</p>
<ul class="container1" style="list-style-type:none;">
<li><input type="text" size="10" name="Name" /></li>
</ul>
<input type="button" class="add_form_field" value="+">
I then need to write those appended values to a .CSV file using PHP and here is where I am having the issue:
<?php
// Receive form Post data and Saving it in variables
header('Location: thanks.html');
$Name = "";
$Name = #$_POST ['Name'];
// Write the name of text file where data will be store
$filename = "file.csv";
// Merge all the variables with text in a single variable.
$f_data= '
Names for people: '.$Name.' ';
$file = fopen($filename, "r+");
fwrite($file,$f_data);
fclose($file);
?>
What happens is that the last appended text box gets written into the csv file.Is there a way to pass these created text boxes so they can write to a the file? Really similar question: Pass dynamic text input to PHP in order to write to text file
But I'm not sure if this can be done with text boxes.

The problem is that every input you add has the name “name”, so PHP can only access the last one (which overwrote the others). To get around this, you can add an index to the input name or make an array of them. This can be achieved like so:
<input type="text" name="name[]"...>
So now, on the PHP script you can iterate over that array to get all the inputs, or implode all the elements into a variable:
<?php
$names = implode(", ", $_POST["name"]); // all the names, comma-separated
?>
Now you can use $names inside $f_data to see all the inputted fields.
(Thanks Fred-ii for the heads up about the quotes)

Related

how to generate dynamic input and get the value by id using jquery

Actually i have a form where i enter name ,html page name in a input box and save it to the database. Here i got some issues
i am able generate input box but how to get the value of that input box ?
how to get the dynamic values of the input box which was entered in dynamic boxes and send it to post request as i know how to send a static input box value request for multiple how can we send it .
here is what below is my code
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
i thins above i can generate dynamic input box and can remove it but unable to get values so how can generate by using id and post all dynamically generated values to the database
You can use the jquery #map() function like this:
var list = wrapper.find('input').map(function() {
return $(this).val();
}).get();
when you want to submit the list of values to the send to the server - see demo below:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) { //on add input button click
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
});
/* ADDED THIS */
$('.submit').click(function() {
var list = wrapper.find('input').map(function() {
return $(this).val();
}).get();
// send to server here
console.log(list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
<button class="submit">Submit</button>
Yea can try something like this
var inputField = $('<div><input type="text" name="mytext[]"/>Remove</div>');
$(wrapper).append(inputField);
Then you can attach an event to that variable.
inputField.on('change', 'input', function() {
var value = $(this).val();
console.log(value);
});
Hope this helps you :)
Another way, add the following button the form:
<button class="getValue">Get Field Values</button>
Add the below button click event in JS on load:
$(getValue).click(function (e) {
e.preventDefault();
let fieldValues = "";
$("input").each(function(i,e){
fieldValues = fieldValues == "" ? $(e).val() : fieldValues + ", " + $(e).val();
})
alert(fieldValues);
});

Display number of Input fields based on the value in database column

I have a database table with column name qty that holds an int.Now i want to display as many input fields as the value in qty.
So far i haved tried this using iavascript code . Here is my javascript code .
$(function() {
var input = $(<input 'type'="text" />);
var newFields = $('');
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n+1) {
if (n > newFields.length) {
addFields(n);
} else {
removeFields(n);
}
}
});
function addFields(n) {
for (i = newFields.length; i < n; i++) {
var newInput = input.clone();
newFields = newFields.add(newInput);
newInput.appendTo('#newFields');
}
}
function removeFields(n) {
var removeField = newFields.slice(n).remove();
newFields = newFields.not(removeField);
}
});
Just store the value in the textfield(hidden)
HTML:
<input type="hidden" id="quantitycount" value="4" />
<div class="textboxarea"></div>
Jquery:
Get the textbox value
var quantitycount=jQuery('#quantitycount').val();
var txthtml='';
for(var txtcount=0;txtcount<quantitycount;txtcount++){
txthtml+='<input type="text" id="txtbox[]" value="" />';
}
jQuery('.textboxarea').html(txthtml);
You can use entry control loops to loop for number of times
Now we can see number of textbox as per need, Just the value from db and store that in the textbox
You can try this
foreach($qty as $qt){
echo '<input type="text">';
}
To append the text fields you need a wrapper on your html form
use some wrapper as mentioned by #Rajesh: and append your text-fields to that wrapper as shown below
$('#qty').bind('blur keyup change', function() {
var n = this.value || 0;
if (n >0) {
for(var x=0;x<n;x++){
$('#textboxarea').append('<input type="text" name="mytext[]"/>');
}
});
similarly you can write your own logic to remove the text-fields also using jquery

php mysql populate several dynamic dropdown list with add button

well this is my first post :)
I have a mysql DB and a form where you chose what you want to order. I have to say, that for input fields it works, but I have a problem when it comes to dynamic dropdowns. This is what I have (the two queries):
<?php
// Getting the data from mySQL table for first list box
$quer1="SELECT DISTINCT kategorija FROM artikli order by kategorija";
// for second dropdown list we will check if category is selected else we will display all the subcategories
if(isset($kategorija) and strlen($kategorija) > 0) {
$quer2="SELECT artikel FROM artikli where kategorija='$kategorija' order by artikel";
}
else {
$quer2="SELECT artikel FROM artikli order by artikel";
}
?>
<form id="forma_narocilo" action="naroci.php" method="POST">
<div class="input_fields_wrap">
<div>
<select name="kategorija" id="kategorija" ><option value="">Izberi kategorijo</option>
<?php
foreach ($dbo->query($quer1) as $row2) {
if($row2['kategorija']==$kategorija) {
echo "<option id='izbirna_kategorija' selected value='$row2[kategorija]' onchange='self.location=self.location+'?kategorija='+this.options[this.selectedIndex].value'>$row2[kategorija]</option>"."<br />";
}
else {
echo "<option id='izbirna_kategorija' value='$row2[kategorija]'>$row2[kategorija]</option>";
}
}
echo "</select>";
echo "<select name='artikel[]'><option value=''>Izberi artikel</option>";
foreach ($dbo->query($quer2) as $row) {
echo "<option value='$row[artikel]'>$row[artikel]</option>";
}
echo "</select>";
?>
<input type="number" name="kolicina[]"/><button class="add_field_button">Add line</button>
</div>
</div>
<input type="submit" id="shrani" value="Save" >
</form>
and this works just fine and it is updating the fields according to my needs, but now I need an "add" button which will insert another line with all three fields (category, item, nrPcs). For normal html inputs I used this:
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>'+x+'<input type="text" name="artikel[]"/><input type="text" name="kolicina[]"/>X</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
this will add a and 2 inputs inside. for the reload I use this:
function reload(){
var form = document.getElementById("forma_narocilo");
var val = form.kategorija.options[form.kategorija.options.selectedIndex].value;
self.location='?kategorija=' + val ;
}
function init(){
document.getElementById("kategorija").onchange = reload;
}
window.onload = init;
Now, my question is, how can I insert dropdowns when clicking the add button? Of course it should work as the first one e.g. it has to be independent...
thanks, erik

Multiple values inserted into 1 attribute in database

How can I get values from the added input field into my database? When I run this code the table shows "array" instead of the values entered..
Javascript to add input field:
<script>
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><label for="no_telefon[]">No.Telefon: </label><input type="text" name="no_telefon[]" id="no_telefon[]" class="required input_field"><label for="lokasi[]">Lokasi: </label><input type="text" name="lokasi[]" id="lokasi[]" class="required input_field">Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
the Input field form:
<fieldset>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<label for="no_telefon[]">No.Telefon:</label> <input type="text" id="no_telefon[]" name="no_telefon[]" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')" required/>
<label for="lokasi[]">Lokasi:</label> <input type="text" id="lokasi[]" name="lokasi[]" class="required input_field" required/>
</div>
and the PHP file to insert data into the database:
<?php
require("dbase.php");
if ($_POST) {
$id_akaun = isset($_POST['id_akaun']) ? $_POST['id_akaun'] : '';
$daerah = isset($_POST['daerah']) ? $_POST['daerah'] : '';
$kategori_akaun = isset($_POST['kategori_akaun']) ? $_POST['kategori_akaun'] : '';
$bahagian = isset($_POST['bahagian']) ? $_POST['bahagian'] : '';
$jenis = isset($_POST['jenis']) ? $_POST['jenis'] : '';
$no_telefon = isset($_POST['no_telefon']) ? $_POST['no_telefon'] : '';
$lokasi = isset($_POST['lokasi']) ? $_POST['lokasi'] : '';
$id = isset($_POST['id']) ? $_POST['id'] : '';
$sql = mysql_query("INSERT INTO maklumat_akaun VALUES ('', '$id_akaun' , '$daerah' , '$kategori_akaun' , '$bahagian' )");
$sql = mysql_query("INSERT INTO detail_akaun VALUES ('', '$jenis' , '$no_telefon' , '$lokasi', '".mysql_insert_id()."' )");
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='lamanutama.php'</script>";
}
?>
You need to use a loop to process all the no_telefon and lokasi fields:
$sql = mysql_query("INSERT INTO maklumat_akaun VALUES ('', '$id_akaun' , '$daerah' , '$kategori_akaun' , '$bahagian' )");
$akaun_id = mysql_insert_id();
foreach ($no_telefon AS $i => $telefon) {
$sql = mysql_query("INSERT INTO detail_akaun VALUES ('', '$jenis' , '$telefon' , '$lokasi[$i]', '$akaun_id' )");
}
This will create a separate row in detail_akaun for each pair of no_telefon and lokasi.
BTW, you're creating duplicate IDs with id="no_telefon[]" and id="lokasi[]". IDs are supposed to be unique. All your labels with for="no_telefon[] and for="lokasi[] will be attached to the fields in the first row, not the one after it. Instead of using IDs and for, try wrapping your labels around the inputs:
<label>No.Telefon: <input type="text" name="no_telefon[]" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')" required/></label>
Array data can't be saved in SQL because it's a php data type, and cannot be easily converted to a string.
So you will need to do the conversion by yourself.
A quick example:
$no_telefon_string = "";
foreach($no_telefon as $telefon)
{
$no_telefon_string .= $telefon.",";
}
$no_telefon_string = rtrim($no_telefon_string, ",");
Now you can insert the $no_telefon_string variable into the database.
To turn $no_telefon_string back into an array you can use:
$no_telefon = explode($no_telefon_string, ",");
$no_telefon will now be the array you originally got from the form post.

How can I extract the values entered in the input boxes generated dynamically and pass it to controller using jquery?

I have a form wherein a user can enter input boxes and remove them at a click. I want to extract the values entered in these input boxes and pass them to controller using jQuery. How do I do that?Right now I am using ids to extract the values but I do not think that is a better method because suppose I add 4 options and then I remove all of them and then again add inputs, I will not be able to track these ids and extract the values.
Here is my HTML code:
<button type="button" class="addoption" id="addoption_btn">Add more option</button>
<div id="Options">
<input type="text" name="mytext[]" id="option_1" placeholder="Option 1"/>
</div>
Here is my JavaScript:
var MaxOptions = 4; //maximum input boxes allowed
var Optionsform = $("#Options"); //Input boxes wrapper ID
var AddButton = $("#addoption_btn"); //Add button ID
var x = Optionsform.length; //initial text box count
var OptionCount=1; //to keep track of text box added
$(AddButton).click(function (e) //on add input button click
{
if(x <= MaxOptions) //max input box allowed
{
OptionCount++; //text box added increment
//add input box
$(Optionsform).append('<div><input type="text" name="mytext[]" id="option_'+ OptionCount +'" placeholder="Option '+ OptionCount +'"/>×</div>');
x++; //text box increment
}
return false;
});
$("body").on("click",".removeclass", function(e){ //user click on remove text
if( x > 1 ) {
$(this).parent('div').remove(); //remove text box
x--; //decrement textbox
}
return false;
});
Here is the jQuery I am using to pass the data to my controller:
$("#addquestion_btn").click(function(){
var val= CKEDITOR.instances['question_topic'].getData();
storequestion(val);
});
function storequestion(ques)
{
$.post("/instructor/store/question",{
question: ques,
option1: $("#option_1").val(),
option2: $("#option_2").val()
},function(data){
if(data[0]==="success")
{
window.location.href = '/instructor/create/topics';
}
else
{
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}}
,'json');
}
Please use below mentioned code to read through all displayed options.
function storequestion(ques) {
obj = {};
obj[question] = ques;
$("#Options:input[name*='mytext']").each(function (index) {
obj['option' + index] = $(this).val();
});
$.post("/instructor/store/question", obj
, function (data) {
if (data[0] === "success") {
window.location.href = '/instructor/create/topics';
}
else {
alert("fails");
window.location.href = '/instructor';
//redirect to further page to enter courses
}
}
, 'json');
}

Categories