Sir, my ajax isnt loading when i use select2 plugin .
it works fine when i remove it. the blur event is working.
but i want to be able to search in the dropdown, and somehow ajax isnt working
this part isnt working
$("#bank_id").focus();
so due to above script not working the blur event in the code below isnt working.
this is the script and html
<div class="col-md-6">
<div class="form-group">
<label>Bank<span><font color="red"></font></span></label>
<select class="form-control select2" name="bank_id" id="bank_id">
<c:choose>
<c:when test="${bankDetailsEdit.bank_id != 0}">
<option value="${bankDetailsEdit.bank_id }" >${bankDetailsEdit.bankName }</option>
</c:when>
<c:when test="${bankDetailsEdit.bank_id == 0}">
<option disabled selected>Select Bank</option>
</c:when>
</c:choose>
<c:forEach var="bank" items="${bankMasterDetails}">
<option value="${bank.bank_id}">${bank.bank_name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Bank Branch Name<span><font color="red"> </font></span></label>
<select class="form-control select2" name="bankBranchId" id="op1" >
<option value="${bankDetailsEdit.bankBranchId }" >${bankDetailsEdit.bankBranchName }</option>
<c:forEach begin="0" end="100" varStatus="loop">
<option></option>
</c:forEach>
</select>
</div>
</div>
<script>
$('.select2').select2();
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#bank_id").focus();
$("#bank_id").on('blur change',function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var bank_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'bank_id':bank_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/bankBranchDetails",
data : ({
'bank_id':bank_id
}),
success: function (bankList) {
$('#op1').empty();
var opt = '<option disabled selected>Select Branch</option>';
for (var i = 0; i < bankList.length; i++) {
$('#op1').append(opt);
opt = new Option(bankList[i].bank_branch_name,bankList[i].bank_branch_id);
}
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
$("#op1").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var branch_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'branch_id':branch_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/branchIfscDetails",
data : ({
'branch_id':branch_id
}),
success: function (data) {
var ifsc = data;
document.getElementById("ifsc").value=ifsc;
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
});
</script>
From this page: https://select2.org/programmatic-control/events:
Select2 has an internal event system that works independently of the
DOM event system, allowing adapters to communicate with each other.
You are tied to using the plugins event handling mechanism so the first paremeter of the jQuery on function needs to be changed.
from $("#bank_id").on('blur change',function(){
to $("#bank_id").on('select2:select',function(){
Unfortunately $("#bank_id").focus(); will not work because it is not listed in the available select2 events.
You're success callback function in the first event listener, which tries to generate options element for the 2nd select box will also not work as select2 has a different way of adding options dynamically through AJAX as listed in this page: https://select2.org/data-sources/ajax
You need to use $('#bank_id').select2('open'); instead of $("#bank_id").focus(); to open the bank selection on page load.
You can check their documentation.
Related
I have One Primary drop-down (Country) and second dependent dropdown. (State). This code works fine only when we select primary dropdown. but doesnt work if primary dropdown already selected on page load.
Primary Dropdown Country:
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$profile_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach
</select>
Dependent Dropdown State:
<select class="select4" name="state" id="state">
<option value="">Please Select</option>
#foreach($state_data as $state)
<option value="{{$state->state_id}}" {{$profile_data->state == $state->state_id ? 'selected' : ''}}>{{$state->state_name}}</option>
#endforeach
</select>
Java Script code to fill dependent dropdown.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: 'family/state/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="state"]').empty();
$.each(data, function(key, value) {
$('select[name="state"]').append('<option value="'+ value.state_id +'">'+ value.state_name +'</option>');
});
}
});
}else{
$('select[name="state"]').empty();
}
});
});
How Ajax code must work on page load also?
You're going to need to manually trigger the change event.
After your:
$('select[name="country"]').on('change', function() { ... }
Force trigger:
$('select[name="country"]').trigger('change');
That way when your document.ready function is about to wrap up, you can force trigger the event and if its set, it'll fire the ajax call
Iam currently using select2 jquery plugin to select data from list dynamically populated from an ajax call. I need to implement select all functionality so that users are able to select all the options at once by using a select all button. I have tried to implement this following this example in jsfidde.
Click here to see the jsfiddle
But for selecting a listing of larger number of items say 500 items.It makes the browser hang for a while. Please suggest a better way to implement this without any performance issues.
$.fn.select2.amd.require([
'select2/utils',
'select2/dropdown',
'select2/dropdown/attachBody'
], function (Utils, Dropdown, AttachBody) {
function SelectAll() { }
SelectAll.prototype.render = function (decorated) {
var $rendered = decorated.call(this);
var self = this;
var $selectAll = $(
'<button type="button">Select All</button>'
);
$rendered.find('.select2-dropdown').prepend($selectAll);
$selectAll.on('click', function (e) {
var $results = $rendered.find('.select2-results__option[aria-selected=false]');
// Get all results that aren't selected
$results.each(function () {
var $result = $(this);
// Get the data object for it
var data = $result.data('data');
// Trigger the select event
self.trigger('select', {
data: data
});
});
self.trigger('close');
});
return $rendered;
};
$("select").select2({
placeholder: "Select Option(s)...",
dropdownAdapter: Utils.Decorate(
Utils.Decorate(
Dropdown,
AttachBody
),
SelectAll
),
});
});
this is the duplicate question of
JQuery Select2 - How to select all options
where solution given for multiple select with checkbox.
if its getting load than you should add extra hidden filed to get comma separated value.
try below code.
HTML :
<select multiple id="e1" style="width:300px">
<option value="AL">Alabama</option>
<option value="Am">Amalapuram</option>
<option value="An">Anakapalli</option>
<option value="Ak">Akkayapalem</option>
<option value="WY">Wyoming</option>
</select>
<br>
<input type="checkbox" id="checkbox" >Select All
<br>
<input type="text" id="valueall" value="" name="valueall">
JQuery :
$("#e1").select2();
$("#checkbox").click(function(){
if($("#checkbox").is(':checked') ){
$("#e1 > option").prop("selected","selected");
<!-- $("#e1").trigger("change"); -->
$("#e1").select2('destroy');
$("#e1").hide();
$("#valueall").val($("#e1").val())
}else{
$("#e1 > option").removeAttr("selected");
<!-- $("#e1").trigger("change"); -->
$("#e1").select2();
$("#e1").show();
$("#valueall").val($("#e1").val())
}
});
You can set type="hidden" for input field.
requirement:
when i click a button ,send a ajax request ,get the result and create a list,in this list ,i wan't to use flip-switch widget
i know ,the flip-switch widget won't initialed in the callback automatically,but how could i initial it by myself?
what i tried?
tried the fresh method,but get the error :"fresh can't be used before initial"
tried to trigger the create event ,but it doesn't work.
appreciate your help!
template:<li class="clearfix">
<span class="keyword-name">{{name}}</span>
<div class="keyword-monitor">
<select data-role="slider" data-mini="true" class="monitor" data-ruleid="{{rule_id}}" data-isoff="{{is_off}}" data-type="{{type}}">
<option value="0" >取消</option>
<option value="1" >监测</option>
</select>
</div>
</li>
function initDefaultTab(index){
$.ajax({
url:"/usercenter/defaultwords/"+index,
method: "POST",
dataType: "json"
}).done(function(data){
var html="";
var source = $("#default-keyword-template").text();
var template = Handlebars.compile(source);
for(var i=0;i<data.length;i++){
var $temp=$(template({
name: data[i].name,
rule_id: data[i].rule_id,
is_off:data[i].is_off,
type:data[i].type
}));
if(data[i].is_off===1){
$temp.find("option").eq(0).attr("selected",true)
}else{
$temp.find("option").eq(1).attr("selected",true)
}
html+="<li class='clearfix'>"+$temp.html()+"</li>";
}
var $html = $(html);
$("#defaultword-"+index).find("ul").append($html);
$("#defaultword-"+index).find(".monitor").flipswitch({enhanced:true});
});}
I am using Jquery 1.6.4 and chosen 1.4.1. I am facing issue while rendering the options from AJAX. Following is my code.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".chzn").data("placeholder","Select Frameworks...").chosen();
jQuery("#item").chosen().change(function(e, params){
values = jQuery("#item").chosen().val();
$('#item_selected').val(values);
});
});
$('#customer').click(function() {
var url = "ajax_common.php?action=getItem&companyid=1";
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function(data){
$("#item option").remove();
$("#item").append(data);
$("#item").trigger("liszt:updated");
}
});
</script>
<select class="chzn inpt-fld" multiple="true" name="item" id="item" style="width: 96%">
</select>
But the value is not appending in the multi-select drop-down?
The problem seem came from the way you output ajax response. You can not append options in the select tag dynamically because it is not belong to the current select. Meaning this select can not detect the options that previously not exist (as hard code).
You should include select and option together in ajax_common.php and render in div as innerHtml.
// inside ajax_commond.php :
<select class="chzn inpt-fld" multiple="true" name="item" style="width: 96%">
<option> xxxx </option>
</select>
// render the ajax response in :
<div id="item"></div>
I have this show/hide div. And I am running into couple issues. I am using CodeIgniter by the way.
First : When I select real-estate the div shows. But if I select Service, the real-estate div won't hide. (Service has no div).
Second : If I select real-estate and fill out the form, and I change my mind and select automobile and fill out the form then send to database, I get all the fields from real-estate and automobile into my database. Which is not what I want.
Third : Is there a different approach if I wanna add more categories and more divs show/hide?
<select id="catid_1" name="catid_1">
<option value=""></option>
<option value="5">Real-Estate</option>
<option value="8">Automobile</option>
<option value="10">Service</option>
</select>
<!--Auto-->
<div id="8" class="forms">
Energie :
<select name="energy">
<option></option>
<option value="Gasoline">Gasoline</option>
<option value="Diesel">Diesel</option>
<option value="GPL">GPL</option>
<option value="Electric">Electric</option>
<option value="Hybrid">Hybrid</option>
</select><br />
Transmission :
<select name="tans">
<option></option>
<option value="Manuel">Manuel</option>
<option value="Automatic">Automatic</option>
</select><br />
Miles :
<input type="text" name="mile"/><br />
Year :
<input type="text" name="year"/><br />
</div>
<!--Realestate-->
<div id="5" class="forms">
Room :
<input type="text" name="room"/><br />
Surface :
<input type="text" name="surface"/><br />
</div>
<!--End Tech-->
$(function() {
$(".forms").hide();
$("#catid_1").change(function() {
var e = $(this).val();
if(e == '8' || e == '5') {
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
});
// Bind to the submit
$('#submit').click(function(e){
e.preventDefault();
// Parse the data only for the displayed div.
var resolve_data = function() {
var output = {};
// Here you place the acceptable fields.
$('.form-active input, .default input').each(function() {
output[$(this).attr('name')] = $(this).val();
});
return output;
};
// Submit the form here.
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: resolve_data(),
beforeSend: function(xhr, settings){
// Before sending, check the data.
alert(settings.data);
},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
});
});
first: service show/hide is not working because you're putting a conditional on the ID:
if(e == '8' || e == '5') { // <<-- remove this conditional
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
second: When you're doing your update, check the value of the drop down box and only update the fields that belong to that choice. Your form should be sending along the value of the option, so that's not to hard to do. For instance, if the select value is 5, only update the room and surface fields in your database. Don't try to clear the form when switching choices, it's safer to do this in the back end.
If you insist on doing it front end, put an actual form in there and .reset() it when changing options.
third: probably, but this seems OK no? Are you not happy with it?
http://jsfiddle.net/zf9BN/1/