How to initial a jquery mobile flipswitch in ajax callback - javascript

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});
});}

Related

Data In Input Box Not Going to JavaScript var

Good day! I want to write an ajax request passing two variables to the controller. The problem is that I cannot get the values from the textboxes to my JavaScript
This is the JavaScript and the HTML code.
When I alert the day variable I get nothing it shows that the field is empty. I am very new to programming
$('#historic_form').submit(function(e) {
e.preventDefault();
var fund_id = $(this).val();
var day = $(this).val();
//data = $('#historic_form').serialize();
$.ajax({
url:'Search/Searchday',
type: 'POST',
dataType:'json',
data: {fund_id: fund_id, day: day},
error: function() {
alert(day);},
success: function(response) {
$("tbody").append("<tr><td>"+title+"</td><td>"+description+"</td></tr>");
}
});
});
And below are my HTML Codes
<select required id="member_id" name="member_id" class="form-control">
<option selected disabled>Select Member</option>
<?php for ($i=0;$i<$fMembers->num_rows();$i++){
echo "<option value='".$fMembers->row($i)->id."'>".$fMembers->row($i)->member_name."</option>";}?>
</select>
<select required class="form-control" id="fund_id" name="fund_id">
<option selected disabled>Select Fund</option>
</select>
<input type="date" required name="day" placeholder="Select a date" class="form-control datepicker hasDatepicker" data-dateformat="dd/mm/yy" id="histDate">
$('#historic_form').submit(function(e) {
Your event handler is triggered by a form submission, so inside the function this will refer to the <form>.
var fund_id = $(this).val();
var day = $(this).val();
<form> elements don't have values. You need to find() the <select> element you want to read the value from and call val() on that.

Refresh selectpicker options after jQuery success is not working

I am trying to refresh a select after executing another jQuery.
I am creating firstly the select options using cURL, which produces code like this.
$json_dropdown = '[{"id":"1475471145964056","name":"Option1"},
{"id":"935675176941821","name":"Option2"},
{"id":"555309881810660","name":"Option3"},
{"id":"304608093904515","name":"Option4"}]';
Then I have the HTML that looks like htis
<h2>Delete topic</h2>
<div class="form-group">
<select class="form-control selectpicker show-tick" name="topic" id="topic_del" data-show-subtext="true" data-live-search="true" showIcon="true" data-style="btn-default" data-size="8" data-width="100%" title="Choose a TOPIC to DELETE..." required></select>
</div>
<div class="form-group">
<button type="button" class="btn btn-danger" id="delete_topic">Delete Topic</button></span>
</div>
<div id="results_del"></div>
I am loading the options into the select with this jquery
$('#topic_del').click(function(){
var a = {Topic:<?echo $json_dropdown; ?>}
$.each(a.Topic, function topics (key, value) {
$("#topic_del").append($('<option></option>').attr('data-tokens',value.id).val(value.id).html(value.name));
//$("#topic").attr('data-tokens',value.id);
});
});
Which works fine.
Then I have another script to delete an option from the select using ajax
// Delete Topic
$('#delete_topic').click(function(){
// bind 'myForm' and provide a simple callback function
$(this).prop("disabled", true);
// add spinner to button
$(this).html(
`<i class="fa fa-spinner fa-spin"></i> Deleting Topic`
);
$(this).removeClass("btn-danger");
$(this).addClass("btn-warning");
var type = $("#type").val();
var action = $("#action_del").val();
var account = $("#account").val();
var topic = $("#topic_del").val();
$.ajax({
type:'POST',
data:{ 'type': type, 'action': action, 'account': account, 'topic': topic },
url:'js/actions.php',
success: function(data){
$('#results_del').html(data);
$('#delete_topic').prop("disabled", false);
$('#delete_topic').html("Delete Topic");
$('#delete_topic').addClass("btn-danger");
$('#delete_topic').removeClass("btn-warning");
var a = {Topic:<?echo $json_dropdown; ?>}
$.each(a.Topic, function topics (key, value) {
$("#topic_del").append($('<option></option>').attr('data-tokens',value.id).val(value.id).html(value.name));
});
}
});
return false;
});
In this script, what I am trying to achieve is to refresh the options after the delete script is successful, using the same script I am using to initially create the options.
It seems I am doing something wrong, but I cannot figure out what.
UPDATE
Just realized that if I remove the selectpicker and try to remove the option that I just deleted from the select in the success like this $("#topic_del option[value='" +topic+ "']").remove(); it will work. However, if I put back the selectpicker it will not remove the option.
Could it be something with the selectpicker not allowing to do it?
I was able to achieve the functionality thanks to this thread Selectpicker with add or delete values
by adding these two lines in the success
$('.selectpicker option:selected').remove();
$('.selectpicker').selectpicker('refresh');
And one other thing. It seems that $('.selectpicker').selectpicker('refresh'); would only execute if there was any other action before that for example $('.selectpicker option:selected').remove();

select2 not letting my other scripts work

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.

Fetch input value after Dropdown menu item selected

I have a table about products. It has id, productdmc, productcode columns.
In this select menu, productdmc is showing.
When one item was selected, label its gonna change with related rows. Thats what i need. But i cant figure out the solution.
productcode.
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
Related input
<input type="text" name="productcode" id="productcode">
This is the js code. I dont know this is working. This is my actual problem.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="productdmc"]').on('change', function() {
var tmp = $(this).val();
if(tmp) {
$.ajax({
url: '/products/create/'+tmp,
type: "GET",
dataType: "json",
success:function(data) {
$('productcode').empty();
$.each(data, function(key, value) {
$('productcode').innerHTML('<input value="'+ key +'">');
});
}
});
}else{
$('productcode').empty();
}
});
});
</script>
In my Controller:
$val = DB::table("products")->pluck("productdmc","productcode");
return json_encode($val);
I know, i messed up so much. But codes are so complicated than this. I write this code in here(shorter version). Not copy-paste. I stucked here in a while. I cant find what is the real solution is.
I am open for all kinda solution.
Sorry for my bad english.
innerHTML is a property of HTML elements, not a function of jQuery's representation.
Use html(content) instead, and I think it should work:
$('#productcode').html('<input value="'+ key +'">');
Your selector is wrong, you forgot the '#'.
var $productCode = $('#productcode');
Also, when the event 'change' is triggered, you need to fetch the selected option.
var selectedValue = $element.find('option:selected').val();
HTML
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
<input type="text" name="productcode" id="productcode">
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('body').on('change', 'select[name="productdmc"]', function(e) {
var $element = $(e.currentTarget); // $(this) is also fine.
// Get selected value
var selectedValue = $element.find('option:selected').val();
var $productCode = $('#productcode');
// No value selected
if (!selectedValue) {
$productCode.val('');
return;
}
$.ajax({
url: '/products/create/' + selectedValue,
type: 'GET',
dataType: 'json',
error: function() {
$productCode.val('');
},
success: function(res) {
$productCode.val('');
if (res.length < 1) return;
$productCode.val(res[0] || '');
// This will populate more than 1 field. So,
// I'm not sure about what you expect on the backend.
// If you want to populate more than 1,
// you should change the selector/field (do not use id in this case)
// $.each(res, function(key, value) {
// $productCode.val(key);
// });
}
})
});
});
</script>
PHP
<?php
$products = DB::table('products')->get();
return response(
$products->pluck('productdmc', 'productcode')->toArray()
);
You can read more about jQuery selectors here: https://api.jquery.com/category/selectors/

Jquery Chosen Ajax call not rendering the options

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>

Categories