User can create tables and add records to it. When records added another values must be calculated. I tried to do that with jQuery but something is wrong and do not work. Maybe someone can help me and say how to do that.
Part from blade template (full template: https://pastebin.com/Mdq8fCnJ):
#foreach($tables as $table)
#foreach($table->fuelAccountingRecords as $record)
<tr>
<td id="name">{{ $record->name }}</td>
<td id="liters">{{ number_format($record->liters, 2, '.', '') }}</td>
<td id="show_kilograms"></td>
<td id="show_price"></td>
<td>
<input type="hidden" name="record_id"
value="{{ $record->id }}">
<button type="submit" class="btn btn-danger btn-sm"
name="deleteRecord">Trinti
</button>
</td>
</tr>
#endforeach
#endforeach
And jQuery code:
$(document).ready(function () {
var total_kilograms = $('#total_kilograms').val();
$('#show_kilograms').text(total_kilograms);
$('[data-table-id]').on('click', function () {
$('#table-' + $(this).data('table-id')).append(
'<tr class="child">' +
'<td><input type="text" class="form-control" name="name" autocomplete="off" required autofocus></td>' +
'<td><input type="text" class="form-control" name="liters" autocomplete="off" required></td>' +
'<td>-</td>' +
'<td>-</td>' +
'<td><button type="submit" class="btn btn-primary btn-sm" name="saveRecord">Išsaugoti</button></td>' +
'</tr>'
);
});
});
Another jQuery lines I am using to add rows to table where user can add records. I can not get a value from table and then ouput it or calculate. Help me to fix it.
Empty fields must be filled with values
Related
I had a table form where I will add multiple users in table and it has checkboxes. My problem is on the checkboxes.
User 1: ✓ Add, ✓ Edit, ✓ Delete
User 2: ✓ Add, Edit, Delete
Expected Output in Database
Full Name | Permissions
John Doe | ["Add", "Edit", "Delete"]
Jane Doe | ["Add"]
What is inserted in the DB
Full Name | Permissions
John Doe | "Add"
Jane Doe | "Edit"
blade html
<button type="button" id="addUser">Add</button>
<table id="userTable">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Add</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS Code
$("#addUser").click(function () {
t.row.add(['',
'<input class="form-control" type="text" name="fullname[]">',
'<input class="form-control" type="checkbox" name="permissions[]" value="Add" data-parsley-multiple="status">',
'<input class="form-control" type="checkbox" name="permissions[]" value="Edit" data-parsley-multiple="status">',
'<input class="form-control" type="checkbox" name="permissions[]" value="Delete" data-parsley-multiple="status">',
]).draw(false);
});
Controller
public function store(Request $request)
{
foreach($request->fullname as $key=>$insert)
{
$user = [
'fullname' => $request->fullname[$key],
'permissions' => json_encode($request->permissions[$key]),
];
DB::table('users')->insert($user);
}
}
In my code, $request->permissions[$key] is only getting 1 value per permission. How can I get all the checked value of permission in one user row and to be inserted for that user.
Add indexes to your input names, so they are grouped per user:
$("#addUser").click(function () {
var index = $(".user-name-field").length;
t.row.add(['',
'<input class="form-control user-name-field" type="text" name="fullname[' + index + ']">',
'<input class="form-control" type="checkbox" name="permissions[' + index + '][]" value="Add" data-parsley-multiple="status">',
'<input class="form-control" type="checkbox" name="permissions[' + index + '][]" value="Edit" data-parsley-multiple="status">',
'<input class="form-control" type="checkbox" name="permissions[' + index + '][]" value="Delete" data-parsley-multiple="status">',
]).draw(false);
});
In this case i've added a class to the user name field, count these fields to create the index
I want to create a dropdown list from database with javascript.
I am trying to make a dynamic form where I can add multiple rows using "add more" button.
My html form contains an input type text and a drop down list
in html
<form id="add_name" name="add_name">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<select class="form-control" name="nom_ar">
<?php
while ($row2 = $result2->fetch_assoc()){
echo "<option value='".$row2['nom_ar']."'>".$row2['nom_ar']." </option>";
}
?>
</select>
</td>
<td><input type="text" name="name[]" placeholder="insert name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">add more</button></td>
</tr>
</table>
</form>
In the javascript code I added only the input type text and I don't know how to add the dropdown list like the next code shows :
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><select class="form-control" name="nom_ar"><?php while ($row2 = $result2->fetch_assoc()){echo "<option value='".$row2['nom_ar']."'>".$row2['nom_ar']."</option>";} ?></select></td><td><input type="text" name="name[]" placeholder="Ingredient" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
}
How can I do it? My drop down list in js is always empty. I'm struggling as I'm a beginner. where should I put the php code?
Well, this is your JS code
<script type="text/javascript">
$('#add').click(function() {
$("#dynamic_field").append("<tr></tr>");
$.post("server.php", {
object_field: "Any data",
}, function(server_data) {
$("#dynamic_field tr:last-child").html(parse_server_data(server_data));
});
});
function parse_server_data(data) {
data = JSON.parse(data);
var output_string = "<td><select>";
for (var key in data) {
var value = data[key];
output_string += "<option value=" + key + ">" + value + "</option>";
}
output_string += "</select></td>";
return output_string;
}
</script>
I intentionally segregated server-side code (server.php file) and js code. Why? You should not mix code from server-side and client-side, use power of ajax technologies.
Add to server.php your code that echo's all necessary data (in your case - your fetch_assoc). Learn about MVC model https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
I also added JSON.parse function. JSON is standard of data compression and submission, check json_encode/json_decode functions in PHP and use them
Don't use tables a lot, practice divs/spans
I have a restaurant_form which allows user to input menu items. Each menu item represent a table row which is added dynamically. Each table row has input for: menu item, price, halal(Boolean), and notes.
Here is a sample entry. data-ids and names of input elements are incremented.
<tbody class="menu-entry ">
<tr id='menu0' data-id="0" class="hidden">
<td data-name="name" class="name">
<input type="text" name='name0' placeholder='Menu Item' class="form-control"/>
</td>
<td data-name="price">
<input type="text" name='price0' placeholder='0.00' class="form-control"/>
</td>
<td data-name="halal">
<input type="checkbox" name="veg0" value="halal" class="form-control">
</td>
<td data-name="notes">
<textarea name="notes0" placeholder="Contains soy." class="form-control"></textarea>
</td>
<td data-name="del">
<button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button>
</td>
</tr>
</tbody>
What is the best way to retrieve data from the table? I have tried this:
$('#restaurant_form').submit(function () {
$('.menu-entry').each(function()
{
$(this).find('td').each(function(){
$(this).find("input").each(function() {
alert(this.value)
});
$(this).find("textarea").each(function() {
alert(this.value)
});
})
})
})
The alert() shows the correct values however I am wondering if there is a better way to do this?
Edit I simplified it using:
$('.menu-entry .form-control').each()
Also, after retrieving the values, how can I pass it to the view with a POST request? I would like to save the values to model
RestaurantMenu with columns name, price, halal and notes.
Thank you.
Here's what I did:
For every menu entry, I converted the values to a string separated by comma and added a hidden input to hold the value. I added class 'menu-row' to tr.
$('#restaurant_form').submit(function () {
$('.menu-row').each(function(){
var menu_entry = ""
$(this).find('.form-control').each(function(){
menu_entry = menu_entry + this.value + ","
})
$('#restaurant_form').append('<input type="hidden" name="menu_entries" value="'+ menu_entry +'" />')
alert(menu_entry)
})
})
In views.py :
menu_entries = request.POST.getlist('menu_entries')
for menu_entry in menu_entries:
entry = menu_entry.split(",")
if entry[1]:
price = round(float(entry[1]), 2)
else:
price = 0.00
if not entry[2]:
entry[2] = False
MenuItems.objects.create(name=entry[0], price=price, halal=entry[2], notes=entry[3], restaurant_id=r.id)
If anyone knows a better approach, I would love to know. Thank you!
I'm trying to alert fields. Here is my html
<table width="100%" id="example1" class="table table-bordered table-striped">
<tr>
<td> Nip </td>
<td> Nama Lengkap </td>
</tr>
<tr id='ke0'>
<td> <input class="form-control nipnya" type="text" name="nip[]" /> </td>
<td> <input class="form-control namanya" type="text" name="namalengkap[]" /> </td>
</tr>
<tr id='ke1'>
</tr>
</table>
<div>
<a id="add_row" class="btn btn-success pull-left">Tambah Baris Baru</a>
<a id="delete_row" class="pull-left btn btn-danger">Hapus Baris</a>
</div>
and i have this jquery
$(document).ready(function() {
$("#rmnya").change(function() {
$('#td11').html($("#rmnya").val());
});
var i = 1;
$("#add_row").click(function() {
$('#ke' + i).html('<td><input class="form-control nipnya" type="text" name="nip[]" /> </td>' +
'<td> <input class="form-control namanya" type="text" name="namalengkap[]" />' +
'</td>');
$('#example1').append('<tr id="ke' + (i + 1) + '"></tr>');
i++;
});
$("#delete_row").click(function() {
if (i > 1) {
$("#ke" + (i - 1)).html('');
i--;
}
});
});
As you can see from my script. There is only one Row <tr></tr>. I can alert it if it only one row. But when click Tambah Baris Baru there is another row showing up. I can't alert it. Here is my other javascript
$(".nipnya").change(function(){
$('.nipnya').each(function(i, obj) {
alert($('.nipnya').val());
});
});
So, can you tell me how to alert after onchange in every field that showing up dynamically.
Here is my fiddle https://jsfiddle.net/spc5884w/
Sorry for my bad english.
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically.
General Syntax
$(staticParentElement).on('event','selector',callback_function)
Example
$('table').on('click', ".nipnya", function(){
alert($(this).val());
});
DEMO
I am trying to build a form where users can add a course using select boxes.
When a course is added, it creates a new table row displaying the course to the user and also adds the course prefix and number (e.g. MATH120) to a hidden form field value. Finally, it adds a delete button.
The delete button should remove the table row AND the hidden input value that corresponds to the course being deleted.
Here's my jsfiddle: http://jsfiddle.net/MtJF2/10/
My script is deleting the row just fine, but its not removing the input value correctly. It's not throwing any errors. Sometimes I've noticed that it will delete the zero in the correct value (e.g. MATH120, becomes MATH12,). Any ideas what might be causing this?
HTML:
<script type="text/javascript">
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function($course, value) {
return value.replace($course, '');
});
}
</script>
<table width="80%" align="center">
<tr id="add-required-course">
<td><input type="button" value="+ Add a Required Course" class="MC-big-button" onclick="$('#course-menu').slideToggle()" /></td>
</tr>
</table>
<input type="hidden" id="required-courses" name="required-courses" value="null" />
<table id="course-menu" width="80%" align="center">
<tr>
<td>Select the course prefix:</td>
<td><select id="1" name="course-prefix">
<option value="MATH">MATH</option>
<option value="BIOL">BIOL</option>
</select>
</td>
</tr>
<tr>
<td>Select the course number:</td>
<td><select id="2" name="course-num">
<option value="101">101</option>
<option value="120">120</option>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Add this course" class="MC-big-button" id="save-course" />
</td>
</tr>
</table>
Javascript:
document.getElementById("save-course").onclick = buildCourse;
function buildCourse() {
var $coursePrefix = ($('#1').val());
var $courseNum = ($('#2').val());
var $course = $coursePrefix + $courseNum;
var $HTMLoutput = '<tr id="' + $course + '"><td>' + $course + '<input type="button" value="Delete" onclick="deleteCourse(\'' + $course + '\')" /></td></tr>';
var $VALUEoutput = ($('#required-courses').val());
if ($VALUEoutput == 'null') {
$VALUEoutput = $course + ',';
}
else {
$VALUEoutput = $VALUEoutput + $course + ',';
}
$('#course-menu').slideToggle();
$('#add-required-course').before($HTMLoutput);
$('#required-courses').val($VALUEoutput);
}
I found this question to be helpful, but I think my implementation is off.
You are replacing $course with a new value in the delete function at
$('#required-courses').val(function($course, value) {
// here it gets a new value which is wrong
Use it like this
function deleteCourse($course){
$('#' + $course).remove();
$course = $course + ','
alert($course);
$('#required-courses').val(function(_, value) {
return value.replace($course, '');
});
}