I have a dependent dropdown and it gets values by comparing ID's, the issue here is when I am trying to save the form values I am getting the ID's instead of names of the select fields. Can anyone tell me how can I get the NAME instead of ID.
My blade view with the javascript: index.blade.php`
<div class="container">
<h2>Region</h2><br>
<form action="details" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Select Country:</label>
<select id="country" name="country" class="form-control" style="width:350px" required>
<option value="" selected disabled>Select</option>
#foreach($countries as $key => $country)
<option value="{{$key}}">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="title">Select State:</label>
<select name="state" id="state" class="form-control" style="width:350px" required>
</select>
</div>
<div class="form-group">
<label for="title">Select City:</label>
<select name="city" id="city" class="form-control" style="width:350px" required>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<script type="text/javascript">
$('#country').change(function() {
var countryID = $(this).val();
if (countryID) {
$.ajax({
type: "GET",
url: "{{url('get-state-list')}}?country_id=" + countryID,
success: function(res) {
if (res) {
$("#state").empty();
$("#state").append('<option value="">Select</option>');
$.each(res, function(key, value) {
$("#state").append('<option value="' + key + '">' + value + '</option>');
});
} else {
$("#state").empty();
}
}
});
} else {
$("#state").empty();
$("#city").empty();
}
});
$('#state').change(function() {
var stateID = $(this).val();
if (stateID) {
$.ajax({
type: "GET",
url: "{{url('get-city-list')}}?state_id=" + stateID,
success: function(res) {
if (res) {
$("#city").empty();
$("#city").append('<option value="">Select</option>');
$.each(res, function(key, value) {
$("#city").append('<option value="' + key + '">' + value + '</option>');
});
} else {
$("#city").empty();
}
}
});
} else {
$("#city").empty();
}
});
</script>
My Controller for the dropdown: DropdownController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class DropdownController extends Controller
{
public function index()
{
$countries = DB::table("countries")->pluck("name", "id");
return view('index', compact('countries'));
}
public function getStateList(Request $request)
{
$states = DB::table("states")
->where("country_id", $request->country_id)
->pluck("name", "id");
return response()->json($states);
}
public function getCityList(Request $request)
{
$cities = DB::table("cities")
->where("state_id", $request->state_id)
->pluck("name", "id");
return response()->json($cities);
}
public function show(Request $request)
{
dd(request()->all());
}
}
The payload I am getting after data dump is the ID's:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxx"
"country" => "1"
"state" => "5"
"city" => "124"
]
What I want is to get Names:
array:4 [▼
"_token" => "xxxxxxxxxxxxxxxxxxxxxxxxx"
"country" => "country_name"
"state" => "state_name"
"city" => "city_name"
]
You should change the name of your select from name to name[]
Related
The form has a select for Customer with populates from a variable in the controller. I can easily retrieve the old input value using old('customer_id').
My problem comes from the second select. The second select uses javascript to populate the Customer Contact based on which Customer is chosen. When validation fails, I lose that value.
Here is the controller code for the store method:
$rules = [
'number' => 'required',
'customer_id' => 'required',
'contact_id' => 'required',
'payment_type' => 'nullable',
'department_id' => 'required',
'requested_ship_date' => 'required|after:yesterday',
];
$customMessages = [
'number.required' => 'The Sales Order number is required.',
'customer_id.required' => 'Please choose a customer.',
'contact_id.required' => 'Please choose a contact.',
'requested_ship_date.required' => 'You must enter a ship date.',
'requested_ship_date.yesterday' => 'The requested ship date must be today or after.',
'department_id.required' => 'Please choose a department.'
];
$salesorder = \request()->validate($rules, $customMessages);
SalesOrder::create($salesorder);
return redirect('/salesorders');
Here is Customer Select:
<select
name="customer_id"
class="shadow text-sm">
#if (old('customer_id'))
<option
value>
</option>
#else
<option
selected
value>
</option>
#endif
#foreach($customers as $customer)
#if (old('customer_id'))
<option
value="{{ $customer->id }}" {{ old('customer_id') == $customer->id ? 'selected' : '' }}>
{{ ucfirst($customer->name) }}
</option>
#else
<option
value="{{ $customer->id }}">
{{ ucfirst($customer->name) }}
</option>
#endif
#endforeach
</select>
Here is the select for the Customer Contact:
<select
name="contact_id"
class="shadow text-sm text-center"
>
<option>
</option>
</select>
And here is the javascript:
$('select[name="customer_id"]').on('change', function () {
var customerId = $(this).val();
if (customerId) {
$.ajax({
url: '/customer/contacts/get/' + customerId,
type: "GET",
dataType: "json",
beforeSend: function () {
$('#loader').css("visibility", "visible");
},
success: function (data) {
$('input[name="email"]').val('');
$('select[name="contact_id"]').empty();
$('select[name="contact_id"]').append('<option value="Choose">Choose Contact</option>');
$.each(data, function (key, value) {
$('select[name="contact_id"]').append('<option value="' + key + '">' + value + '</option>');
});
},
complete: function () {
$('#loader').css("visibility", "hidden");
}
});
} else {
$('select[name="customer_id"]').empty();
}
});
I have a form in which there should be submitting a price for various health care services. Treatments are already categorized. Now, I want to first select a treatment group from a selector and then select the treatment list for that category in the next selector. When I have just one form on the page, I have no problem. But I need to clone this form and the user can simultaneously record the price of some treatments. In this case, all the second selectors are set according to the last selector for the categories. While having to match their category's selector. I searched for the solution very well and did not get it. My code in vuejs is as follows. Please guide me. Thank you in advance.
<template>
<div>
<div id="treatment_information">
<div class="col-md-3">
<select id="category_name" class="form-control show-tick"
v-on:change="getTreatmentList($event)"
name="treatment_rates[]category_id" v-model="treatment_rate.category_id"
>
<option value="0"> -- select category --</option>
<option class="form-control main"
v-for="item in vue_categories" :id="item.id+1000" :value="item.id"
:name="item.name">
{{ item.name }}
</option>
</select>
</div>
<div class="col-md-3">
<select id="treatment_id" class="form-control show-tick"
name="treatment_rates[]treatment_id" v-model="treatment_rate.treatment_id"
>
<option value="0"> -- select treatment --</option>
<option class="form-control main"
v-for="item in vue_treatments" :value="item.id">
{{ item.value }}
</option>
</select>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
vue_temp: [],
vue_categories: [],
vue_treatments: [],
vue_category: '',
//for clone form
treatment_rate: {
category_id: 0,
treatment_id: 0,
hospital_id: 0,
dollar: 'دلار',
rial: 'ریال'
},
treatment_rates: [],
};
},
mounted() {
console.log('Component mounted.');
this.getList();
},
methods: {
getList() {
var self = this;
axios.get('/vueDashboard/get/categories').then(function (response) {
self.vue_temp = response.data;
const len = self.vue_temp.length;
self.vue_temp.forEach(function (item) {
if (self.vue_right.length > 0) {
while (self.vue_right[self.vue_right.length - 1] < item['rgt']) {
self.vue_right.pop();
if (self.vue_right.length == 0)
break;
}
}
self.vue_categories.push({
'id': item['id'],
'name': '---'.repeat(self.vue_right.length) + ' ' + item['name']
});
self.vue_right.push(item['rgt'])
var str = "---";
});
}).catch(function (error) {
console.log(error);
});
axios.get('/vueDashboard/get/treatments?category=' + JSON.stringify(self.treatment_rates)).then(function (response) {
console.log(response.data);
self.vue_treatments = response.data;
}).catch(function (error) {
console.log(error);
});
},
addForm(event) {
var self = this;
self.vue_increment_id[self.vue_counter++]=self.vue_counter;
console.log(self.vue_increment_id);
self.treatment_rates.push(Vue.util.extend({}, self.treatment_rate));
},
}
}
</script>
I'm new to node. I need to make a dependent dropdown menu which gets the address data of the selected user from another dropdown menu in the same page..The proplem is that the hole page is updated not only the second dropdown menu.. I think it's the same problem as dynamically dropdown in nodejs mysql, but it didn't help me much.
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
<% address.forEach((address) => { %>
<option value="<%= address.addressId %>" > <%=address.addressName %> </option>
</select>
<% }) %>
my ajax request:
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
var add = $('#address').val();
$.ajax({
type:'GET',
data: {selectedId : item },
url:'/order/new',
success: function(result1){
$('#body').html(result1);
}
});
});
});
order.js
module.exports = {
addOrderPage: (req, res) => {
let query1 = "SELECT * FROM users";
getConnection().query(query1, (err, result1) => {
let query2 = "SELECT * FROM address WHERE userId = '" +req.query.selectedId + "'";
getConnection().query(query2, (err, rows, fields) => {
if (err) {
return res.status(500).send(err);
}
console,log(rows)
res.render('newOrder.ejs', {
address : rows,
users: result1
});
});
});
}
}
app.js
app.get('/order/new', addOrderPage)
Your success function has missing the data that is return from request update your success function
$(document).ready(function(){
$('#user').change(function(){
var item = $('#user').val();
$.ajax({
type:'GET',
data: { selectedId: item },
url:'/users/address',
success: function(data){
console.log(data);
$('#address').empty();
$('address').append("<option disabled selected> Select Address..</option>");
$.each(data, function (index, addressObj) {
$('#address').append("<option value = '" + addressObj.id + "' > " + addressObj.first_name + ". </option > ");
});
}
});
});
And in your order.js you need create one call for users and one call is for usersaddress data:-
module.exports = {
addOrderPage: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM users";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.render('newOrder.ejs', {
players: result1,
});
});
},
getUserAddress: (req, res) => {
var selecteduser = req.query.selectedId;
let query1 = "SELECT * FROM address WHERE userId = '" + selectedId + "'";
db.query(query1, (err, result1) => {
if (err) {
return res.status(500).send(err);
}
res.send(result1);
});
}
}
neworder.js
<select name="selectUser" id="user" >
<option disabled selected> Select User..</option>
<% users.forEach((users) => { %>
<option value="<%= users.id %>" > <%=users.name %> </option>
<% }) %>
</select>
<br>
<label>Address :</label>
<select name="selectAddress" id="address">
<option disabled selected> Select Address..</option>
</select>
And in your app.js or index.js you need to add its route
app.use("/users/address", order.getUserAddress);
I want to send multiple records in the database using javascript in asp.net mvc i tried many different ways but all in vain. here I have the best code which can send the data to the controller but the file is not sending.
I search different ways i have found one is with FormData but i am unable to handle that in this context.
Controller:
public ActionResult SaveAllFeedback(FEEDBACKVM[] fEEDBACKs)
{
try
{
if (fEEDBACKs != null)
{
FEEDBACK fEEDBACK = new FEEDBACK();
foreach (var item in fEEDBACKs)
{
fEEDBACK.DATE = item.DATE;
fEEDBACK.COMMENT = item.COMMENT;
fEEDBACK.STUDENTID = item.STUDENTID;
fEEDBACK.TEACHERID = db.TEACHERs.Where(x => x.EMAIL == User.Identity.Name).FirstOrDefault().ID;
if (item.HOMEWORK != null)
{
fEEDBACK.HOMEWORK = SaveToPhysicalLocation(item.HOMEWORK);
}
db.FEEDBACKs.Add(fEEDBACK);
}
db.SaveChanges();
return Json("Done", JsonRequestBehavior.AllowGet);
}
return Json("Unable to save your feedback! Please Provice correct information", JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json("Unable to save your feedback! Please try again later.", JsonRequestBehavior.AllowGet);
}
}
ViewPage:
<form>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<input name="DATE" id="DATE" type="date" class="form-control" />
</div>
<table class="table table-responsive table-hover" id="table1">
<thead>
<tr class="bg-cyan">
<th></th>
<th>RollNumber</th>
<th>Comment</th>
<th>Homework</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.students)
{
<tr>
<td>
<input name="STUDENTID" type="text" value="#item.Key" hidden="hidden" />
</td>
<td>
<input name="STUDENTROLLNUMBER" type="text" value="#item.Value" class="form-control" readonly="readonly" />
</td>
<td>
<input name="COMMENT" type="text" class="form-control" />
</td>
<td>
<input name="HOMEWORK" type="file" class="form-control" />
</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<div class="col-md-10">
#Html.ValidationMessage("ErrorInfo", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="saveButton" type="submit" class="btn btn-danger">Save Attendance</button>
</div>
</div>
</form>
Script:
<script>
//After Click Save Button Pass All Data View To Controller For Save Database
function saveButton(data) {
return $.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '#Url.Action("SaveAllFeedback", "Teacherss")',
data: data,
success: function (result) {
alert(result);
location.reload();
},
error: function () {
alert("Error!")
}
});
}
//Collect Multiple Order List For Pass To Controller
$("#saveButton").click(function (e) {
e.preventDefault();
var formData = new FormData();
var arr = [];
arr.length = 0;
$.each($("#table1 tbody tr"), function () {
//arr.push({
// //DATE: $("#DATE").val(),
// //STUDENTID: $(this).find('td:eq(0) input').val(),
// //COMMENT: $(this).find('td:eq(2) input').val(),
// //HOMEWORK: $(this).find('td:eq(3) input').val()
// });
formData.append("DATE", $("#DATE").val());
formData.append("STUDENTID", $(this).find('td:eq(0) input').val());
formData.append("COMMENT", $(this).find('td:eq(2) input').val());
formData.append("HOMEWORK", $(this).find('td:eq(3) input')[0].files[0]);
});
var data = JSON.stringify({
fEEDBACKs: formData
});
$.when(saveButton (data)).then(function (response) {
console.log(response);
}).fail(function (err) {
console.log(err);
});
});
</script>
I just want to send multiple records with the file to the database
are you sure you want send the files???? if yes then
Your form tag should be look like this
<form id="yourid" action="youraction" enctype="multipart/form-data">
Form Component
</form>
NOTE:- enctype="multipart/form-data" tag is important
and then controller should be look like this
public ActionResult YourController(FormCollection data)
{
if (Request.Files.Count > 0)
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//you can save the file like this
string path = Server.MapPath("~/Yourpath/FileName" + fileName.Substring(fileName.LastIndexOf('.')));
file.SaveAs(path);
//or you can load it to memory like this
MemoryStream ms = new MemoryStream();
file.InputStream.CopyTo(ms);
//use it how you like
}
}
return View();
}
I'm wondering if this is possible or not. When the user hits the save button, I want knockout to check if the field labeled Status has been changed to Completed - then I want it to enter the current date into the Date Completed field.
Here are my fields -
<ul class="button-group">
<li><button data-bind="click: save" class="success">Save</button></li>
<li><button data-bind="click: saveAndClose" class="success">Save and close</button></li>
<li><button data-bind="click: cancel" class="alert">Cancel</button></li>
</ul>
<div data-bind="with: item">
<label for="Type">Type</label>
<input id="Type" data-bind="value: Type" disabled="disabled" type="text" />
<label for="Status">Status</label>
<select id ="Status" data-bind="value: Status">
<option value="Not Started">Not Started</option>
<option value="In Progress">In Progress</option>
<option value="Completed">Completed</option>
</select>
<label for="Subject">Subject</label>
<input id="Subject" data-bind="value: Subject" type="text"/>
<label for="Content">Content</label>
<textarea id="Content" data-bind="value: Content" type="text"></textarea>
label for="DateCreated">Date Created (DD/MM/YYYY)</label>
<input id="DateCreated" disabled data-bind="valueFormat: DateCreated, type: 'datetime', format: 'DD/MM/YYYY'" type="text" placeholder="Enter date in format DD/MM/YYYY" />
<label for="DateLastModified">Date Last Modified (DD/MM/YYYY)</label>
<input id="DateLastModified" data-bind="valueFormat: DateLastModified, type: 'datetime', format: 'DD/MM/YYYY'" type="text" placeholder="Enter date in format DD/MM/YYYY" />
<label for="DateCompleted">Date Completed (DD/MM/YYYY)</label>
<input id="DateCompleted" data-bind="valueFormat: DateCompleted, type: 'datetime', format: 'DD/MM/YYYY'" type="text" placeholder="Enter date in format DD/MM/YYYY" />
</div>
And heres what my js file consists of so far
var Module = function(){
var self = this;
var updateItem = function(item) {
if (item) {
self.setupEntityValidation(item, self);
self.item(item);
}
};
self.title = ko.observable();
self.item = ko.observable();
self.isLoadingData = ko.observable(true);
self.entityName = 'Task';
self.entityId = null;
self.activate = function(cid, idOrNew, newType) {
var loadedItem,
types = {
task: {
type: 'Task',
newStatus: 'Not Started'
},
phone: {
type: 'Phone',
newStatus: 'Completed'
},
email: {
type: 'Email',
newStatus: 'Completed'
},
note: {
type: 'Note',
newStatus: 'Completed'
}
},
now = null,
mode = 'new' === idOrNew ? 'Create new' : 'Edit';
// Page title
self.entityId = 'new' === idOrNew ? 0 : parseInt(idOrNew);
self.title(mode + ' task');
if ('new' !== idOrNew) {
// Load the item
self.isLoadingData = ko.observable(true);
ds.getEntityWithKey('Task', self.entityId)
.then(function(data) {
if (data && data.entity) {
// Load item
updateItem(data.entity);
} else {
log.error('#todo get by id failed with result', data);
}
})
.fail(function(err) {
log.error('#todo get by id failed completely', err.stack);
})
.finally(function() {
self.isLoadingData(false);
});
} else {
// No id, create new. Check newType is valid
if (types.hasOwnProperty(newType)) {
// Create new task
now = new Date();
loadedItem = ds.createEntity('Task', {
CentreID: parseInt(cid),
Type: types[newType].type,
Status: types[newType].newStatus,
DateCreated: now.toISOString()
});
if (loadedItem) {
updateItem(loadedItem);
} else {
log.error('Could not create new task item');
}
} else {
log.error('Cannot create new task, illegal type:' + newType);
}
self.isLoadingData(false);
}
};
};
var moduleInstance = new Module();
modex.addComponent('EntitySaveCancel', moduleInstance);
modex.addComponent('EntityValidation', moduleInstance);
return moduleInstance;
});
If you want to instantly apply the change when the field changes to "Completed" you can add a subscribe function that watches the observable "Status" for any change:
self.Status.subscribe(function (value) {
if (value === "Completed") {
//Change date here.
}
});
If you want to change it upon clicking save, you can check "Status" observable value there and set the date accordingly.
Please let us know if this works with you.