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)
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
I'm using codeigniter 3.0.4 and now stuck on a basic problem. I have an <input type='text'> with a default value generated using Jquery.
My Question, how do I check whether the value has been changed or not when I submit a form?
If the value now is different from default given value, it'll do a callback validation (it's actually to check email availability). Otherwise if the value is still the same as the default given value it will skip the callback validation.
This is my modal
<div class="modal-body" id="myModalBody">
<form id="contactform" role="form" method="POST" action='<?php echo base_url('administrator/kategori/editcategory');?>' >
<div class="form-group">
<label for="kategori"> Nama Kategori </label>
<input type="hidden" name="id" class='id' id='id'>
<input type="text" class="form-control edit-category" name='edit-category' id="edit-category" required autofocus>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success confirm-edit"> Edit Data </button>
</form>
</div>
as you can see, that form above submits the data to administrator/kategori/editkategori
and this is my editkategori() function
public function editcategory(){
if($this->input->post()){
$this->form_validation->set_rules('kategori', 'Kategori Baru', 'required|callback_correctcategory');
if($this->form_validation->run() == FALSE){
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"id" => $this->input->post('id'),
"kb" => $this->input->post('kategori')
);
$result = $this->admincrud->editcategory($tobesent);
if($result){
$this->session->set_flashdata('result', 'Kategori Sukses Diubah');
redirect('administrator/kategori');
}
}
} else {
redirect('administrator/kategori');
}
}
This is the JQuery function to automatically give values to corresponding text when the modal above is shown
$('.toggle-edit-modal').click(function(){
var id = $(this).closest('tr').find('td:eq(0)').text();
var categoryname = $(this).closest('tr').find('td:eq(1)').text();
$('.id').val(id);
$('.edit-categoryname').val(categoryname);
})
in the set of validation rules, I put the callback correctcategory(), and this is the correctcategory() function :
public function correctcategory($str){
$sterilizedkey = strtoupper(trim(str_replace(" ", "", $str)));
$tobeshown = ucfirst(strtolower($sterilizedkey));
$this->CI->db->select("upper(trim(REPLACE(`CategoryName`, ' ',''))) as `CategoryName`");
$this->CI->db->from('category');
$result = $this->CI->db->get()->result_array();
$data = array();
foreach ($result as $key => $value) {
$data[] = $value['CategoryName'];
}
if(in_array($sterilizedkey, $data)){
$this->set_message('correctcategory', 'The faculty has been registered before');
return false;
} else {
return true;
}
}
With the code above, the system will evaluate every value submitted through the form.
The problem comes when I open the modal, and a textbox with default given value appears. How can I skip the correctcategory validation if I directly submit the form but without changing the value of the textbox, or when the new value and the old given one are exactly the same ?
you have to store the original value in a hidden text box. and check it with the text box which has values.
for eg:
<input type="text" id="orig" value="your email">
<input type="hidden" id="hid" value="your email">
then in jquery on submit check like the following
var original = $('#orig').val();
var static = $('#hid').val();
if(original == static){
alert("not changed");
}else{
alert("changed");
}
Note: this code is only for example as you did'nt shared any of your code
If the value being set by Jquery is known by you, then the controller should as well be aware( guess this is the category database value)
Based on the assumption that default value is known.
To solve this, the controller function needs to be aware of the default value you are setting for the input.
class Categories extends CI_Controller {
public function edit()
{
// form submited?
If ( $this->input->post())
{
$this->load->model('category_model');
$error = null;
$success = false ;
$id = $this->input->post('id');
// now you were looking for 'kategori' instead of 'edit-category'
$posted_cat_name = $this->input->post('edit-category');
// get the db record
$category = $this->category_model->fetch( array('id' => $id ));
if( !$category->id)
{
$error = 'Category not exist' ;
// set flash and redirect
redirect('categories/admin_list');
}
// category remain the same
If( $posted_cat_name == $category->name)
{
$error = "No changes made" ;
}
else if( $this->category_model->update($id , $posted_cat_name) == false)
{
$error = 'Error occured updating category' ;
// get the error and log_message() for debuging
}
else
{
$success = true ;
// set flash data and redirect
}
}
// do you need this remaining code? aren't you suppose to redirect back to admin list where the form was posted ?
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
}
}
What I have here is validation for comparing textbox values. I have quantity textbox and a hidden textbox, If quantity textbox is lower than the hidden textbox error message will display in span. But the problem is even in other span that has a correct value error message always appears.
Just like the picture below if quantity is less than the hidden textbox error message display but on the other textbox which is has a correct value error message is still display. Help?
$('.n_quantity,.pr_total').each(function () {
var textBox1 = $(".n_quantity");
var textBox2 = $(".pr_total");
for (var i = 0, len = textBox1.length; i < len; i++) {
if (parseInt(textBox2[i].value) > parseInt(textBox1[i].value)) {
$(this).next("span.val_over").html("Over").addClass('validate');
validation_holder = 1;
return false;
}
}
});
<p>
<label for="">PR Quantity</label>
<input name="n_quantity[]" id="n_quantity" class="qty tb1 n_quantity" type="text" value="<?php echo $row['total_quantity'] ?>" />
<span class="val_qty val_over"></span>
</p>
<p style="display:none;">
<input id="pr_total" class="tb2 pr_total" type="text" value="<?php echo $row['total_quantity'];?>" readonly="readonly">
</p>
You could iterate the editable fields, then traverse the dom to the related elements:
$('.n_quantity').each(function () {
var $this = $(this);
var $total = $this.closest('p').next().find('.pr_total');
if (parseInt($this.val(), 10) > parseInt($total.val(), 10)) {
$this.siblings('.val_over').html('Over').addClass('validate');
validation_holder = 1;
}
});
I have a MySQL database of orders that each have various activities associated with them. My PHP/HTML page pulls down the activities when you click an order and allows the user to change attributes of the activities with a form. On submit another PHP file loops through activities in the table and runs an update query on the database. Works great!
I have recently added a JavaScript function that will add activities to the list (appendChild, createElement...). I then added to my PHP file an INSERT query for the new activities.
The problem is that when I run the update PHP file it is not looping through the newly added records that were added with JavaScript. I checked it by using <?php print $size = count($_POST['FcastID']) ?> and the value doesn't change when records have been added.
The records look fine when added to the table and the id and name convention match the other records. It seems like the page needs to be refreshed before the PHP file runs.
PHP file with dynamically created html form
<div id="submit"><form method="post" action="Up_Forecast.php"><input type="submit" value="Submit"></div>
....
<table id="fcast">
<?
$i=0;
while($row = mysqli_fetch_array($res_fcast))
{
echo "<tr id='fcastRow[$i]'>";
echo "<td class='medium'><input type='text' id='qtyJan[$i]' name='qtyJan[$i]' value='".$row[Jan]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyFeb[$i]' name='qtyFeb[$i]' value='".$row[Feb]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMar[$i]' name='qtyMar[$i]' value='".$row[Mar]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyApr[$i]' name='qtyApr[$i]' value='".$row[Apr]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyMay[$i]' name='qtyMay[$i]' value='".$row[May]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJun[$i]' name='qtyJun[$i]' value='".$row[Jun]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyJul[$i]' name='qtyJul[$i]' value='".$row[Jul]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyAug[$i]' name='qtyAug[$i]' value='".$row[Aug]."'/></td>";
echo "<td class='medium'><input type='text' id='qtySep[$i]' name='qtySep[$i]' value='".$row[Sep]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyOct[$i]' name='qtyOct[$i]' value='".$row[Oct]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyNov[$i]' name='qtyNov[$i]' value='".$row[Nov]."'/></td>";
echo "<td class='medium'><input type='text' id='qtyDec[$i]' name='qtyDec[$i]' value='".$row[Dec]."'/></td>";
echo "<td class='medium'><input type='text' id='Totalqty[$i]' name='Totalqty[$i]' value='".$row[Total]."' disabled/></td>";
echo "</tr>";
++$i;
}
?>
<tr><td class="blank"></td><td class="mini"><input type="button" onclick="addRowYear(this)" value="Add"/></td></tr>
</table>
</form>
</div>
Javascript function to add row
function addRowYear(lastRow){
var rowNo = lastRow.parentNode.parentNode.rowIndex;
var newRow = document.getElementById("fcast").insertRow(rowNo);
newRow.setAttribute("id","fcastRow["+rowNo+"]");
var cell0 = newRow.insertCell(0);
cell0.setAttribute("class","mini");
var input0 = document.createElement("input");
input0.setAttribute("type","text");
input0.setAttribute("name","FcastID["+rowNo+"]");
input0.setAttribute("value","new");
cell0.appendChild(input0);
var cell1 = newRow.insertCell(1);
cell1.setAttribute("class","mini");
var input1 = document.createElement("input");
input1.setAttribute("type","text");
input1.setAttribute("name","Fcast_ActID["+rowNo+"]");
input1.setAttribute("id","Fcast_ActID["+rowNo+"]");
cell1.appendChild(input1);
var curAct = document.getElementById("selAct").innerHTML;
document.getElementById("Fcast_ActID["+rowNo+"]").value = curAct;
var cell2 = newRow.insertCell(2);
cell2.setAttribute("class","mini");
var input2 = document.createElement("input");
input2.setAttribute("type","text");
input2.setAttribute("name","Year["+rowNo+"]");
cell2.appendChild(input2);
var month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
for (var i = 0; i < month.length; i++) {
//alert(month[i]);
x=3;
var cell = newRow.insertCell(x);
cell.setAttribute("class","medium");
var input = document.createElement("input");
input.setAttribute("type","text");
input.setAttribute("class","numbers");
input.setAttribute("name","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("id","qty"+month[i]+"["+rowNo+"]");
input.setAttribute("onkeyup","findTotal()");
cell.appendChild(input);
x=x+1;
}
var cell15 = newRow.insertCell(15);
cell15.setAttribute("class","medium");
var input15 = document.createElement("input");
input15.setAttribute("type","text");
input15.setAttribute("class","numbers");
input15.setAttribute("name","Totalqty["+rowNo+"]");
input15.setAttribute("id","Totalqty["+rowNo+"]");
cell15.appendChild(input15);
PHP Update - Called on Submit of form
$size = count($_POST['FcastID']);
$i = 0
while ($i < $size) {
$FcastID = $_POST['FcastID'][$i];
$ActID = $_POST['Fcast_ActID'][$i];
$Year = $_POST['Year'][$i];
$Jan = $_POST['qtyJan'][$i];
$Feb = $_POST['qtyFeb'][$i];
$Mar = $_POST['qtyMar'][$i];
$Apr = $_POST['qtyApr'][$i];
$May = $_POST['qtyMay'][$i];
$Jun = $_POST['qtyJun'][$i];
$Jul = $_POST['qtyJul'][$i];
$Aug = $_POST['qtyAug'][$i];
$Sep = $_POST['qtySep'][$i];
$Oct = $_POST['qtyOct'][$i];
$Nov = $_POST['qtyNov'][$i];
$Dec = $_POST['qtyDec'][$i];
$Total = $_POST['Totalqty'][$i];
$update = "UPDATE FCAST SET
Year='$Year',
Jan=replace('$Jan',',',''),
Feb=replace('$Feb',',',''),
Mar=replace('$Mar',',',''),
Apr=replace('$Apr',',',''),
May=replace('$May',',',''),
Jun=replace('$Jun',',',''),
Jul=replace('$Jul',',',''),
Aug=replace('$Aug',',',''),
Sep=replace('$Sep',',',''),
Oct=replace('$Oct',',',''),
Nov=replace('$Nov',',',''),
`Dec`=replace('$Dec',',',''),
Total=replace('$Total',',','')
WHERE
FcastID='$FcastID'";
mysqli_query($link, $update);
Without seeing your code, it is difficult to say. Something I have used in the past that works well is the following:
PHP:
foreach($_POST as $key => $value) {
//... $key is name of field, $value is the value
}
This goes through each individual field in the submitted form and reads the value in each. I've used this exact script for dynamically-created forms, and it works great. You have to be careful, though, if you use the same name for different fields, the values will be stored as arrays.
EDIT
HTML:
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
JavaScript:
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
It isn't all that important to know how the JavaScript code works. All you need to know is that clicking on the "Add" button will duplicate the field and clicking on "Remove" will remove the most recently added field. Try it out at the link provided.
PHP:
This is where the magic happens…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
Looks easy enough, right?
This PHP code is within the same file as the form, so first we check to see if the form has been submitted by checking for the name of the submit button if(isset($_POST['submit'])){…}.
If the form has been submitted, go through each submitted item foreach($_POST as $name => $item){…}.
The submit button counts as one of the fields submitted, but we aren't interested in storing that value, so check to make sure the value you are reading in is not from the submit button if($name != 'submit'){…}.
Finally, all the fields within this form have the same name field_name[]. The square brackets are used for multiple items that share the same name. They are then stored in an array. Read through each item within that array for the length of the array for($m=0; $m < sizeof($item); $m++){…} and then do what you'd like with each value. In this case, I've just printed them to the screen echo ($name.' '.$item[$m].'<br>');
Below are a couple screen-shots of the page…
Before submitting the form:
After submitting the form:
You can go to the page and view the code (right click -> View Source), but the PHP will not show up in the source. I assure you that all the PHP used for this is shown above - just the few lines.
If each item has a completely unique name (which you can achieve via JavaScript when adding fields), then you will not need to loop through the array of values (i.e. will not need for($m=0; $m < sizeof($item); $m++){…} block). Instead, you'll likely read the value using simply $item. If you name your fields with the square brackets (i.e. field_name[]), but only have one of that field, then reading a singular value may require $item or $item[0]. In that case you'll just have to test it and see. Some field types behave differently than others (i.e. input, text area, radio buttons, etc).
The Whole Thing
Here is the entire code for index.php - you can just copy and paste it and run it on your own server. Just make sure to change the name of the file in the action attribute <form> tag…
<?php
if(isset($_POST['submit'])){
foreach($_POST as $name => $item){
if($name != 'submit'){
for($m=0; $m < sizeof($item); $m++){
echo ($name.' '.$item[$m].'<br>');
}
}
}
}
?>
<html>
<head>
<script type="text/javascript" src="../scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<form method="post" action="index.php">
<div>
<div>
<p>
<label class="reg_label" for="field_name">Item:</label>
<input class="text_area" name="field_name[]" type="text" id="testing" tabindex="98" style="width: 150px;"/>
</p>
</div>
</div>
<input type="button" id="btnAdd" value="Add" class="someClass1"/>
<input type="button" id="btnDel" value="Remove" class="someClass2" disabled/><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
<script>
var j = 0;
$(document).ready(function () {
$('.someClass1').click(function (e) {
var num = $(this).prev().children().length;
var newNum = new Number(num + 1);
var newElem = $(this).prev().children(':last').clone().attr('id', 'input' + newNum);
if(newElem.children().children().last().hasClass('otherOption')){
newElem.children().children().last().remove();
}
newElem.children().children().each(function(){
var curName = $(this).attr('name');
var newName = '';
$(this).attr('id', 'name' + num + '_' + j);
j++;
});
newElem.children().children().each(function(){
$(this).removeAttr('value');
});
$(this).prev().children(':last').after(newElem);
$(this).next().removeAttr('disabled');
});
$('.someClass2').click(function (e) {
var num = $(this).prev().prev().children().length;
$(this).prev().prev().children(':last').remove();
if (num - 1 == 1) $(this).attr('disabled', 'disabled');
});
});
</script>
</html>