i have a modal form where user enters details like for an item,the modal has a select option where user can select the item category there are savings,i have no problem here.the issue is when the user want to edit some details of the item.u will require to retrieve the item.here is my issue i cant get the category saved transferred back to the select option then set is as selected.
how can i do this.//id of selected category is the one that is inserted to db.
$.get(
'../Inventory/PopulateCategory',
{},
function (data) {
$('#Category').empty();
$.each(data,
function (key, value) {
$('#Category')
.append($("<option />")
.val(value.StockCategoryId)
.html(value.StockCategory));
});
},
'json'
);
this is how i retrieve the value,am able to load input but cant get to load the correct saved item to select.
function EditCompanyRecord(_id) {
var url = "/Inventory/itemEdit?_id=" + _id;
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
var currcat = obj.StockCategory;
var _vat = obj.taxcode;
$("#StockId").val(_id);
$("#Description").val(obj.description);
$('#Category').val(obj.StockCategory)
//i need to reverse and get save id as the selected category
}
});
}
The value persisted as category for the stock is the category name/title.
While the options input uses the category id for the value.
In order to have persisted category for the stock selected in the category options, you need to find the id for the persisted category for the stock in the category options. e.g.
const $objStockCategoryId = $('#Category').children().filter((i, e) =>
e.text === obj.StockCategory);
Then select the category option
$('#Category').val($objStockCategoryId.val());
However, I suggest to set a data attribute in the category options for a succinct DOM query. e.g.
$.each(data,
function (key, value) {
$('#Category')
.append(
$("<option />")
.attr('data-name', value.StockCategory)
.val(value.StockCategoryId)
.html(value.StockCategory)
);
});
const $objStockCategoryId = $('#Category')
.find(`[data-name="${obj.StockCategory}"]`);
$('#Category').val($objStockCategoryId.val());
Related
I have a drop down list and I want the value to be sent to the controller when an option is selected,replaceing the returned values in the desired inputs
Html Inputs :
<input type="text" class="form-control js-inputs" id="microchipcode">
<input class="form-control js-inputs" id="fa-horse">
<input type="text" id="fa-fatherhorse" class="form-control js-inputs">
Html DropDown:
$('.js-selected-item').change(function () {
let Value = $(this).val();
$.ajax({
data: { value: Value },
Url: "/Horse/GetHorseByMcode",
type: "post",
success: function (data) {
}
});
});
Controller :
public async Task<IActionResult> GetInfoHorse(string value)
{
var horse = await _coach.GetHorseByMcode(value);
if (horse != null)
{
return Json(horse);
}
return NotFound();
}
Query :
public async Task<Horse> GetHorseByMcode(string value)
{
return await _context.Horses.SingleAsync(h => h.MicrochipCode == value.Trim());
}
If you want to put a value into an input via js, add an ID to the inputs and do the following:
JS:
document.getElementById('//inputId').value = '';
Jquery:
("#//inputId").val("");
How do I access the data inside the object?
You can check the request and response in f12 developer tool Network tab, like below.
and implement frontend code to populate input field(s) in ajax success callback function based on your actual returned data.
For example:
success: function (data) {
$("#fa-fatherhorse").val(data.fatherHorse);
//populate other inputs based on your actual returned data
How to replace Drop Down list ?
If you want to dynamically set the selected value/option of the dropdown, you can try:
$("#dropdown_id_here").val(value_of_selected_option);
If you want to dynamically append <option> to your dropdown, you can try:
var newoption = "<option value='" + option_val + "'>" + option_text + "</option>";
$("#dropdown_id_here").append(newoption);
I want to get a data value from the clicked td, which opens a modal with the informations of the user.
When I select all users, everything works fine..
But when I want to search a specific user (table is not displayed until you search for a user), the modal shows not the right data..
I created a JS array with the usernames and put it in my data value. The innerHTML from the column is the first- and last name of the user.
The problem is that when I click on the name the modal shows the information from the FIRST user in my array (grouped by lastname ASC)
I'm using the DataTables plugin. Here's a short example of my drawCallback function:
"drawCallback": function(settings) {
var api = this.api();
var rows = api.rows({
page: 'current'
}).nodes();
var last = null;
api.column(0, {
page: 'current'
}).data().each(function(group, i) {
if (last !== group) {
var groupName = api.row(i).data();
$(rows).eq(i).before(
'<tr class="group"><td style="font-weight: bold;" data-value="'+groupName[0]+'" data-toggle="modal" data-target="#profileModal" class="tdPerson" colspan="1">'+group+'</td><td colspan="5"></td></tr>'
);
last = group;
}
});
}
Here's my AJAX request:
$('.table').on('click', '.tdPerson', function(event) {
id = $(this).attr('data-value');
$.ajax({
url: "getData.php",
data: {
type: "getPersonModal",
data: id
},
type: "POST",
success: function(data) {
$('#profileModalContent').html(data);
}
});
});
I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();
I want replace the select box inside of the div
<div class="models">
<select disabled="disable">
<option>Model Name</option>
</select>
</div>
I'm trying to target the div and load the select box like this
jQuery('.models select').change(function() {
var model = jQuery('.models option:selected').text();
I'm not getting any action on change though
http://jsfiddle.net/HNgKt/
Simple change: bind your change event handler to the container div (which should be present when this executes) and get the text value from that:
jQuery('.models').on('change','select',function() {
var model = jQuery(':selected',this).text();
var modelValue = jQuery(':selected',this).val();
});
Note: your fiddle and markup has it diabled, of course it would need to be enabled first, something like:
jQuery('.models>select').prop('disabled',false);
EDIT: Using your fiddle, I mashed around, commented out your load - as it does not work there and the cleanstring, not present, and this works:
jQuery('.brands').change(function () {
alert('here');
var brand = jQuery('.brands option:selected').text();
// brand = cleanString(brand);
//jQuery('.models').load('/pf-models #' + brand);
jQuery('.models>select').append('<option >She is a classic</option>').prop('disabled', false);
});
alert(jQuery('.models>select').prop('disabled'));
jQuery('.models').on('change', 'select', function () {
var model = jQuery(":selected", this).text();
alert(model);
model = cleanString(model);
jQuery('#show-models').load('/pf-urls #' + model);
});
updated fiddle: http://jsfiddle.net/HNgKt/6/
EDIT Further detailed example, still based on the valid markup assumptions coming back from the load on the first part which I have substituted for a html replace since we have not access to that part:
jQuery('.brands').change(function () {
var brand = jQuery('.brands option:selected').text();
$('.models').html('<select class="models"><option >' + brand + ' She is a classic</option><option>clunker</option></select>');
});
jQuery('.models').on('change', 'select', function () {
var model = jQuery(":selected", this).text();
alert('model:' + model);
});
Fiddle for that: http://jsfiddle.net/HNgKt/7/
Alerts the model if you choose a brand, then a model.
Try following steps,
on change of brands list make an ajax call and make sure in result you recieve the new list options or you can dynamically prepare the options list in jquery also.
And on success of call repopulate new list with the received data.
jQuery('.brands').change(function() {
var brand = jQuery('.brands option:selected').text();
brand = JSON.stringify(cleanString(brand));
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: brand , //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (data) {//On Successful service call
var $newList = $(".models select'").empty();
$newList.append(data);
},
error: function(){} // When Service call fails
});
});
Try the following:
/* using delegate version of .on */
jQuery(document).on('change', '.brands', function() {
var brand = jQuery('.brands option:selected').text();
brand = cleanString(brand);
jQuery('.models').load('/pf-models #' + brand);
});
jQuery(document).on('change', '.models select', function() {
var model = jQuery('.models option:selected').text();
model = cleanString(model);
jQuery('#show-models').load('/pf-urls #' + model);
});
For dealing with "dynamic" elements, you want to use delegate to assign action. This basically reserves a method to be assigned to all elements who match the description.
See also:
http://api.jquery.com/delegate/
http://api.jquery.com/on/#direct-and-delegated-events
I have a sendData.JSON.aspx page that sends data to the textfile called Print.txt.
but i want to Print only data that is selected on my web-browser page/HTML PAGE ,NOTE on that web-browser page
the DATA is selected on a TABLE . and i have a checkbox column so i want to print all selected ROWS accordingly.
Here is my code to print:
function printSelected()
{
var selecteditems = hesto.ui.getselecteditems('#scannedlabeltable');
$.each(selecteditems, function (i, item) {
$.ajax({
url: SEND_TO_TEXTFILE_PAGE
, data: "serial=" + item.id
, datatype: 'json'
, success: function (status) {
if (status.error) {
alert(status.error);
}
}
, error: hesto.ajax.errorhandler
});
});