How can i edit my ingredients through array of input fields - javascript

How can I make a form like posting my ingredient but in the way that I will only edit the posted ingredients
this is the Javascript of the button
<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; //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 class="col-md-6 div-' + x + '"><input type="text" class="form-control" name="mytext[]" required/></div>'); //add input box
$(wrapper).append('<div class="col-md-6 div-' + x + '"><input type="text" class="form-control" name="mytext2[]" required/>Remove</div>');
}
});
$(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
e.preventDefault();
$(".div-" + $(this).attr("div-id")).remove();
x--;
})
});
</script>
This is the form of inserting the ingredients
<div class="input_fields_wrap">
<div class="col-md-6">
<h5>Notes/Scaling (quantity, additional info)</h5>
<input type="text" class="form-control" name="mytext2[]" required>
<br>
</div>
<div class="col-md-6">
<h5>Name of Ingredient:</h5>
<input type="text" class="form-control" name="mytext[]" required>
<br>
</div>
<br>
</div>
<div class="col-md-12">
<button class="add_field_button button loading-pulse">Add More Fields</button>
</div>
this is how i implode it
$ingredient_name =implode("^",$_POST["mytext"]);
$ingredient_value = implode("^", $_POST["mytext2"]);
this is how i explode it
$ingredient_name = explode("^",$ingredient_name);
$ingredient_value = explode("^", $ingredient_scale);
$ingredients = array_combine($ingredient_value,$ingredient_name);
this is how i loop it
<table class="table-bordered" style="width:90%;">
<th style="text-align:center;">Ingredient Scale</th>
<th style="text-align:center;">Ingredient Name</th>
<?php
foreach($ingredients as $amount => $name)
{
?>
<tr>
<td style="margin:left:10px;"><?php echo "{$amount}"?></td>
<td style="margin:left:10px;"><?php echo "{$name}"?></td>
</tr>
<?php
}
?>
</table>
for example in the database
there are 2 columns,
recipe_ingredient_value recipe_ingredient_name
1/4,1/2,1 cup sugar,meat,water
i want it to extract into an input fields that i can edit (rename, add ,delete)
for example
1/4 sugar remove
1/2 meat remove
1 cup water remove
add more fields

You should print all values in a form inside the loop and then you need some sort of "Save" button and a route ready to receive new values. This route should be a php script, for example, that would loop through your new data and perform an update.
I'm suggesting you're writing PHP framework-free, standalone app. That way you have to think about a lot of things, which is good for you if you are a beginner.
Now back to the point:
It would be great if you could print a hidden id of a database row, somewhere inside the loop:
<tr>
<td><input type="text" name="recipe_id" value="<?php echo $amount; ?> /></td>
<td><input type="text" name="recipe_id" value="<?php echo $name; ?> /></td>
<input type="hidden" name="recipe_id" value="<?php echo $recipe_id; ?> />
</tr>
Remember that route that collects and updates the data? Let's call it "update-script.php".
The update-script.php should perform a check for every field in a $_GET or $_POST variable, to see if that value has been changed. If yes, the row should be updated, if not, then it should be skipped. It's up to you to create the logic for this.
Furthermore, I noticed that your javascript code needs some adjustments. I will only hint one thing that kinda sticks out:
$(add_button).click(function(e){
For the sake of your future work, please use "on" method that is described here:
http://api.jquery.com/on/
Trust me, when you start working with DOM elements, changing the DOM and adding new events, this will be your savior.
Good luck!

I think the easiest way would be to structure your inputs like this.
<tr>
<td>
<input type="hidden" name="recipe[<?= $recipe_id; ?>][id]" value="<?php echo $recipe_id; ?>" placeholder="value"/>
<input type="text" name="recipe[<?= $recipe_id; ?>][value]" value="<?php echo $value; ?>" placeholder="name"/>
</td>
<td><input type="text" name="recipe[<?= $recipe_id; ?>][name]" value="<?php echo $name; ?>" /></td>
<td><input id="recipe_<?= $recipe_id; ?>" type="checkbox" name="recipe[<?= $recipe_id; ?>][delete]" value="1" /><label for="recipe_?= $recipe_id; ?>">Delete</label></td>
</tr>
Where $recipe id is the row id. Then your javascript would add more rows like
<tr>
<td><input type="text" name="recipe[2][value]" value="" placeholder="value" /></td>
<td><input type="text" name="recipe[2][name]" value="" placeholder="name" /></td>
<td></td>
</tr>
Then in your php you can see the array will be formatted nicely into arrays of recipes like:
array(
array(
'name' => 'Pie'
'value' => 2
'recipe_id' => 1
),
array(
'name' => 'Deleted Pie'
'value' => 2
'recipe_id' => 2
'deleted' => 1
),
array(
'name' => 'New pie'
'value' => 2
),
)
Then using the deleted key you can check if you need to delete the Database row and if it has the recipe_id key then it might need to be updated. If it doesn't have the recipe key then its a new recipe.

Related

Get the values of while loop using button with js

How can I get the values in the while loop using button with js?
<?php
while ($row = mysqli_fetch_array($query))
{
echo '<input type="text" name="sample" value="'.$row['sample'].'">';
}
?>
Thanks
You can get the value of textbox when you click on a button.
<input type="text" name="sample[]" value="abc" class="valueInput">
<input type="text" name="sample[]" value="xyz" class="valueInput">
<input type="text" name="sample[]" value="pqr" class="valueInput">
<input type="button" class="getValue" value="Get Value">
Note: I have set the static input box you can make it dynamic but make sure please add the class as valueInput.
Jquery Code.
$(document).on('click','.getValue',function(){
var valArr = [];
$(".valueInput").each(function(){
valArr.push($(this).val());
});
console.log(valArr);
})
The name of the input field should indicate an array with [].
<form action="action.php" method="POST">
<?php
while ($row = mysqli_fetch_array($query)){
echo '<input type="text" name="sample[]" value="'.$row['sample'].'">';
}
?><input type="submit">
</form>
action.php: (Processes the data on submit)
<?php
echo "<pre>";
print_r($_POST['sample']);
echo "</pre>";

could not get input field value in jquery

I am creating an input field using foreach loop like this
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
$data is Array
(
[0] => Array
(
[asset_id] => abc-02
[asset_name] => Freezer
)
[1] => Array
(
[asset_id] => xyz-01
[asset_name] => Refrigerator
)
[2] => Array
(
[asset_id] => 300001
[asset_name] => Generator
)
)
and in javascript, I am trying to get the value using this code but it always alerts first value of the input.
<script type="text/javascript">
$(document).ready(function () {
var typename = $('#typename').val();
alert(typename);
});
</script>
i have to disable this input field when value is 'Generator'
Try:
$('[readonly].form-control').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="5">
</td>
.val() called once will always produce only one value; .val() docs:
Get the current value of the first element in the set of matched elements .
HTML id attribute is supposed to be unique, try this instead.
<?php
$count = 0;
foreach($data as $key=>$val) {
?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_<?php echo $count++; ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
It'll produce different id attributes for each input, typename_0, typename_1, ..., typename_n, allowing you to for example:
$('[id^="typename_"]').each(function(i,e) {
console.log($(e).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" id="typename_0" type="text" value="1">
<input readonly class="form-control" name="model[]" id="typename_1" type="text" value="2">
<input readonly class="form-control" name="model[]" id="typename_2" type="text" value="3">
<input readonly class="form-control" name="model[]" id="typename_3" type="text" value="4">
<input readonly class="form-control" name="model[]" id="typename_4" type="text" value="5">
</td>
Where [id^="typename_"] is CSS attribute selector, matching all elements with an id attribute starting with typename_.
You should never use same id for several elements.
Update you code for debug, and you'll see that you have an array:
<script type="text/javascript">
$(document).ready(function () {
var typename = $('[name="model[]"]')
.toArray().map(e => e.value);
alert(JSON.stringify(typename));
});
</script>
You should update your php, to set different id for each element drawn in a cycle, i.e:
<?php $i=1;foreach($nomatter as $a) {?>
<input id="typename_<?=$i++?>">
<?php } ?>
So you'll be able to address eash input separately:
var typename = $('#typename_1').val();
Use class instead of duplicate id like this.
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control clsValue" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery loop your class and get value using this instant..
$(document).ready(function () {
$( ".clsValue" ).each(function( index ) {
var typename = $(this).val();
alert(typename);
});
});
try this ,
this will call alert function for each input with form-control class
$(document).ready(function () {
$(".form-control").each(function(){
alert($(this).val());
})
});
Set class="typename" instead of id="typename":
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control" name="model[]" class="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
You can get values like this:
<script type="text/javascript">
$(document).ready(function () {
var typename1 = $('.typename')[0].val();
var typename2 = $('.typename')[1].val();
alert(typename1);
});
</script>
there is a big mistake in your code, you can't use same id for multiple input fields, when the loop run multiple input fields will create with same id, you have to make the id dynamic, you can make the id dynamic by appending some unique value to the id each time you create an input field the use that id to fetch the data.
Please let me know if you need sample code.
pure js approach;
replace id with class;
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control typename" name="model[]" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
js
window.onload = alertTypeNames();
function alertTypeNames() {
document.getElementsByClassName('typename').map((inputTag) => {
alert(inputTag.value);
return true;
});
}
you fired with your id that's why it's fired only first element value.
this is how you can do that with your current code
$(document).ready(function () {
$('input[name="model[]"]').each(function(){
alert($(this).val());
});
});
However, it's highly recommended that you have to used unique id for each element otherwise used class to do what you want to.
The id attribute specifies a unique id for an HTML element it's not a good practice to use same ID more than once on a page, instead of ID attribute loop the class attribute in jquery.
<script type="text/javascript">
$(document).ready(function () {
$('.common-class').each(function() {
alert($(this).val());
});
});
</script>
<?php $incr_var = 1; ?>
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1">
<input readonly class="form-control common-class" name="model[]" id="typename<?php echo $incr_var ?>" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
Element id should be unique. And try it inside on event because dynamically adding elements will not grab ready state.
http://api.jquery.com/live/
<?php foreach($data as $key=>$val) { ?>
<td class="table-td-1 status">
<input readonly class="form-control" name="model[]" id="typename" type="text" value="<?php echo $val['asset']; ?>">
</td>
<?php } ?>
And in jquery
$(document).on('change','.status',function(){
var $status = $(this).val();
if($status == 'not_working'){
$(this).closest('tr').find('.reason').removeAttr('disabled');
}
});
reason is class you have to give which input field you want to disable

If input has a value, add it to a variable in php?

So I am new to PHP and I'm trying to create a spreadsheet-like program. I have a form with columns and cells, and the user can add and delete rows (using Javascript). Once the data in the cells has been entered, the user can save the sheet and the data is displayed in the same cells. I have been able to get this to work, but I have to manually check each input and put the data into a variable, and then display that variable in the cells. I'm trying to find a way to automatically get all the data from the cells, and store each one into a variable with incrementing id's. The problem is, I want the user to be able to add infinite rows with infinite cells; so how would I get all the data if I don't know how many cells there will be?
I don't know if I am even going about this the right way, so I'm hoping someone can at least point me in the right direction. Like I said, I'm new to PHP so I may be completely ignorant and thinking about this completely wrong.
Note: I'm not looking for a copy/paste answer, but more of guidance on the theory of accomplishing this. Of course the plan is to eventually store all the inputted data into a MySQL table, and then display it on the screen from there; but, I'm first trying to solve this problem.
This is what I have so far:
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$a1_post = $_POST['a1'];
$a2_post = $_POST['a2'];
$a3_post = $_POST['a3'];
$b1_post = $_POST['b1'];
$b2_post = $_POST['b2'];
$b3_post = $_POST['b3'];
}
HTML
<form class="table-form" method="post" action="">
<div class="column" id="column-a">
<p>Antigen</p>
<input class="cell" id="a1" type="text" name="a1" value="<?php echo $a1_post; ?>">
<input class="cell" id="a2" type="text" name="a2" value="<?php echo $a2_post; ?>">
<input class="cell" id="a3" type="text" name="a3" value="<?php echo $a3_post; ?>">
</div>
<div class="column" id="column-b">
<p>Start Size</p>
<input class="cell" id="b1" type="text" name="b1" value="<?php echo $b1_post; ?>">
<input class="cell" id="b2" type="text" name="b2" value="<?php echo $b2_post; ?>">
<input class="cell" id="b3" type="text" name="b3" value="<?php echo $b3_post; ?>">
</div>
<input class="submit" type="submit" value="Save">
</form>
As long as you use a naming convention you can just iterate over $_POST and update your table as necessary...
To simplify this process name your inputs with square brackets:
<input class="cell" id="c1" type="text" name="c[0]" value="<?php echo $c[0]; ?>" />
<input class="cell" id="c2" type="text" name="c[1]" value="<?php echo $c[1]" />
When you submit your data will already be in an array per row:
$_POST would equal
[
'c' => ['c1 value', 'c2 value']
];
So you can interact with your dataset by iterating over $_POST:
foreach ($_POST as $rowName => $row) {
//$row equals ['c1 value', 'c2 value']
}

Input Clear Button for Textareas

Updating what has worked and the current issue:
I have 1 clear button beside each field. Each clear button works. The problem is after clearing both fields, when selecting another file from the dropdown, it only populates the text field with the file name and does not display the contents in the second textarea until refreshing the page.
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div><font color=#2F6054>Below is the list of your saved codes. To view or delete your codes, select it from the list.</font></font></div><p>
<select size="1" name="CodeList" id="CodeList">
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo "<option>" . $file . "</option>";
}
}
?>
</select><p>
<font color=#2F6054><font size=4>Enter Codes Here</font></font>
<form method="post" action="/evo/avsaveprocess.php">
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<table width="100%">
<tr>
<td>Description:</td>
<td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
<td><button type="reset" class="clear-tn" value="Clear"></button></td>
</tr>
<tr>
<td valign="top">Code:</td>
<td>
<textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Save" />
function code:
<script>
$(function(){
$('.clear-btn').on('click',function(e){
e.preventDefault();
$(this).closest('tr').find('input[type="text"],textarea').val('');
});
});
</script>
Edited to show current working code
Editing to show on change script at the bottom of my form for the dropdown
<script>
$(document).ready(function(){
// apply a change event
$('#CodeList').change(function() {
// update input box with the currently selected value
$('#CodeName').val($(this).val());
$.get( '<? echo $directory ?>' + '/' + $('#CodeName').val(), function( data ) {
$( "#CodeValue" ).val( data );
});
});
});
</script>
You can try the below link, it works without javascript or jquery. Just simple HTML
<form>
<input type="reset" />
<input type="submit" />
<input type="text" />
<textarea></textarea>
</form>
Here is the demo
Change type attribute "button" to "reset".
<button type="reset" class="clear-btn">Clear</button>
Try below working fiddle as per your requirement.
http://fiddle.jshell.net/t7gkr8rk/1/

Ajax oncheck event to search item in a table

modify search
<div class="highlight_2"> <img src="images/collapse2.jpg" width="151" height="28" border="0" />
<div id="inox">
<input type="checkbox" value="kar_kar" />kar and kar <br />
<input type="checkbox" value="bala_bala" />bala and bala <br />
<input type="checkbox" value="jena_jena" />jena and jena <br />
<input type="checkbox" value="senapati" />senapati <br />
<input type="checkbox" value="sarangi_sarangi" />sarangi and sarangi <br />
<input type="checkbox" value="sairam" />sairam <br />
<input type="checkbox" value="madhumita" />madhumita <br />
<div class="clear"></div>
</div>
search table
<tr>
<td>Sl No.</td>
<td>Bus Operator</td>
<td>Bus No. </td>
<td>Departure Time</td>
<td>Arrival time</td>
</tr>
<?php
$count=0;
$s=mysql_query("SELECT * FROM bus_detail where source_point='$_SESSION[source_point]' && destination_point='$_SESSION[destination]'");
while($row=mysql_fetch_array($s))
{
$count+=1;
?>
<tr>
<td><?php echo $count; ?></td>
<td><input name="bus_name" type="text" value="<?php echo $row['bus_name'];?>" class="input_box" /> </td>
<td><?php echo $row['bus_no'];?></td>
<td><?php echo $row['departure_time'];?></td>
<td><?php echo $row['arrival_time'];?></td>
</tr>
<?php }?>
I want to use my modify search in a ajax oncheck event.. In the picture i ve given ,this is my search list apper but if i check a check box name "jena and jena" from the bus operator div, it should only show me the result of jena and jena , the other two, i want to hide them .. I want to modify my search according to my bus operators(after checking a check box from the operator list).. It ll be a great help .. Thank you
My database :
Sorry i miss understood your question. I think you are looking to hide / show html table rows when user selects list. If this is what you are look, Then please check by code below.
Note: You can tweak this code to get better performance and result
Fiddle: http://jsfiddle.net/663Mx/2/
$("#inox input[type='checkbox']").live('click', function () {
// STORE CHECKED VALUED IN ARRAY
var cv = [];
$("#inox input[type='checkbox']:checked").each(function () {
cv.push($(this).val());
});
// SHOW / HIDE ROWS BY DEFAULT
if(cv.length <= 0) {
$("#mytab tbody").find("tr").show();
} else {
$("#mytab tbody").find("tr").hide();
var rows = $("#mytab tbody").find("tr");
var data = $(this).val();
// LOOP THROUGH AND SHOW ONLY CHECKED ROWS
rows.each(function (i, v) {
for (var n=0; n<cv.length; n++) {
var check = $(v).find('td').filter(":contains('" + cv[n] + "')");
check.parent('tr').show();
}
});
}
});

Categories