Knockout: Can't edit item that was added to UI - javascript

I am successfully creating an observableArray from local JSON data and creating a grid in the UI. I am able to edit these items and even add (push) a new item -- I can see the new item in the observableArray so I know that it's there. The issue I am having is that I am unable to edit the item once it is in the array.
Here is my JS:
$(function () {
var dataFromServer = ko.utils.parseJson(JSONdataFromServer);
var shortUserArray = dataFromServer;
shortUserArray.length = 5;
console.log(shortUserArray);
function Item(firstName, lastName, title) {
this.firstName = ko.observable(firstName, { persist: firstName });
this.lastName = ko.observable(lastName, { persist: lastName });
this.title = ko.observable(title, { persist: title });
}
//do some basic mapping (without mapping plugin)
var mappedData = ko.utils.arrayMap(shortUserArray, function (item) {
return new Item(item.firstName, item.lastName, item.title);
});
var viewModel = function () {
var self = this;
// data
self.people = ko.observableArray(mappedData, { persist: 'people' }),
self.firstNameToAdd = ko.observable(""),
self.lastNameToAdd = ko.observable(""),
self.titleToAdd = ko.observable(""),
self.selectedPerson = ko.observable(null),
self.addPerson = function () {
this.people.push({
firstName: this.firstNameToAdd(),
lastName: this.lastNameToAdd(),
title: this.titleToAdd()
});
this.firstNameToAdd("");
this.lastNameToAdd("");
this.titleToAdd("");
},
self.selectPerson = function () {
viewModel.selectedPerson(this);
},
self.addOnEnter = function () {
var keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
viewModel.addPerson();
}
return true;
};
$(document).on("click", ".row-delete", function () {
var itemToRemove = ko.dataFor(this);
self.people.remove(itemToRemove);
});
};
ko.applyBindings(new viewModel());
});
// Custom binding to add an item to the list when the user presses enter
ko.bindingHandlers.executeOnEnter = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value;
value = void 0;
value = valueAccessor();
return $(element).keypress(function (event) {
var keyCode;
keyCode = void 0;
keyCode = (event.which ? event.which : event.keyCode);
if (keyCode === 13) {
value.call(viewModel);
return false;
}
return true;
});
}
};
...and here is the HTML:
<div class="container">
<div class="row">
<div class="col-md-12">
<a data-toggle="modal" href="#addUser" class="btn btn-primary"><span class="glyphicon glyphicon-plus"></span> Add New User</a>
<button type="button" class="btn btn-default pull-right" onclick="localStorage.clear();"><span class="glyphicon glyphicon-refresh"></span> Clear Local Storage</button>
<hr />
<div class="table-responsive">
<table class="table table-bordered table-striped table-hover">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Title</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: firstName"></td>
<td data-bind="text: lastName"></td>
<td data-bind="text: title"></td>
<td data-bind="click: $root.selectedPerson">
<span class="glyphicon glyphicon-edit"></span> Edit User
</td>
<td data-bind="click: $root.selectedPerson">
<span class="glyphicon glyphicon-remove"></span> Delete User
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- Add User Modal -->
<div class="modal fade" id="addUser" tabindex="-1" role="dialog" aria-labelledby="addUserLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="first-name">First Name</label>
<input type="text" class="form-control" id="first-name" data-bind="value: firstNameToAdd, valueUpdate: 'afterkeydown'">
</div>
<div class="form-group">
<label for="last-name">Last Name</label>
<input type="text" class="form-control" id="last-name" data-bind="value: lastNameToAdd, valueUpdate: 'afterkeydown'">
</div>
<div class="form-group">
<label for="job-title">Job Title</label>
<input type="text" class="form-control" id="job-title" data-bind="value: titleToAdd, valueUpdate: 'afterkeydown'">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" data-bind="click: addPerson, enable: firstNameToAdd().length > 0 && lastNameToAdd().length > 0 && titleToAdd().length > 0" data-dismiss="modal">Add User</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- Edit User Modal -->
<div class="modal fade" id="editUser" tabindex="-1" role="dialog" aria-labelledby="editUserLabel" aria-hidden="true" data-bind="with: selectedPerson">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 id="editUserLabel" data-bind="text: firstName" class="modal-title">Edit User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="edit-first-name">First Name</label>
<input type="text" class="form-control" id="edit-first-name" data-bind="value: firstName" id="edit-first-name">
</div>
<div class="form-group">
<label for="edit-last-name">Last Name</label>
<input type="text" class="form-control" id="edit-last-name" data-bind="value: lastName" id="edit-last-name">
</div>
<div class="form-group">
<label for="edit-job-title">Job Title</label>
<input type="text" class="form-control" id="edit-job-title" data-bind="value: title" id="edit-job-title">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>

Currently when you are giving a name for the new person, you are only passing on the value of the observable this.firstNameToAdd() but not making the firstName property itself an observable..
you should either..
this.people.push({
firstName: ko.observable(this.firstNameToAdd()),
lastName: ko.observable(this.lastNameToAdd()),
title: ko.observable(this.titleToAdd())
});
or even better - since you already have an Item class..
this.people.push(new Item(
this.firstNameToAdd(),
this.lastNameToAdd(),
this.titleToAdd()
));
fiddle : http://jsfiddle.net/sskMG/1/

Related

Jquery validates one row out of many rows

I am working in one inventory project I use bootsrap modal for inserting and updating records the problem that I am facing is that when I am editing the record the jquery validation only applied on first row not on any other row can any one help me in this matter.
index page is like below
<tbody>
#foreach ($suppliers as $key => $supplier)
<tr class="odd">
<td class="sorting_1 dtr-control">{{ $key + 1 }}</td>
<td>{{ $supplier->name }}</td>
<td>{{ $supplier->mobile_no }}</td>
<td>{{ $supplier->email }}</td>
<td>{{ $supplier->address }}</td>
<td>
<a href="#edit{{ $supplier->id }}" data-bs-toggle="modal" class="fas fa-edit" title="Edit Data" style=" margin-right:20px">
</a>
#include('backend.supplier.editSupplier')
</td>
</tr>
#endforeach
</tbody>
Modal is like below
<div class="modal fade editModal" id="edit{{ $supplier->id }}" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit Supplier</h5>
<button type="button" class=" btn btn-danger btn btn-sm close" data-bs-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST" action="{{ route('supplier.update', $supplier->id) }}"
class="needs-validation" novalidate>
#csrf
#method('PUT')
<div class="modal-body">
<!-- name -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name"
id="name" name="name1" value="{{ $supplier->name }}">
</div>
</div>
<!-- mobile number -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no"
placeholder="Mobile Number" id="mobile_no" name="mobile_no1"
value="{{ $supplier->mobile_no }}">
</div>
</div>
<!-- email -->
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address"
name="email_address1" value="{{ $supplier->email }}">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address"
id="address" name="address1" value="{{ $supplier->address }}">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"
onclick="resetForm()">No</button>
<button type="submit" class="btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
Jquery code is like below
<script type="text/javascript">
$(document).ready(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
},
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
},
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
},
});
});
function resetForm() {
$("#editForm").trigger("reset");
var validator = $("#editForm").validate();
validator.resetForm();
}
</script>
This is a VERY verbose example but here I take a rendered table and remove the form from that. This avoids duplication of the id's on the form and also gives you smaller HTML and the ability to use the same form over in every row and on and "add" action.
I then trigger the edit with the edit link/button; it saves by submit of the form but you could alter that to post the data using ajax or something also.
I did not venture into the "add" but you could put a button on the screen for that also; stick the id or whatever you need in the "action" to save the NEW item in that part.
$(function() {
$('#editForm').validate({
rules: {
name1: {
required: true,
},
mobile_no1: {
required: true,
},
address1: {
required: true,
},
email_address1: {
required: true,
}
},
messages: {
name1: {
required: 'Please Enter Supplier Name',
},
mobile_no1: {
required: 'Please Enter Supplier mobile number',
},
address1: {
required: 'Please Enter Supplier address',
},
email_address1: {
required: 'Please Enter Supplier email',
}
},
errorElement: 'span',
errorPlacement: function(error, element) {
error.addClass('invalid-feedback');
element.closest('.form-group').append(error);
},
highlight: function(element, errorClass, validClass) {
$(element).addClass('is-invalid');
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass('is-invalid');
}
});
$('#my-great-suppliers').on('click', '.edit-link', function(event) {
//event.preventDefault().preventPropagation();
console.log('set up edit');
const trow = $(this).closest('.supplier-row');
console.log("Row:", trow.index(), trow.length);
const modal = $('#edit-modal-container').find('.edit-modal-child');
const modalForm = modal.find('#editForm');
const rowEdits = trow.find('.edit-me');
let supplierid = $(this).data("supplierid");
let name = rowEdits.filter('[data-suppliername]').data("suppliername");
let email = rowEdits.filter('[data-email]').data("email");
let mobile = rowEdits.filter('[data-mobile]').data("mobile");
let address = rowEdits.filter('[data-address]').data("address");
console.log(supplierid, name, trow.length);
modalForm.find('#name').val(name);
modalForm.find('#email_address').val(email);
modalForm.find('#address').val(address);
modalForm.find('#mobile_no').val(mobile);
let actionV = modalForm.attr("action");
console.log(actionV);
// update the form action with the id
modalForm.attr("action", actionV + supplierid);
// modal.show();
});
$('.submit-button').on('click', function(event) {
event.preventDefault();
const modalForm = $('#editForm');
console.log("trying to save");
// now do what you need to validate
if (modalForm.valid()) {
// add your extra logic here to execute only when element is valid
console.log('It is valid');
let savedata = {
name: modalForm.find('#name').val(),
email: modalForm.find('#email_address').val(),
address: modalForm.find('#address').val(),
mobile: modalForm.find('#mobile_no').val()
};
console.log("Saving:", savedata, 'To:', modalForm.attr("action"));
//now do what you want to save the form
// since we updated the action when edit started we have the id in there
// modalForm.submit()
}
});
});
function resetForm() {
$("#editForm").trigger("reset");
let validator = $("#editForm").validate();
validator.resetForm();
}
.edit-link {
margin-right: 20px;
}
.edit-modal-container {}
.cheers {
border: solid 1px green;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js" integrity="sha512-rstIgDs0xPgmG6RX1Aba4KV5cWJbAMcvRCVmglpam9SoHZiUCyQVDdH2LPlxoHtrv17XWblE/V/PP+Tr04hbtA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table id="my-great-suppliers" class="my-great-suppliers-container">
<tbody>
<tr class="supplier-row odd">
<td class="sorting_1 dtr-control">$key1</td>
<td class='edit-me' data-suppliername="Dirt supplier">Dirt supplier</td>
<td class="edit-me" data-mobile="123-123-1234">123-123-1234</td>
<td class="edit-me" data-email="happydays#example.com">happydays#example.com</td>
<td class="edit-me" data-address="1234 Main St">1234 Main St</td>
<td>
<a href="#" data-supplierid="supplier-1" data-bs-toggle="modal" class="edit-link fas fa-edit" title="Edit Data" data-bs-target="#supplier-modal">
</a>
</td>
</tr>
<tr class="supplier-row odd">
<td class="sorting_1 dtr-control">$key2</td>
<td class='edit-me' data-suppliername="Rock supplier">Rock supplier</td>
<td class='edit-me' data-mobile="321-123-4321">321-123-4321</td>
<td class='edit-me' data-email="biggerrocks#example.com">biggerrocks#example.com</td>
<td class='edit-me' data-address="12 Granite Lane">12 Granite Lane</td>
<td>
<a href="#" data-supplierid="supplier-2" data-bs-toggle="modal" class="edit-link fas fa-edit" data-bs-target="#supplier-modal" title="Edit Data">
</a>
</td>
</tr>
</tbody>
</table>
<div id="edit-modal-container" class="edit-modal-container">
<div id='supplier-modal' class="edit-modal-child modal fade editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Supplier</h5>
<button type="button" class="btn btn-danger btn btn-sm close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form id="editForm" method="POST" action="/route/supplierupdate/" class="needs-validation" novalidate>
<div class="modal-body">
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="name" placeholder="Supplier Name" id="name" name="name1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="text" autocomplete="mobile_no" placeholder="Mobile Number" id="mobile_no" name="mobile_no1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control " type="email_address" placeholder="Email" id="email_address" name="email_address1" value="">
</div>
</div>
<div class="col-md-12 ">
<div class="mb-3 position-relative form-group">
<input class="form-control" type="text" autocomplete="address" placeholder="Address" id="address" name="address1" value="">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="resetForm()">No</button>
<button type="submit" class="submit-button btn btn-primary">Add Supplier</button>
</div>
</form>
</div>
</div>
</div>
</div>
if you try to inspect the modal on each row. the input will have the same name eg. name1, mobile_no1, etc.
Jquery will validate the first input element with that name.
You can either move the modal and Jquery function each with their own unique id inside foreach. may use $supplier->id
Or
Im guessing the modal already inside the foreach since it have the unique id. Update eqch input to include the unique id(name="mobile_no1<?php $supplier-id ?>") Then, update the jquery function to accept id identifier($supplier->id) so it can fetch the unique input element

Join Multiple tables : Edit and Update an Item from a table list to a modal in asp.net mvc

I'm new to ASP.NET MVC and I'm having trouble editing an item and showing it in a modal form and updating it in the database. The data is not showing in a modal. The data is coming from different tables in the database.
Expected output: show the list in a single view(table) and edit a selected item from the list (modal) and update it.
Here's my code:
AdminController:
public JsonResult EditItem(int? itemID)
{
var id = db.Items.Where(i => i.ItemID == itemID).FirstOrDefault();
List<Item> itemList = db.Items.ToList();
List<ItemDetail> itemDetailList = db.ItemDetails.ToList();
List<ProductType> productTypeList = db.ProductTypes.ToList();
var details = from itm in itemList
join itmDetail in itemDetailList on itm.ItemID equals itmDetail.ItemID into ItemInfo
from itmDetail in ItemInfo.DefaultIfEmpty()
join product in productTypeList on itmDetail.ProductID equals product.ProductID into ProductInfo
from product in ProductInfo.DefaultIfEmpty()
where itm.ItemID.Equals(id)
select new TableCollection { Item = itm, ItemDetail = itmDetail, ProductType = product };
return Json(details, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult EditItem(Item item, ItemDetail details)
{
ItemDetail itmDetails = db.ItemDetails.Where(d => d.ItemID == item.ItemID).FirstOrDefault();
itmDetails.ItemID = details.ItemID;
db.SaveChanges();
return RedirectToAction("Inventory", "Admin");
}
InventoryList View:
#model IEnumerable<VetClinic.Models.Admin.TableCollection>
#if (Model != null)
{
<table id="inventory" class="table table-striped table-hover">
<thead class="thead-dark">
<tr>
<th>Product Type</th>
<th>Item Name</th>
<th># of Stock</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody class="bg-light">
#foreach (var item in Model)
{
<tr id="row_#item.ItemDetail.ItemID">
<td>#item.ProductType.Name #item.ProductType.Type</td>
<td>#item.ItemDetail.ItemName</td>
<td>#item.ItemDetail.NumOfStock</td>
<td>#item.ItemDetail.Price</td>
<td>
<i class="fa fa-pencil" data-toggle="tooltip" title="Edit" style="color: blue;"></i>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="EditItem" tabindex="-1" role="dialog" aria-labelledby="EditItem" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Edit Item</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#using (Html.BeginForm("EditItem", "Admin", FormMethod.Post))
{
<input type="hidden" id="hiddenItemID" />
<div class="form-group row">
<div class="col-lg-3">
<label>Product Type:</label>
</div>
<div class="col-lg-4">
<input type="text" id="productType"/>
</div>
</div>
<div class="form-group row">
<div class="col-lg-2">
<label>Item Name:</label>
</div>
<div class="col-lg-3">
<input type="text" id="itemName" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-5">
<label>Number of Stocks</label>
</div>
<div class="col-lg-2">
<input type="text" id="numOfStocks" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-lg-2">
<label>Price:</label>
</div>
<div class="col-lg-3">
<input type="text" id="price" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">Update</button>
</div>
}
</div>
</div>
</div>
</div>
}
else
{
<i class="fa fa-info-circle"> </i>#ViewBag.EmptyList;
}
<script>
function EditItem(id) {
$.ajax({
url: "/Admin/EditItem/" + id,
type: "GET",
dataType: "json",
success: function (response) {
$("#hiddenItemID").val(response.ItemID);
$("#EditItem").modal("show");
}
});
return false;
}
</script>

Laravel: javascript for some reasons is not working

I have to develop a CRUD function to manage a DB. The button EDIT and DELETE open modal window and interact with the DB. What I cannot get is that the script works perfectly for EDIT but seems to be ignored for DELETE...what is wrong?
Those are my routes:
Route::get('/', 'DataController#overview');
Route::get('/myproject', 'ProjectsController#getForm');
Route::post('/myproject/create', 'ProjectsController#create');
Route::post('/myproject/update', 'ProjectsController#update');
Route::post('/myproject/delete', 'ProjectsController#delete');
Route::get('/upload','DataController#showform');
Route::post('/upload', 'DataController#read_xsl');
Route::get('/jobcontents', 'DataController#showscrape');
Route::post('/jobcontents', 'DataController#scrape');
This is my controller:
public function update(Request $request)
{
#$projectID = \DB::table('projects')->select('id')->get(),
try
{
//Find the project id in Project_model
#var_dump($request->toArray());
#var_dump($request->get('id'));
#exit;
$project = Project_model::findOrFail($request->get('id'));
//Set project object attributes
$project->name = $request->get('name');
$project->description = $request->get('description');
// Save/update project.
$project->save();
#return view('form_project')->with('project', $project);
return redirect()->back()->with('project', $project);
#return back();
}
catch(ModelNotFoundException $err)
{
return redirect()->action('ProjectsController#getForm');
}
}
public function delete(Request $request)
{
try
{
var_dump($request->toArray());
exit;
$project = Project_model::findOrFail($request->get('id'));
$project->delete();
return redirect()->back()->with('project', $project);
}
catch(ModelNotFoundException $err)
{
return redirect()->action('ProjectsController#getForm');
}
}
This is my blade:
//search and retrieve data from Modal
$(document).ready(function() {
$('#editModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget)
var name = button.data('myname')
var description = button.data('mydesc')
var project_id = button.data('projectid')
var modal = $(this)
//put the values in modal <input>
modal.find('.modal-body #name').val(name);
modal.find('.modal-body #description').val(description);
modal.find('.modal-body #project_id').val(project_id);
})
$('#deleteModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget)
var projctid = button.data('projid')
var modal = $(this)
modal.find('.modal-body #projid').val(projctid);
})
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<div class="container">
<h3 class="jumbotron">Create here your project</h3>
<form method="post" id="projectform" class="w3-container w3-light-grey" action={{action( 'ProjectsController#create')}} enctype="multipart/form-data">
{{csrf_field()}}
<p>
<label>Project Name</label>
<input class="w3-input w3-border w3-round" name="name" type="text"></p>
<p>
<label>Project Description</label>
<input class="w3-input w3-border w3-round" name="description" type="text"></p>
<button type="submit" class="btn btn-primary" style="margin-top:10px">Create Project</button>
</form>
</div>
<div class="container-fluid">
<h3 class="jumbotron">Your Projects</h3>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>name</th>
<th>description</th>
<th>created_at </th>
<th>updated_at </th>
</tr>
</thead>
<tbody>
#if(isset($project_data)) #foreach($project_data as $project)
<tr>
<td> {{$project->id}} </td>
<td> {{$project->name}} </td>
<td> {{$project->description}} </td>
<td> {{$project->created_at}} </td>
<td> {{$project->updated_at}} </td>
<td>
<button type="button" class="btn btn-warning btn-detail open-modal" data-projectid="{{$project->id}}" data-myname="{{$project->name}}" data-mydesc="{{$project->description}}" data-toggle="modal" data-target="#editModal">Edit</button>
<button type="button" class="btn btn-danger btn-delete open-modal" data-projid="{{$project->id}}" data-toggle="modal" data-target="#deleteModal">Delete</button>
<button class="btn btn-info">See Jobs</button>
</td>
</tr>
#endforeach #endif
</tbody>
</table>
</div>
</div>
<!-- Modal (Pop up when edit button clicked) -->
<div class="modal" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="editModalTitle">Edit your project</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form method="post" action={{action( 'ProjectsController#update')}} id="frmSave" name="frmSave" class="form-horizontal" role="form">
{{csrf_field()}}
<input type="hidden" name="id" id="project_id">
<div class="form-group">
<label for="name" class="col-sm-3 control-label">Project Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="name" name="name" placeholder="" value="">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="description" name="description" placeholder="" value="">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" form="frmSave" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal (Pop up when delete button clicked) -->
<div class="modal" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="deleteModalTitle">Delete your project</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<form method="post" action={{action( 'ProjectsController#delete')}} id="frmDel" name="frmDel" class="form-horizontal" role="form">
{{csrf_field()}}
<input type="hidden" name="id" id="projid">
<p class="text-center">
Are you sure you want to delete this?
</p>
</form>
</div>
<div class="modal-footer">
<button type="submit" form="frmDel" class="btn btn-primary" id="btn-delete" value="">Yes, delete!</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">No, don't!</button>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
---EDIT---
These are the results when I run console.log(button) and console.log(projctid)
Hope this can help newbie like me in the future!
The problem was just related to Chrome CACHE REFRESH!!!
So be sure to clear cache (Shift+F5) and not only refresh the page when something does not work!

Modal in Asp.NET MVC

I have a Asp.NET MVC application, i trying to use a modal to make the update of the data, i have two modal for Register and Update, the Register is OK, but the Update is not working, when a click on the "Alterar" button, need to open a modal with the data filled, i trying to use JavaScript to do this.
Can someone help me?
My table
My modal that need open filled with data
My Code
Table
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>ID</th>
<th>Produto</th>
<th>Custo</th>
<th>Lucro</th>
<th>Opcoes</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach(var sale in Model)
{
<tr>
<td>#Html.DisplayFor(model => sale.idProduct)</td>
<td>#Html.DisplayFor(model => sale.nameProduct)</td>
<td>#Html.DisplayFor(model => sale.costProduct)</td>
<td>#Html.DisplayFor(model => sale.profitProduct)</td>
<!--Get values to put on Modal-->
<td><a class="update" data-toggle="modal" href="#updateModal" data-id="#sale.idProduct" data-name="#sale.nameProduct"
data-cost="#sale.costProduct" data-profit="#sale.profitProduct"><span class="glyphicon glyphicon-edit">Alterar</span></a></td>
</tr>
}
}
</tbody>
</table>
enter code here
JavaScript
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var $this = $(this);
var idProduct = $this.data('id');
var nameProduct = $this.data('name');
var costProduct = $this.data('cost')
var profitProduct = $this.data('profit')
$('#nameProduct').text(nameProduct);
$('#costProduct').text(costProduct);
$('#profitProduct').text(profitProduct);
$("#updateModal #form_update #idProduct").val(idProduct);
$('#updateModal').modal();
});
});
Modal
<div id="updateModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal">×</button>
<h4 class="modal-title">Alterar Produto<span id="name_product"></span></h4>
</div>
<form method="post" id="form_update" action="/Dashboard/Product">
<div class="modal-body">
<div class="form-group">
<input type="hidden" name="idProduct" id="idProduct" class="form-control" placeholder="ID do produto"/>
<input type="text" name="nameProduct" id="nameProduct" class="form-control" placeholder="ID do produto" required />
<input type="text" name="costProduct" id="costProduct" class="form-control" placeholder="Custo do Produto" required />
<input type="text" name="profitProduct" id="profitProduct" class="form-control" placeholder="Lucro do Produto" required />
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" value="Atualizar" />
<button type="button" class="btn btn-warning" data-dissmiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
to change the value of input you need to use val() :
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var $this = $(this);
var idProduct = $this.data('id');
var nameProduct = $this.data('name');
var costProduct = $this.data('cost')
var profitProduct = $this.data('profit')
$('#nameProduct').val(nameProduct);
$('#costProduct').val(costProduct);
$('#profitProduct').val(profitProduct);
$("#updateModal #form_update #idProduct").val(idProduct);
$('#updateModal').modal();
});
});
Your modal contains only inputs.
For setting the value of input you used $('#nameProduct').text(nameProduct) and that's the wrong thing. You need the val() method.
$('#nameProduct').val(nameProduct);
.text() method is used specially for div, span, etc.
UPDATE
<td>#Html.DisplayFor(model => sale.idProduct)</td> generates a span with the follow properties: id and name have value idProduct. The problem is that you have two elements with same id(in table and in modal). id attribute must be unique in DOM.
Modal
<div id="updateModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal">×</button>
<h4 class="modal-title">Alterar Produto<span id="name_product"></span></h4>
</div>
<form method="post" id="form_update" action="/Dashboard/Product">
<div class="modal-body">
<div class="form-group">
<input type="hidden" class="form-control modalInput" placeholder="ID do produto"/>
<input type="text" class="form-control modalInput" placeholder="ID do produto" required />
<input type="text" class="form-control modalInput" placeholder="Custo do Produto" required />
<input type="text" class="form-control modalInput" placeholder="Lucro do Produto" required />
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-warning" value="Atualizar" />
<button type="button" class="btn btn-warning" data-dissmiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
JAVASCRIPT
<script type="text/javascript">
$(document).ready(function () {
$('.update').on('click', function () {
var modal=$('#updateModal');
var idInput = modal.find('input.modalInput').eq(0);
var nameInput = modal.find('input.modalInput').eq(1);
var costInput = modal.find('input.modalInput').eq(2);
var profitInput = modal.find('input.modalInput').eq(3);
idInput.val($(this).data('id'));
nameInput .val($(this).data('name'));
costInput.val($(this).data('cost'));
profitInput .val($(this).data('profit'));
modal.modal();
});
});
</script>
HTML
foreach(var sale in Model)
{
<tr>
<td>#Html.DisplayFor(model => sale.idProduct)</td>
<td>#Html.DisplayFor(model => sale.nameProduct)</td>
<td>#Html.DisplayFor(model => sale.costProduct)</td>
<td>#Html.DisplayFor(model => sale.profitProduct)</td>
<!--Get values to put on Modal-->
<td><a class="update" data-id="#sale.idProduct" data-name="#sale.nameProduct" data-cost="#sale.costProduct" data-profit="#sale.profitProduct"><span class="glyphicon glyphicon-edit">Alterar</span></a></td>
</tr>
}
you must use val().You use like a text("asda").you change these problem resolve

How can i get form input values by id in meteor

I am new in meteor framework. Now i am practice in my local server. I have added my all data by meteor but now i want to edit my data. I have tried to edit my data but unable to get all values. below is my all code.
<head>
<title>Login page</title>
</head>
<body>
{{> facebooktest}}
{{> usersDetails}}
</body>
<template name="usersDetails">
<table class="userdetailstable">
<tr>
<th>#Id</th>
<th>Email Address</th>
<th>Name</th>
<th>Username</th>
<th>Password</th>
<th>Created</th>
<th>Edit</th>
<th>Delete</th>
</tr>
{{#each returnRegistrationData}}
<tr>
<td>{{_id}}</td>
<td>{{email}}</td>
<td>{{name}}</td>
<td>{{username}}</td>
<td>{{created}}</td>
<td>{{password}}</td>
<td><button class="delete-entry btn btn-primary" id="edit-entry">Edit</button></td>
<td><button class="delete-entry btn btn-danger" id="delete-entry">Delete</button></td>
</tr>
{{/each}}
</table>
</template>
<template name="facebooktest">
<div class="container">
<button class="login-button">Login From here</button>
<button class="registration"> Registration </button>
</div>
<div class="modal fade" id="login-page">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Login</h4>
</div>
<form class="login-form" id="login-form">
<div class="modal-body">
<label for="name">Username</label>
<input type="text" id="username" class="username" placeholder="Username" value="" />
<label for="name">Password</label>
<input type="password" id="password" class="password" placeholder="Password" value="" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="save">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="registration-page">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Registration</h4>
</div>
<form class="login-form" id="login-form">
<div class="modal-body">
<label for="name">Email</label>
<input type="email" id="email" class="email" placeholder="email#example.com" value="{{email}}" required />
<label for="name">Your Name</label>
<input type="text" id="name" class="name" placeholder="Your Name" value="{{name}}" required/>
<label for="name">Username</label>
<input type="text" id="username" class="username" placeholder="Username" value="{{username}}" required/>
<label for="name">Password</label>
<input type="password" id="password" class="password" placeholder="Password" value="{{password}}" required/>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="registration-added">Add</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</template>
Below my JS file code
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { Registration } from '../db/database.js';
import './main.html';
Template.body.events({
'click .login-button' : function(event)
{
event.preventDefault();
$('#login-page').modal('show');
},
'click .registration' : function(event)
{
event.preventDefault();
$('#registration-page').modal('show');
}
});
Template.usersDetails.helpers({
returnRegistrationData : function()
{
return Registration.find({});
}
});
Template.usersDetails.events({
'click #delete-entry' : function(event)
{ //console.log(event.target);
Registration.remove(this._id);
},
'click #edit-entry' : function(event)
{
$('#registration-page').modal('show');
var editdata = Registration.find(this._id);
console.log(editdata.target);
}
});
I am using modal box when we click on buttons. I just want to get edit button row values.
http://i.imgur.com/cz79YN9.png
Template.facebooktest.events({
'submit #login-form' : function(event)
{
event.preventDefault();
const target = event.target;
var username = target.username.value;
var password = target.password.value;
if(username == '')
{
alert('Please enter your username.');
return false;
}
else if(password == '')
{
alert('Please enter your password.');
return false;
}
else
{
var selectmethod = Registration.find({
"name" : username,
"password" : password
});
console.log(selectmethod);
$('#login-page').modal('hide');
}
},
'submit #registration-page' : function(event)
{
event.preventDefault();
const target = event.target;
const email = event.target.email.value;
const name = event.target.name.value;
const username = event.target.username.value;
const password = event.target.password.value;
Registration.insert({
email,
name,
username,
password,
created : new Date(),
});
event.target.email.value = '';
event.target.name.value = '';
event.target.username.value = '';
event.target.password.value = '';
$('#registration-page').modal('hide');
}
});
// db.registration.insert({ email: "test#sad.com",name: "test#sad.com",username: "test#sad.com",password: "123456", createdAt: new Date() });

Categories

Resources