I have the following multi-select picker which is populated with data. I want to be able to set multiple selected values that I get from the database.
<div class="form-group col-md-6 col-lg-6 col-sm-6">
<label>Choose Skills</label>
<select id="DDLSkills" name="selValue" data-live-search="true" data-style="btn-default form-control" class="selectpicker form-control" data-size="5" multiple data-max-options="2"></select>
</div>
This is the code that I use to populate the multi-select picker:
$('.selectpicker').selectpicker();
$.ajax({
type: "POST",
url: '/TutorSkills/FetchTutorSkills',
success: function (data) {
//console.dir(data);
for (var i = 0; i < data.length; i++) {
$("#DDLSkills").append('<option data-tokens="' + data[i].Skill.SkillName + '" value="' + data[i].Skill.Id + '">' + data[i].Skill.SkillName + '</option>');
}
$("#DDLSkills").selectpicker("refresh");
},
error: function (error) {
alert('Failed to get the logged-in tutor skills!');
}
})
However, I want to be able to set selected values that I get from the database but the code below only sets the last value that I get from the database.
$.ajax({
type: "POST",
url: '/ClassSkills/GetClassSelectedSkills',
data: { 'id': selectedEvent.id },
success: function (data) {
console.dir(data);
for (var i = 0; i < data.length; i++) {
$('.selectpicker').selectpicker('val', [data[i].Skill.Id]);
}
$('.DDLSkills').selectpicker('refresh')
},
error: function (error) {
alert('Failed');
}
})
Thank you
Try if this work
$.ajax({
type: "POST",
url: '/ClassSkills/GetClassSelectedSkills',
data: { 'id': selectedEvent.id },
success: function (data) {
console.dir(data);
let optArr = [];
for (var i = 0; i < data.length; i++) {
optArr.push(data[i].Skill.Id);
}
$('.selectpicker').selectpicker('val', optArr);
$('.DDLSkills').selectpicker('refresh')
},
error: function (error) {
alert('Failed');
}
})
Related
I have a dropdown and when I select an option I run one ajax call, on pc is working as expected but on iPhone is not triggering the ajax, it goes to the function and I know this because I added alerts.
When i click 13,14,15 is not working. At 9,10,11,12 is working.
<div class="row" id="type">
Selected type: #Html.DropDownListFor(model => model.GymType, listItems, new { id = "GymType", onchange = "getBookTime();" })
</div>
<div id="timesList" style="display:none;margin:auto">
Selecte time: <select id="states_ddl" name="states_ddl" class="cs3 input-small" > </select>
</div>
function getBookTime(e) {
var selectedtype = $('#GymType').val();
alert(selectedtype);
var selectedDate = $('#date').text();
$.ajax({
type: "GET",
async: false, //This makes the JQuery below wait until $.ajax() call is finished
cache: false,
headers: { "cache-control": "no-cache" },
url: '/Home/GetBookTime/',
data: { date: selectedDate, type: selectedtype },
success: function (data) {
if (data.message != undefined) {
alert(data.message);
$('#error').show();
document.getElementById("errormsg").innerHTML = data.message;
}
else {
alert(data);
$('#error').hide();
$("#timesList").show();
var options = $("#states_ddl");
options.empty();
$.each(data, function (index, item) {
options.append($("<option />").val(item).text(item));
});
}
$("#submitbtn").show();
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
})
}
I've created the options using jquery:
<select name="models" class="form-control" id="models" style="width: 100%">
<option value="0" class="select_model"> - </option>
</select>
jQuery:
var p = {
event : 1
}
$.ajax({
type: "POST",
url: base_url + 'report/models',
data: p,
dataType: "json",
success: function(data){
var i;
for (i = 0; i < data.models.length; i++) {
$('.select_model').empty().append($('<option>', {
value: data.models[i].model_id,
text : data.models[i].model_name
}));
}
},
error: function(xhr, status, error) {
$.alert({
title: 'CAUTION!',
content: "Theres an error: " + xhr.status + " - " + xhr.statusText,
type: 'red',
icon: 'fa fa-warning',
});
}
});
then, when I call the event change, it just don't work:
$("#models").select2().change(function(){
console.log('worked');
});
When I chose an option on the select, it not even log the message. What's wrong?
I have a form with dynamic rows, after fetching record I want to update status of selected rows by checkbox.
I'm successfully getting each row checkbox values and dynamic row id in console but when trying to update values, it's updating first row only.
HTML:
<button type="button" class="btn btn-info" id="update_status_btn">Update Status</button>
Fetched record:
success: function(data){
var trHTMLr = '';
$.each(data,function(i,row){
trHTMLr += '<tr>' +
'<td><input type="text" name="first_name" class="form-control text-center" value="' + row.first_name + '" /></td>' +
'<td><input type="checkbox" name="status" class="form-control text-center updatestatusclass" data-id="' + row.id + '" value="' + 'YES' + '"/></td>' +
'</tr>';
});
$('#mytable').append(trHTML);
}
Update status:
$("#update_status_btn").click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var eachrow_value=[];
$('.updatestatusclass').each(function(){
if($(this).is(":checked"))
{
eachrow_value.push($(this).val());
}
});
eachrow_value=eachrow_value.toString();
var row_id = $('.updatestatusclass').attr('data-id');
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {id: row_id, status: eachrow_value},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
});
Controller:
if ($request->ajax()) {
$stat = Services::where('id', $request->get('id'))
->update(array(
'status' => $request->get('status')
));
return Response::json($stat);
}
I want to update status of selected row by checkbox with it's respective row ID.
What you are looking for is to update multiple checkboxes in one go. So, you need to store both selected & unselected checkboxes.
Your jQuery
let checkedIds = [];
let unCheckedIds = [];
$('.updatestatusclass').each(function () {
if ($(this).is(":checked")) {
checkedIds.push($(this).attr('data-id'));
} else {
unCheckedIds.push($(this).attr('data-id'));
}
});
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {
checkedIds: checkedIds,
checkedIdStatus: 'active', //do your thing
unCheckedIds: unCheckedIds,
unCheckedIdStatus: 'inactive', //do your thing
},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
In your Controller
if ($request->ajax()) {
Services::whereIn('id', $request->get('checkedIds'))
->update(array(
'status' => $request->get('checkedIdStatus')
));
Services::whereIn('id', $request->get('unCheckedIds'))
->update(array(
'status' => $request->get('unCheckedIdStatus')
));
}
Hope this helps. Cheers!
I am using select multiple control using selectsize.js here is my control
<div class="default selectize-control multi">
<select multiple id="select-email" class="selectize-input items has-options has-items full">
#*<option value="0">Zero</option>
<option value="1">One</option>
</select>
</div>
I am trying to bind this control through ajax
here is my Ajax code
var selectemailemail = $("#select-email");
selectemailemail.empty().append('<option selected="selected" value="0" disabled = "disabled">Loading.....</option>');
$.ajax({
type: "GET",
url: "/api/Customer/GetCustomerList",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
console.log('response', data);
for(var i=0;i<data.length;i++)
{
console.log('data[i].email' + data[i].Email);
$("<option value=" + data[i].TokenId + ">" + data[i].Email + ")</option>").appendTo(selectemailemail);
}
selectemailemail.multipleSelect('refresh');
},
failure: function (response)
{
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
};
while running ajax codei am getting data in an array
here is the data in an array
{Id: 0, ContactNo: null, FirstName: null, LastName: null, Email: "verveshivam#gmail.com ", …}
and i want to try to bind the email value in that selected multiple control using code here is my code
for(var i=0;i<data.length;i++)
{
console.log('data[i].email' + data[i].Email);
$("<option value=" + data[i].TokenId + ">" + data[i].Email + ")</option>").appendTo(selectemailemail);
}
but it is not binding the value
in console it is not showing error in console alsoso how can i bind the value in selected multiple control.
I have this html markup:
<!-- ko foreach: Orders -->
<div class="row">
<div>
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
</select>
</div>
<div>
<a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
<span class="glyphicon glyphicon-cloud-download"></span> Download
</a>
</div>
</div>
<!-- /ko -->
There will be n number of items in the foreach loop, that will not be known in the moment of development.
What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message.
So in the RequestImage that action should happen, this is the RequestImage function currently:
self.RequestImage = function () {
};
How can I achieve this?
Update
OrdersVM:
var self = this;
self.Orders = ko.observableArray([]);
$.ajax({
type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var orderIds = [];
ko.utils.arrayForEach(data.d, function (item) {
item._teacherOrders = ko.observable();
$.ajax({
type: "POST",
url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
contentType: "application/json; charset=utf-8",
data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
dataType: "json",
success: function (data) {
if (data) {
return item._teacherOrders(data.d);
}
},
error: function (n) {
alert('Error retrieving teachers for orders, please try again.');
}
});
item.TeacherNames = ko.computed(function () {
return item._teacherOrders();
});
self.Orders.push(item);
orderIds.push(item.OrderId);
});
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
console.log("error retrieving orders:" + response.Message);
}
});
I would do it this way:
add an observable selectedTeacher to every order object
add value: selectedTeacher to your selects:
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>
check that observable in your RequestImage event
if ( !data.selectedTeacher() ) {
alert('Error: select teacher')
} else {
alert('Success')
}
A working demo - Fiddle