Add New Field to Form and Save it to database - javascript

First Problem:
I want to add new field with a button, so everytime the button is clicked it will create new field. I try using Jquery but I am new in this kind of programming language, can someone help me? Am I doing it right?
HTML
<table>
<tbody>
<tr>
<td>
<?php
$n = 0;
$c = 0;
echo "<Select>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?>
</td>
<td><input type="text"></td>
</tr>
</tbody>
</table>
<center><button id="addrow">Add Row</button></center>
Script
<script>
$(document).ready(function(){
$("#addrow").click(function(){
consoloe.log("asdasda");
$(tbody).append('<tr><td><?php
$n = 0;
$c = 0;
echo "<Select>";
do{
if($c>10){$n="";}
echo "<option>".$n.$c.":00</option>";
echo "<option>".$n.$c.":30</option>";
$c++;
}while($c<24);
?></td>
<td><input type="text"></td>
</tr>');
});
});
</script>
This is the error I get
This is The form look like
Second Problem:
I think I need to give a name or ID for this field, because I need to save it to a database, can you give me some advice about POST method to insert multiple records with mysqli? How can I loop the insert statement?

One things about your code first: 1. You neeed to also close the "select" element before ""
My advice solution:
Use jQuery to add new field like so
$("#addRow").click(function(){
$(tbody).append('<tr><td><select><option>Test1</option><option>Test2</option></select> </tr></td>);
});
Then to loop through your form before you submit it you can use PHP. All the fields would be in the $_POST[] suberglobal so foreach($_POST[] as $item){ //insert field in DB }
You can also use AJAX to submit the form and iterate over it's fields in jQuery:
$.each("tbody tr td select", function(field){
$.post("yourPHPfile.php", {name:field}, function(data){
//on success handler
});
});
Hope that helps!

You can do this by pure javascript , here is the example
var yourHTML="<td><select>";
yourHTML +="<option>--</option>";
yourHTML +="<option>--</option>";
yourHTML +="</select></td>";
yourHTML +="<td><input type='text'></td>";
function addRow(e){
var tab=e;
var rowCount=tab.rows.length;
var row=tab.insertRow(rowCount);
row.innerHTML=yourHTML;
}
Now call addRow() on click of button
$(document).ready(function(){
$("#addrow").click(function(){
addRow(document.getElementsByTagName("table")[0]);
});
});
LIVE http://jsfiddle.net/mailmerohit5/3outf4vm/

Related

Capture specific row information after calling blur event

Let's say that I have this table with two rows:
<tr>
<td contenteditable="true" data-group1="<?php echo $_GET['group']; ?>" class="no1" id="nom1" name="nom1"><?php echo $item[$i]; ?></td>
</tr>
<tr>
<td contenteditable="true" data-group2="<?php echo $_GET['group']; ?>" class="no2" id="nom2" name="nom2"><?php echo $item[$i]; ?></td>
</tr>
The table is contenteditable which means, I can change the value inside the table. Currently, once the data have been manipulated, the data will be captured once the blur event is called. This is my script:
$(document).on('blur', '.no1', function(){
var group= $(this).data("group1");
var no = $(this).text();
});
$(document).on('blur', '.no2', function(){
var group= $(this).data("group2");
var no = $(this).text();
});
Based on this algorithm, let's say that I have manipulated the data from the first row which is referring to the class = "no1", it will then run this script as shown above:
$(document).on('blur', '.no1', function(){
var group= $(this).data("group1");
var no = $(this).text();
});
However, the number of rows for this table is not fixed. Therefore, this script is not helpful as we defined the function by ourselves based on the number of rows. Is there any way on how we can capture specific row information after calling the blur event so that we do not have to define quite a lot of similar functions.
You can use a common class on your trs and attach a blur event handler on its contenteditable td.
About your data-groupX attributes, just rename them all to data-group :
PHP
<tr class="common"> //Add your class here
<td contenteditable="true" data-group="<?php echo $_GET['group']; ?>" class="no1" id="nom1" name="nom1"><?php echo $item[$i]; ?></td>
</tr>
Javascript
$(document).on('blur', '.common td[contenteditable]', function(){
var group= $(this).data("group");
var no = $(this).text();
});

How to sum up multiple Inputs multiplied by value simultaneously

So, I have This Fiddle where I have a table that has an input and a cost. It also has a bit of jquery.
$( ".total" ).change(function() {
i = 1;
var input001 = document.getElementsByName(i)[0];
var cost001 = document.getElementById("cost" + i);
var total001 = input001.value * cost001.innerHTML;
var num = total001;
var total = num.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "1,");
document.getElementById("printchatbox").value = total;
i++;
});
This code multiplies the first input times the first Item Cost. I would like to find a way to repeat this 45 times (one for each item) without copy and pasting this code 45 times... If that is the only way to do it, I can do that... but I'm hoping to learn something and make my code significantly shorter at the same time. This table is generated by php, I just copied and pasted the html that was generated for the fiddle.
while($row = $result->fetch_assoc()) {
$row['ItemID'] = ltrim($row['ItemID'], '0');
?>
<tr>
<td><input type="number" class="total" name="<?php echo $row['ItemID']?>" value "<?= isset($_POST[$row['ItemID']]) ? htmlspecialchars($_POST[$row['ItemID']]) : "" ?>"></td>
<td><?php echo $row['ItemID']?></td>
<td><?php echo $row['ItemDescription']?></td>
<td id="<?php echo 'cost' . $row['ItemID'] ?>"><?php echo $row['ItemCost']?></td>
<td id="<?php echo 'value' . $row['ItemID'] ?>"><?php echo $row['ItemValue']?></td>
</tr>
<?php
}
?>
</table>
this is the PHP code on the website that creates the table...
this is the first row of the html table.
<tbody><tr>
<td><input class="total" name="1" value="" ""="" type="number"></td>
<td>1</td>
<td>Barrel Wrap 47"x31"</td>
<td id="cost1">39.38</td>
<td id="value1">47.25</td>
</tr>
and here is an image of the first 10 rows of the table.
if I have to change something in there, that is totally fine, I'm just hoping to keep the readability and reduce the redundancy.
Thanks
Here's your updated fiddle: https://jsfiddle.net/737v3qxr/2/
So I've changed a few things:
$( ".total" ).change(function() {
var name = this.name;
var quantity = this.value;
var cost = document.getElementById("cost" + name).innerHTML;
var total = quantity * cost;
items[name] = {cost, quantity}
new_total();
});
when you apply a function/listener to something, the this references the element itself, so you didn't need to do an extra i and i++ with it.
I've also introduced JSON (it's basically a dictionary in any other language), which helps with tracking prices.
Most of the code is just renamed since your logic wasn't actually too far off, just very clumsy and convoluted.
I've also added a new_total function, which doesn't really need to be a function in and of itself, but it's just my preference.
Finally I've added an id to your total to make it easier to track.
<input id="total" type="text" readonly id="printchatbox" name="total">
There's also some weird empty text which I'm assuming refers to your php, but you will have to deal with that yourself.
<input class="total" name="45" value="" ""="" type="number">
You can use the event handler argument as well:
$( ".total" ).change(function(e) {
var cost001 = document.getElementById("cost" + e.target.name);
var total001 = e.target.valueAsNumber * Number(cost001.innerHTML);
var prev = Number(document.getElementById("printchatbox").value);
document.getElementById("printchatbox").value = total001 + prev;
});

How to use Javascript to validate dynamically generated PHP form?

I've created a form using PHP in which the user has to click on a radio button before clicking on the button to submit the form. It looks as follows:
<form name="films" action="showing.php" method="post">
<table id="filmtable">
<tr><th>Title</th><th>Length</th><th>Description</th><th>Poster</th><th>Required</th></tr>
<?php
//Loop through every row returned by $result query to display it in table.
while ($newArray = mysql_fetch_array($result)){
$title = $newArray['title'];
$length = $newArray['length'];
$description = $newArray['description'];
$image = $newArray['image'];
//Echo statements will display query results on screen.
echo "<tr><td>$title</td><td>$length</td><td>$description</td>";
echo "<td><image src=\"$image\"</td>";
echo "<td><input type=\"radio\" id='wanted' name=\"wanted[]\" value='$title'></td></tr>";
}
// if (! array_key_exists($_POST['wanted[0]'], $result)){
// echo "Select it.";
//}
?>
</table>
<input type="submit" onsubmit = 'return validate()' value="Select Film">
</form>
As a validation measure I created the following in Javascript with the aim of preventing the user from submitting the form if they have not selected a radio button:
<script>
function validate(){
var radio = document.getElementById('wanted').checked;
if(radio=="")
{
alert("Please select a film to continue making a booking.");
return false;
}
return true;
}
</script>
The script prevents the user from submitting the form if no selection has been made from the radio boxes as intended. However, it will only allow the form to be submitted if the first radio box is selected. Selecting any button other than this one will cause the submit attempt to fail. What changes should I make to the JS to rectify this situation?
This PHP fetch loop attributes multiple times the same id="wanted" to many radio buttons.
An Id should be unique.... So it's a bad practice.
Remove the id and add a class instead:
echo "<td><input type=\"radio\" class=\"wanted[]\" name=\"wanted[]\" value='$title'></td></tr>";
Then, the use of jQuery saves pain...
Within your submit script:
if(!$('.wanted').prop("checked")){
alert("Please select a film to continue making a booking.");
return;
}
Add this jQuery lib call in your head:
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
EDIT - See comments
Function validate should be this:
function validate(){
var wantedChecked=$(".wanted:checked");
if (!wantedChecked.prop("checked")){
console.log("false");
return false;
}else{
console.log("true");
return true;
}
}
getElementById returns the first element matching the selector. If you just want to verify that any of them were checked, you could do something like:
var anyChecked = document.querySelectorAll('[name=wanted]:checked').length > 0;

javascript/jquery: how to add/remove variables from array depending on whether a checkbox is selected

I'm outputting order addresses for a takeout restaurant: each individual order is output as a table, each table has a checkbox. I want to put the addresses into an array when the .ordercollected checkbox is ticked, and remove it from the array if it is unticked.
At the moment, rather than appending each new address I get each order address on its own in the array, which updates each time I tick the .ordercollected checkbox.
Really new to programming so any help appreciated!
//get the addresses from selected tables
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
$(this).each(function() {
//if checkbox is ticked
if ($(this).is(':checked')) {
//get address from table
var address = $(this).closest('.ordertable').find('.address').text();
//append value of address into activeaddress array
activeaddress.push(address);
};
});
console.log('active address: ', activeaddress);
});
edit to add in the tables I am creating:
<table class="ordertable">
<tr>
<td>
<p>Order #
<?php echo $order_id; ?> —
<time datetime="<?php the_time('c'); ?>">
<?php echo the_time('d/m/Y g:i:s A'); ?>
</time>
</p>
</td>
<td>
<?php echo $order->billing_first_name . ' ' . $order->billing_last_name ?>
</td>
<td>
<?php if ($order->billing_phone) : ?>
Tel.
<?php endif; ?>
</td>
<td>
<p class="address"><?php echo $order->shipping_address_1 . ' ' . $order->shipping_postcode ?></p>
<td/>
<td>
<a class="maps-activate" href="#">Open in Maps</a>
</td>
<td>
<form action="">
<input type="checkbox" class="ordercollected" value="0" />
</form>
</td>
</tr>
</table>
Rather than remake your entire activeaddress array every time a checkbox changes, the best thing to do here would be to add or remove only the selected address when a checkbox changes. To do this activeaddress will have to be available outside of that function. I also think it will be cleaner if you use a JS object instead of an array.
var activeaddress = {};
$('.ordercollected').change(function() {
// get table id
var orderTableID = $(this).closest('.ordertable').attr('id');
// if checkbox is ticked
if($(this).is(':checked')) {
// get address from table
var address = $(this).closest('.ordertable').find('.address').text();
// append value of address into activeaddress object
activeaddress[orderTableID] = address;
} else { // checkbox is NOT ticked
// remove address from object
delete activeaddress[orderTableID];
}
console.log("active address: ", activeaddress);
});
As you can see, this code assumes that each table with class .ordertable has a unique id that can be used as the key in the activeaddress object. This is better than looping over the entire array/object each time because, especially if you have a very big set of orders. If you had included your HTML I would be able to help more, but as the question is this is as far as I can help. Let me know if you have any follow up questions.
A couple of things to note:
Using pascalCase for variable names and class names makes code more readable (e.g. activeAddress instead of activeaddress)
In my opinion, using an object instead of an array is a better way to add and remove a specific item
When asking question on SO, please give as much information as possible, such as including your HTML
Finally some links:
Adding a key value pair to an object
Removing a key value pair from an object
try something like this?
HTML:
<input type="checkbox" class="ordercollected" value="apple" />
<input type="checkbox" class="ordercollected" value="mango" />
JS
$('.ordercollected').change(function() {
var activeaddress = [];
//loop through checkboxes with class .ordercollected
if (this.checked) {
activeaddress.push(this.value);
}
else {
var index = activeaddress.indexOf(this.value);
if (index > -1) {
activeaddress.splice(index, 1);
}
}
console.log('active address: ', activeaddress);
});

php form to javascript

I need to pass the form id to javascript, but always shows the same data.
<script>
$(document).ready(function() {
$('input[name="submit"]').on('click', function(){
var vauid = $( "input[name='uid']" ).val(); alert("\n ID: "+vauid);
return false;
});
});
</script>
<? include "../includes/config.php";
$sql = "select * from table";
$reg = mysql_query($sql);
while($row = mysql_fetch_array($reg)){ ?>
<form action="" method="POST">
<input type="text" name="uid" value="<? echo $row['uid']?>" />
<input type="submit" name="submit" value="Show"/>
</form>
<? }?>
Part of the problem is that you're inserting numerous forms with elements having the same names - that is a bad idea as names are intended to be unique.
Second, when you click you have to reference the currently clicked info:
$(document).ready(function() {
$('input[name="submit"]').on('click', function(e){
e.preventDefault();
var vauid = $(this).prev("input[name='uid']").val();
console.log("ID: "+vauid);
});
});
Here is a working demo.
$(this) will be the clicked button from which we look for the previous input's value. I'm also using preventDefault() to stop the button's default action, rather than returning false.
In addition you should quit using alert() for troubleshooting., use console.log() instead.

Categories