get the multiple checked value from select tag using multiple="true" - javascript

<Select id="chkProduct" multiple="true">
</select>
<script type="text/javascript">
$(function () {
$(document).ready(function() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'http://###.##.##.##/####/Country.svc/ProductBind',
data: '{}',
dataType: "json",
processData: false,
success: function (data) {
var oi;
for (var i = 0; i < data.Data.length; i++) {
appendString = "<option value='"+data.Data[i].Product+"'>"+data.Data[i].Product +"</option>";
$("#chkProduct").append(appendString);
}
},
error: function (result) {
alert("Error");
}
});
});
});
</script>
i need some suggestion how can i get the checked value after binding the data..
this dropdown bind checkbox with default OK AND CANCLE button and on OK cleck i get single checked value instead if multiple checked value...
it allow to select multiple check but it take single checked item value...and i want multiple checked value

For a multiple select, the .val() returns an array of the selected values (not text). Here is an example:
Given an empty select and a button we'll click to get the selected values
<select name="chkProduct" id="chkProduct" multiple="true" data-native-menu="false">
</select>
<button id="btnGet">Get Selected</button>
The script loads some options on pagecreate (this would be your ajax function) and then the click handler displays the selected values as a comma delimited list:
$(document).on("pagecreate", "#page1", function(){
var appendString = '';
for (var i = 0; i < 6; i++) {
appendString += "<option value='"+ i +"'>item "+ i +"</option>";
}
$("#chkProduct").empty().append(appendString).selectmenu( "refresh" );
$("#btnGet").on("click", function(){
alert($("#chkProduct").val());
});
});
Here is a working jsFiddle

Related

Why does the dropdown displays options one by one on first click when using append()

$(document).on('focus', '.resource_person', function() {
var topic_code = $(this).attr('id');
var rp_reference = $(this).attr('selected-rp');
var option = '';
$.ajax({
type: 'POST',
url: siteUrl + 'course_management/Training_courses/topic_rp',
data: {topic_code: topic_code},
dataType: 'json',
success: function(source) {
$('.resource_person[id="'+topic_code+'"]').empty();
for (var key in source) {
if (source[key] != rp_reference) {
option += '<option value="'+source[key]+'">'+key+'</option>';
} else {
option += '<option value="'+source[key]+'" selected="">'+key+'</option>';
}
}
console.log(option);
$('.resource_person[id="'+topic_code+'"]').append(option);
}
});
});
This what was happening when I first click the dropdown
After clicking it for the second time it goes back to the normal behavior of dropdown
On first click it makes request causing delay to show items, but it uses cahce on second request.
If you force request not to use cache, same delay will happen every time:
$.ajax({
cache: false,
//other options...
});
Note: Setting cache to false will only work correctly with HEAD and
GET requests.

Reset the data after unchecking the checkbox

I have some results in div's ,each result has one checkbox associated with it, when a user click on single checkbox user, Current checked box's value is passed to another page using an ajax call and data is fetched and displayed in a hidden div box.
Now problem is, when user uncheck the checkbox it should remove the data associated with the checkbox.
My code is :
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(".compare").change(function() {
if(this.checked) {
var check = $(this).val();
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').append(data);
}
});
}
});
});
Use something like this to empty the contents of the DIV
$('#compare_box').empty()
better way is to keep the reference map, something like this
$(document).ready(function() {
var boxes = {};
$(".compare").change(function() {
var check = $(this).val();
var data = $(this).closest('.box').clone();
if (this.checked) {
boxes[check] = data;
$('#comparebox').append(boxes[check]);
} else if (!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
});
});
EDIT - should be working (not tested)
var check = $(this).val();
if (this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType: 'JSON',
data: {
value: check
},
success: function(data) {
boxes[check] = $(data);
$('#compare_box').append(boxes[check]);
}
});
} else if(!this.checked && boxes[check]) {
boxes[check].remove();
delete boxes[check];
}
DEMO

AJAX filled Select2 not clickable

I'm using Select2 for a project. The second select box gets filled depending on the selected item in the first box, as shown in the link below. However, I can't click the first item in the second select box for some reason. The only way for me to select the first item if I want to, is to first select a different user, and then back to the first. How can I solve this?
Video:
My code:
This is the first select box, getting filled by regular PHP (Laravel). Everything works fine here.
<div class="form-group">
<label for="select"> Partner: </label>
<select id="select" name="select" class="searchselect searchselectstyle">
#foreach($partners as $i => $partner)
<option {{$i == 0 ? 'selected' : ''}} value="{{$partner->id}}">{{$partner->name}}</option>
#endforeach
</select>
</div>
Here Is the second select box, with the error.
<div class="form-group" >
<label for="select2"> Hoofdgebruiker: </label>
<select id="select2" style="min-width: 200px;" name="select2" class="searchselect searchselectstyle">
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
var url = '/json/getusers';
var $post = {};
$post.id = $("select").val();
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: $post,
cache: false
}).done(function(data){
$('#select2')
.find('option')
.remove()
.end();
$.each(data, function(i, value) {
console.log(data);
$('#select2').append($('<option>').text(value.text).attr('value', value.id));
});
}
);
});
-
public function getusers(){
if(!isset($_POST['term'])){
$users = User::where('partner_id', $_POST['id'])->get();
}else{
$wildcard = '%'.$_POST['term'].'%';
$users = User::where('partner_id', $_POST['id'])->where('email', 'LIKE', $wildcard)->get();
}
$array = array();
foreach($users as $i => $user){
$array[$i] = array("id" => $user->id, "text" => $user->email);
}
return response()->json($array);
}
Check the case sensitivity of the key "id" in json data. Probably you return "ID" insteat of "id".
{"results":[{"id":"3","text":"Exampe 3"},{"id":"4","text":"Example 4"},{"id":"16","text":"Example 16"}]}
not like that
{"results":[{"ID":"3","text":"Exampe 3"},{"ID":"4","text":"Example 4"},{"ID":"16","text":"Example 16"}]}
I found a solution, which is the following:
<script type="text/javascript">
$(document).ready(function() {
$(".searchselect").select2();
search();
$("#select").change(function(){
search();
});
});
function search(){
var $post = {};
$post.id = $("#select").val();
$("#select2").select2({
ajax: {
dataType: "json",
type: "POST",
data: function (params) {
var query = {
term: params.term,
id: $post.id
};
return query;
},
url: '/json/getusers',
cache: false,
processResults: function (data) {
return {
results: data
};
}
}
});
}
</script>
Now I'm using the regular AJAX functionality built in Select2, it is all working as expected now!

Get select multiple values with JQuery

I have a problem with JQuery, I have a multiple select that i can populate in 2 ways, manually taking some value from another select with a add button, and dynamically, with parsing a json returned from a spring call.
I have no problem to take the value when I add it manually, but, when I populate dynamically the select, the JQuery code doesn't take any value although int the html code there're values in the select.
Here my code:
The empty html selects
<div id="enti_disp_box">
<label>Enti disponibili</label>
<select id="ente" multiple> </select>
<button class="btn" onclick="addEnteInBox();" type="button">Aggiungi</button>
</div>
<div id="enti_att_box">
<label>Enti attivi*</label>
<select id="entiAttivi" multiple></select>
<button class="btn" onclick="removeEnteInBox();" type="button">Rimuovi</button>
</div>
JQuery for populate the second select manually
function addEnteInBox(){
var selectedOptions = document.getElementById("ente");
for (var i = 0; i < selectedOptions.length; i++) {
var opt = selectedOptions[i];
if (opt.selected) {
document.getElementById("entiAttivi").appendChild(opt);
i--;
}
}
}
function removeEnteInBox(){
var x = document.getElementById("entiAttivi");
x.remove(x.selectedIndex);
}
JQuery for populate the second select dynamically
function getEntiByIdUtente(idutente) {
var action = "getEntiByidUtente";
var payload = {
"idUtente": idutente,
"action": action,
"token": token
};
$.ajax({
type: "POST",
url: '../service/rest/enti/management_utenti',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(payload),
resourceType: 'json',
success: function(obj, textstatus) {
obj = obj.trim();
var json = JSON.parse(obj);
//parse response
if (obj.stato == 'error') {
alert('Errore');
} else {
$('#entiAttivi').empty();
//fetch obj.data and populate table
$(json.data).each(function() {
$("#piva").val(this.piva);
$("#codiceipa").val(this.codiceipa);
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
});
}
return json;
},
error: function(obj, textstatus) {
alert('Errore di comunicazione col server!');
}
});
}
JQuery for taking the value of the second select
var entiList = $("#entiAttivi").val();
This line seems to be wrong, it's not working for me
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
would you try replacing by
$('#entiAttivi').append($('<option value="' + this.idente + '">' + this.regionesociale + '</option>');
The append, is trying to create an option with the json as parent, this is not working. please try my code.

Issue with Data returning from AJAX call showing up in Bootstrap Multiselect dropdown

I am using Bootstrap Multiselect from http://davidstutz.github.io/bootstrap-multiselect/#getting-started
However, my dropdown is not showing my results...or even dropping down for that matter. Not sure if it makes any difference, but I am using this in a Modal and I am using this along side AngularJS.
This is all I should have to put on my HTML page (according to the website above):
<select id="primaryCategory-dropdown" multiple="multiple"></select>
I am making the following AJAX call to my service:
function loadPrimaryCategories() {
$.ajax({
url: '/Portal/api/PrimaryCategories/GetAll',
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data, function(i, primaryCategory) {
$("#primaryCategory-dropdown").append('<option value="' + primaryCategory.Id + '">' + primaryCategory.Name + '</option>');
});
},
error: function(data) {
alert(data);
}
});
}
I am getting results back(I have 57 to be exact):
<option value="1">2004 Examination
<option value="2">341 Meeting
<option value="3">Abandonment
But the button does not open to show my results. It will enable and disable when I click on it. You can also see a scroll list box appear with all the values when I change the style='display: block'. It almost seems like it isn't binding properly.
I am following the same instructions as this example, but once I implement it into my solution it doesn't work: https://jsfiddle.net/3p3ymwwc/
I tried with $("#ddlState").multiselect('refresh');
but it didn't work for me.
But when I replaced 'refresh' with 'rebuild' it works:
$("#ddlState").multiselect('rebuild');
I found it!
I needed to add to my ajax call 'async: false'
try adding the refresh call inside the success method:
$.ajax({
url: '/Portal/api/PrimaryCategories/GetAll',
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data, function(i, primaryCategory) {
$("#primaryCategory-dropdown").append('<option value="' + primaryCategory.Id + '">' + primaryCategory.Name + '</option>');
});
$("#primaryCategory-dropdown").multiselect('refresh');
},
error: function(data) {
alert(data);
}
});
You might be loading multiselect.js file before the option list updated with AJAX call so while execution of multiselect.js file there is empty option list is there to apply multiselect functionlaity.
So first update the option list by AJAX call then initiate the multiselect call you will get the dropdown list with the dynamic option list.
Hope this will help you out.
// Multiselect dropdown list related js & css files
[http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css][1]
[http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js][2]
// This function should be called while loading page
var loadParentTaskList = function(){
$.ajax({
url: yoururl,
method: 'POST',
success: function(data){
// To add options list coming from AJAX call multiselect
for (var field in data) {
$('<option value = "'+ data[field].name +'">' + data[field].name + '</option>').appendTo('#parent_task');
}
// To initiate the multiselect call
$("#parent_task").multiselect({
includeSelectAllOption: true
})
}
});
}
// Multiselect drop down list with id parent_task
<select id="parent_task" multiple="multiple">
</select>
Even if anyone is facing problem in populating the dropdown after ajax call using jquery-multiselect plugin..
Try using reload instead of "refresh" OR "rebuild"
$('#select-id').change(function(){
var selectedId = $('#select-id').val();
$.ajax({
url: 'url-to-action', //getDatafromYourMethod()
type: "post",
dataType: "json",
data: {
data: 'fetchData',
name: selectedId
},
crossDomain: true,
success: function(returnData) {
var options = '';
$.each(returnData, function(key, value){
options +='<option value='+key+'>'+value+'</option>';
})
$('#select-ids').html(options);
$('#select-ids').multiselect('reload');
}
});
});
idk why your code isn't being rendered properly, but do give this a try.
Instead of appending one by one , store that html data as a string in variable and then once you have finsihed iterating over all the items, append them at once. Try putting this in inside your success: function(data)
let htmldata=""
$.each(data, function(i, primaryCategory) {
htmldata+= '<option value="' + primaryCategory.Id + '">' + primaryCategory.Name + '</option>';
});
$("#primaryCategory-dropdown").html(htmldata);
},
TRY THIS,100% YOU WILL GET EXPECTED OUTPUT
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="bootstrap-2.3.2.min.js" type="text/javascript"></script>
<script src="bootstrap-multiselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "multiselect.aspx/BindStates",
dataType: "json",
async: false,
success: function(data) {
var select = $("#ddlState");
select.children().remove();
if (data.d) {
$(data.d).each(function(key,value) {
$("#ddlState").append($("<option></option>").val(value.State_id).html(value.State_name));
});
}
$('#ddlState').multiselect({includeSelectAllOption: true});
$("#ddlState").multiselect('refresh');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
});
</script>
<center>
<select id="ddlState" name="ddlState" multiple="multiple">
</select>
</center>
</div>
include this css in top

Categories