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.
Related
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 am new to web development and currently experimenting with HTML forms. I am using Chrome to test out how to show JSON data in a div based on a selection from a tag using jQuery, and my code is not working. When I inspect my webpage, it shows the div for the JSON to load, but the data itself is not there after selecting an element from the dropdown menu. Also, I'm using a stylesheet if that makes any difference. Am I going about this incorrectly?
<json>
{
"firstName": "Jason",
"lastName": "Bourne"
},
{
"firstName": "John",
"lastName": "McClane"
}
<html>
<div id="names">
<select id ="drop-list">
<option value="" disabled="disabled" selected="selected">--Select A Name--</option>
<option>Jason Bourne</option>
<option>John McClane</option>
</select>
</div>
<javascript>
$(function() {
let names = $('#names');
dropList.on('select', getDataViaAjax);
function getDataViaAjax(evnt) {
let request = $.ajax({
method: 'GET',
url: 'people.json',
dataType: 'json',
});
request.done(function(data) {
console.log(data);
let dropList = $('#drop-list');
for (let person of data) {
let newParagraph = $('<p>');
newParagraph.text(person.firstName + ' last name ' + person.lastName);
dropList.append(newParagraph);
}
});
request.fail(function(response) {
console.log('ERROR:' + response.statusText);
});
}
});
I used to use this structure, I thinks its simple but efective, hope it works:
//in your html
<form>
<select id="filterAgendas">
</select>
</form>
//In app,js
$.ajax({
url: 'YourJsonFileLocation',
type: 'GET',
success: function(response) {
console.log(response);
const list = JSON.parse(response);
let filter = '';
list.forEach(list => {
filter += `<option value="${list.id}"> ${list.name}</option>`
});
$('#filterAgendas').html(filter);
}
});
//your json file
{
{
id: 1,
name: name1
},
{
id: 2,
name: name2
},
}
i have select2 dropdown like:
<select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />
and i am setting dropdown data by ajax call like:
$.ajax({
type: "POST",
url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
data: '{LedgerId: "' + AccId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.Result == "OK") {
var challanresults = [];
$.each(data.d.Records, function (index, challn) {
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
});
eachtr.find('.txtSelectChallan').select2({
placeholder: "Select Challan",
data: challanresults,
multiple: true
});
swal.close();
challanresults = null;
}
},
error: function (err) {
swal(
'Oops...',
'Error occured while retrieving data',
'error'
);
}
});
and i get dropdown like :
<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
<option value="1006">123123</option>
<option value="1007">32123</option>
i have tried to set option attribute using:
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
but i cant get amout as option attribute any idea how to set custom attribute for all option in select2?
Try like this inside foreach loop, and set the trigger after that.
var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};
var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');
Check this link for further solution on custom attributes
Or Simply you can do like this in a loop for the result set
var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>
This is what Select2 Official Site has to say about custom-data-fields
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
Click here for the above reference link
I have a Select 2 drop down search function. I am trying to load the results from an ajax call as the selected/default values. I am not sure where I am going wrong? What is the syntax I need to change here so that when I click my modal it shows results preset.
$(document).ready(function() {
$('.editApptModal-button').click(function() {
var appointmentID = $(this).attr('data-appointmentID');
$('#editApptModal').find('input[name="appointmentID"]').val(appointmentID);
$.ajax({
type: 'ajax',
method: 'get',
url: '/ajax',
async: false,
dataType: 'json',
success: function(response) {
console.log(JSON.stringify(response));
$.each(response.employees.data, function(key, value) {
$('select').append($("<option selected></option>",
//<HERE Selected is not working.
//If I remove selected results load in dropdown
{
value: value.id,
text: value.name
}));
});
$('#editApptModal').modal('show');
},
error: function(response) {
alert('Could not displaying data' + response);
}
});
$('#editApptModal').modal('show');
});
});
<select multiple="multiple" name="employees[]" id="form-field-select-4" class="form-control search-select">
<option selected value=""></option>
First you should try to append only once because it's an heavy operation.
And by setting attributes directly seems to work here.
var datas = [
{value: 'toto', text: 'Toto'},
{value: 'titi', text: 'Titi'}
];
var options = '';
$.each(datas, function(key, value) {
options += '<option selected>'+value.text+'</option>';
});
$('#select').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple id="select"></select>
You have to issue the refresh command after you are done. Here a quick snippet of it working doing the same thing for one of my projects. TransportRecord_TransportCarrierID is the ID for my select element.
$('#TransportRecord_TransportCarrierID').empty();
$.each(jsonResponse, function (key, item) {
var option = $('<option selected>').text(item.Text).val(item.Value);
$('#TransportRecord_TransportCarrierID').append(option);
});
$('#TransportRecord_TransportCarrierID').selectpicker('refresh');
Html
<select class="form-control selectpicker" data-live-search="true" data-style="btn-defaultWhite" multiple="multiple" id="TransportRecord_TransportCarrierID" name="TransportRecord.TransportCarrierID">//your initial options</select>
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