I did a little form with jQuery, that when a button is clicked, it adds a new input with a name.
The jQuery I add to the page:
<script>
$(document).ready(function() {
var i = 2;
$("span").click(function() {
$("#add").before("<tr><td>Name</td><td><input type='text' name='name-"+i+"' /></td></tr>");
$("#numper").val(i);
i++;
});
});
$("#numper").val(i) is an hidden input to know how many times I added an input.
When I check the console and Elements (F12 in Chrome) the fields are added, and the hidden one is changed correctly, but when I try to obtain the values with PHP, it says that the added inputs are undefined.
for($i = 1; $i <= $_POST['numper']; $i++) {
echo $_POST['name-'.$i];}
If you can help me to sort this out, I would be very grateful!
Thanks!
I would simply approach your requirements in a different way, name all your inputs so PHP reads them as an array like so:
<input name="name[]" ..... />
PHP:
foreach($_POST['name'] as $index => $input_value) {
....
}
Please check if below code helps you.
<html>
<head>
<script type='text/javascript' src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#addbutton').click(function() {
var i = parseInt($('#numper').val()) + 1;
$('#table').prepend("<tr><td>Name</td><td><input type='text' name='name-"+i+"' /></td></tr>");
$('#numper').val(i);
});
});
</script>
</head>
<body>
<form method='post' action='<?php echo $PHP_SELF;?>'>
<table>
<tr>
<td>
<input type='button' id='addbutton' value='Add new input box' />
</td>
</tr>
</table>
<table id='table'>
<tr>
<td>Name</td>
<td>
<input type='text' name='name-1' />
</td>
</tr>
<tr>
<td>
<input type='hidden' id='numper' name= 'numper' value='1' />
<input type='submit' value='submit' />
</td>
</tr>
</table>
</form>
</body>
<?php
for ( $i = 1; $i <= $_POST['numper']; $i++ ) {
echo $_POST['name-' . $i] . '<br>';
}
?>
In Javascript you have variable i = 2. So, your first input will have a name "name-2".
In PHP, you have for loop with variable $i = 1. So it will try to get $_POST['name-1'].
So, it will give error for undefined.
for the jquery part, you can write this
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append("<input name='whatever' type='text' class='whatever'>");
});
});
if you want the php part, then notify me
Related
I use jquery append for more fields in CI. But Don't know How to to insert multi value into the Db. Please help me.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$tr="<tr><td><input type='input' name='title' /></td><td><textarea name='text'></textarea></td></tr>";
$("#btn2").click(function(){
$("#tb").append($tr);
});
});
</script>
<?php echo validation_errors(); ?>
<button id="btn2">add New</button>
<?php echo form_open('welcome/create'); ?>
<table id="tb" width="100%">
<tr>
<td>Title
</td>
<td>Text
</td>
</tr>
</table>
<input type="submit" name="submit" value="Create news item" />
</form>
Try this
Use [] with the name attribute of an input field
$tr = "<tr><td><input type='input' name='title[]' /></td><td><textarea name='text[]'></textarea></td></tr>";
This will take all the values as an array from input field having the same name attribute
Make You input/textarea field as array:
<tr><td><input type='input' name='title[]' /></td><td><textarea name='text[]'></textarea></td></tr>
In php controller:
//Load model
//Pass Post data to model function
$this->model_name->function_name($_POST);
In php model:
function_name($data)
{
$name_arr = $data['name'];
$text_arr = $data['text'];
for($i=0;$i<count($name_arr);$i++)
{
//Insert query with values like $name_arr[$i],$text_arr[$i];
}
}
Note: Still you are not able to understand then go through CI Tutorials.
I have html table generated via ajax. And last column on this table contains button. My question is what is the best practice to submit these rows (only one at time. I need use this method to amend records).
Is it worth to wrap each row with
<form>
<input type="hidden" value="hidden value">
<input type="submit">
</form>
Or people using something difference? Reason why i'm asking for is because i'm worry about very long list example 1k rows or 10k rows (that means i will have 1k or 10k forms on a page).
You can just use a hyperlink (which you can style to look like a button using CSS if you want). e.g:
Edit
where the value you give as the "id" parameter is the primary key of the record in that row.
Then in edit.php look for the id value using $_GET["id"] and fetch the appropriate record from the DB.
As Progrock advises, a form element may only be used "where flow content is expected" (i.e. not as a direct child of table or tr).
HTML 5 introduces a form attribute as a workaround:
<form id="row_1">
<input type="hidden" name="id" value="pk1">
</form>
<form id="row_2">
<input type="hidden" name="id" value="pk2">
</form>
<table>
<tr>
<td> <input type="text" name="attribute1" form="row_1"> </td>
<td> <input type="submit" form="row_1"> </td>
</tr>
<!-- and so on for each row -->
</table>
It has been brought to my attention that in this case, there is no direct user input being submitted, but only generated contents.
Well, then the solution is even simpler:
<table>
<tr> <td>
<form id="row_1">
<input type="hidden" name="id" value="pk1">
<input type="hidden" name="attribute1" value="whatever">
<input type="submit">
</form>
</td> </tr>
<!-- and so on for each row -->
</table>
I thought I'd have a go without form elements, working with editable table cells. Within each row you provide a button. And when you click it, an ajax post is made of the cell values.
You could have a non js fall back where the save button is replaced for an edit button that takes you to another page with a single form.
Forgive my JS.
I have the session storage in there just to check the concept.
<?php
session_start();
var_dump($_SESSION);
$data = array(
23 => ['triangle', 'green', '2'],
47 => ['square', 'red', '3'],
17 => ['pentagon', 'pink', '4']
);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Save state here
$_SESSION['submission'] = $_POST;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
$('button').click(function() {
// Get all table cells in the buttons row
var $cells = $(this).closest('tr').find('td[contenteditable="true"]');
var jsonData = {};
$.each($cells, function() {
jsonData[get_table_cell_column_class($(this))] = $(this).text().trim();
});
jsonData['id'] = $(this).attr('id');
$.post('',jsonData, function() {
alert('Saved.');
});
});
function get_table_cell_column_class($td)
{
var $th = $td.closest('table').find('th').eq($td.index());
return $th.attr('class');
}
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th class="shape">Shape</th>
<th class="colour">Colour</th>
<th class="width">Width</th>
<th>Ops</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $row) { ?>
<tr>
<?php foreach($row as $field) { ?>
<td contenteditable=true>
<?php echo $field ?>
</td>
<?php } ?>
<td>
<button id="<?php echo $key ?>">Save</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
You can use the following
<table id="YourTableId">
...
<tr data-id="yourrowId">
<td class="col1"> value1</td>
<td class="col2"> value2</td>
<td class="col3"> value3</td>
<td class="actions">
Submit
</td>
</tr>
....
</table>
your javascript code will be like
$(document).ready(function (){
$('#YourTableId a').off('click').on('click',function(e){
e.preventDefault();
var tr = $(this).closest('tr')
var data={ // here you can add as much as you want from variables
'id' : tr.data('id), // if you want to send id value
'col1': tr.find('.col1').text(),
'col2': tr.find('.col2').text(),
'col3': tr.find('.col3').text(),
};
$.ajax({
method: 'post',
url: 'your url goes here',
data: data,
success: function(result){
// handle the result here
}
});
});
});
Hope this will help you
I have a problem with checkbox array
this is my code
<?php
include('config.php');
if(isset($_POST['submit']))
{
for($x = 0;$x <= 5;$x++)
{
if(isset($_POST['check'][$x]))
{
echo "THERE IS A VALUE<br>";
}
else{
echo "EMPTY<br>";
}
}
}
?>
<html>
<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input type='checkbox' name='check[]' />Never Expired</div>");
});
});
</script>
</head>
<body>
<form enctype="multipart/form-data" action="" method="POST">
<div id="text">
<input type="checkbox" name="check[]" />Never Expired<br>
</div>
<input type="button" id="add-file-field" name="add" value="Add input field" />
<input type="submit" value="Upload File" name="submit" id="submit" />
</form>
</body>
</html>
in here i make example i create 5 checkbox
Checkbox1
Checkbox2
Checkbox3
Checkbox4
Checkbox5
and when i check Checkbox3
the output result is
THERE IS A VALUE
EMPTY
EMPTY
EMPTY
EMPTY
I want the result is like this
EMPTY
EMPTY
THERE IS A VALUE
EMPTY
EMPTY
how to make it like that ? please help me
You need to add the key to the array
<input type="checkbox" name="check[0]" />
and
var num = 1;
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input type='checkbox' name='check["+num+"]' />Never Expired</div>");
num++;
});
Checkboxes that are not checked are not sent to the server by the browser, and hence are not in the $_POST['check'] array. This is why THERE IS A VALUE always comes first.
You can see this for a guide in the future...
http://www.html-form-guide.com/php-form/php-form-checkbox.html
Your problem is , you just check that is is set. You must check thier value..
Fix your html form like this
<input type="checkbox" name="check" value="1"> checkbox1</input>
"----do the same---------------------------"2""---------2------->"//do this until you get your five checkbox
Then on php
<?php
include('config.php');
if(isset($_POST['submit']))
{
for($x = 0;$x <= 5;$x++)
{
if($_POST['check']==strval($x))
{
echo "THERE IS A VALUE<br>";
}
else{
echo "EMPTY<br>";
}
}
}
?>
Hope it works
PS. If anyone see errors please edit it.
Hope this is work
add
<input type="checkbox" name="check[0]" />
then
edit this
var x = 1;
$("#add-file-field").click(function(){
$("#text").append("<div class='added-field'><input type='checkbox' name='check["+x+"]' />Never Expired</div>");
x++;
});
then simple php code
if(isset($_POST['submit']))
{
// $x = cout($_POST['check']);
for($x = 0;$x <= 5;$x++)
{
if(strlen($_POST['check'][$x])>1)
{
echo "THERE IS A VALUE<br>";
}
else{
echo "EMPTY<br>";
}
}
}
thanks
I have a table there is showing some values. In each row there is a Order_ID and a button.
How can i get my value in $Order_ID to show (alert) when clicking on a button?
<tbody>
<?php
foreach($menuextra_result as $transaction)
{
?>
<tr>
$order_id = isset($transaction['order_id'])?($transaction['order_id']) :"";
?>
<?php if($order_id){ ?>
<td><div id="orderID"><?= $order_id ?></a></td>
<?php } else {?>
<td><div ><span style="color:red">MANGLER</span></td>
<?php }?>
style="color:red">MISSING</span></td>
<?php }?>
//There's more here, but did not bother to show it, because it was irrelevant.
<td><input type="submit" onclick="getElementById" value="Yes "></td>
<?php }
?>
</tr>
<?php
}
?>
</tbody>
This is how i tried
<script type="text/javascript">
function getElementById()
{
el = document.getElementById('order_id');
alert(el);
}
</script>
But when clicking on a button, nothing happens
table.php
//assuming you have done you loop work
<table>
<tr>
<td>
<?php echo $row['name']?>
</td>
<td><input type="button" value="click me" onclick="clickMe(<?php echo $row['id']?>)" /></td>
</tr>
</table>
clickme unction is like this
function clickMe(id) {
alert(id);
}
You will pass one parameter to clickMe() function and the parameter is id
First of all, don't use id as you have more than one such element. You can use class instead:
<div class="orderID"><?= $order_id ?></div>
Also fixed invalid HTML you got, closing tag for <div> is </div> and not </a>.
Second, change the click to send the button to the function:
<input type="submit" onclick="FindOrder(this);" value="Yes " />
And finally this function should do the trick: (by searching for "brother" div)
function FindOrder(oButton) {
var oRow = oButton.parentNode;
while (oRow && oRow.tagName.toLowerCase() !== "tr")
oRow = oRow.parentNode;
var arrDivs = oRow.getElementsByTagName("div");
var orderDiv = null;
for (var i = 0; i < arrDivs.length; i++) {
if (arrDivs[i].className === "orderID") {
orderDiv = arrDivs[i];
break;
}
}
if (orderDiv != null) {
var orderNumber = orderDiv.innerHTML;
alert("order is " + orderNumber);
} else {
alert("order not found");
}
}
Live test case.
You'll need to print the $order_id to your HTML somewhere. You could use hidden input:
<input name="order_id" id="order_id" value="<?php echo $order_id; ?>">
Then you can submit form or grab the value.
You can't getElementById from you web page if it does not exist.
So solution is simple, just add an hidden input element on your table. You can get the id from your script.
<tbody>
<?php
foreach($menuextra_result as $transaction)
{
?>
<tr>
<?php
$order_id = isset($transaction['order_id'])?($transaction['order_id']) :"";
?>
//There's more here, but did not bother to show it, because it was irrelevant.
<td>
<input type="hidden" name="order_id" id="order_id" value="<?php echo $order_id;?>">
<input type="submit" onclick="getElementById" value="Yes "></td>
<?php }
?>
</tr>
<?php
}
?>
</tbody>
I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table:
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
<tr>
<td>
<input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>
<?php
}
?>
This resolves to something like this:
<tr>
<td>
<input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>
Notice the data hash attribute is different for each button. I want to process this button with my jquery code:
$(".play").click(function(){
var camerahash = $('input').data('hash');
console.log($('input').data('hash'));
});
No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5. Any help is appreciated.
$('input').data('hash') gives you the data attribute of the first input in the selection use $(this).data('hash') to get the data attribute of the currently clicked input
You need to specify which input element to read.
Try something like:
$(".play").click(function(){
$this = $(this);
var camerahash = $this.data('hash');
console.log($this.data('hash'));
});
You are always calling the first object of .play. This would be a correct way:
$('.play').on('click', function(){
var camerahash = $(this).data('hash');
});
You could always grab them by using the .attr(data-hash) html5 attribute.
Try:
$('.play').on('click', function() {
var _hash = $(this).attr('data-hash');
console.log(_hash);
});
Your selector will return the first one that it comes to. Use this instead
<script>
$("input.play").click(function() {
alert($(this).data('hash'));
});
</script>