after a long search i can't find a way to call an autocomplete function when the document is ready passing a specific variable.
So i got this function that works fine when i select element from autocomplete:
var option_row = <?php echo $option_row; ?>;
$('input[name=\'option\']').autocomplete({
'source': function(request, response) {
$.ajax({
url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(request),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item['category'],
label: item['name'],
value: item['option_id'],
type: item['type'],
option_value: item['option_value']
}
}));
}
});
},
'select': function(item) {
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
etc etc......
after many research i'm thinking to switch to another possible solution...
I wish to call this directly without select item but passing a variable to the function...
i'm trying doing this:
$(document).ready(function(e){
var option_row = <?php echo $option_row; ?>;
var req = 'item';
setOptions(req);
});
function setOptions(req){
$.ajax({
url: 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(req),
dataType: 'json',
success: function(json) {
response($.map(json, function(item) {
return {
category: item['category'],
label: item['name'],
value: item['option_id'],
type: item['type'],
option_value: item['option_value']
}
}));
}
});
'select': function(item) {
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['label'] + '" />';
etc, etc...
}
Now, i don't know what i should use instead of 'select': function(item) { to make it works.
Thanks in advance, any help is appreciated.
Well, i have finally make it... it was more simple than i thought
this is the code:
$(document).ready(function(e) {
var data = 'Adulti';
addOptions(data);
});
var option_row = <?php echo $option_row; ?>;
function addOptions(data){
var base_url = 'index.php?route=catalog/option/autocomplete&token=<?php echo $token; ?>&filter_name=' + encodeURIComponent(data);
var n='';
$.ajax({
url: base_url,
dataType: 'json',
success: function(json) {
$.map(json, function(item) {
category = item['category'];
label = item['name'];
value = item['option_id'];
type = item['type'];
option_value = item['option_value'];
html = '<div class="tab-pane" id="tab-option' + option_row + '">';
html += ' <input type="hidden" name="product_option[' + option_row + '][product_option_id]" value="" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][name]" value="' + item['name'] + '" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][option_id]" value="' + item['value'] + '" />';
html += ' <input type="hidden" name="product_option[' + option_row + '][type]" value="' + item['type'] + '" />';
etc, etc....
Related
I have this code for add dynamic select box and load select2 search for each like this:
<script type="text/javascript">
var attribute_row = <?= $attribute_row; ?>;
function addAttribute() {
html = '<tr id="attribute-row' + attribute_row + '">';
html += ' <td class="text-left"><input type="text" name="product_attribute[' + attribute_row + '][name]" class="attribute-name' + attribute_row + '" value=""><select id="' + attribute_row + '" name="product_attribute[' + attribute_row + '][attribute_id]" class="form-control attributeSelect">';
html += ' </select></td>';
html += ' <td><div class="icheck-primary"><input type="checkbox" id="checkboxAttribute' + attribute_row + '" name="product_attribute[' + attribute_row + '][visible_on_product]" value="1"><label for="checkboxAttribute' + attribute_row + '"></label></div></td>';
html += ' <td><input type="text" name="product_attribute[' + attribute_row + '][text]" value="" placeholder="<?= lang('Product.price'); ?>" class="form-control" /></td>';
html += ' ';
html += ' <td><button type="button" onclick="$(\'#attribute-row' + attribute_row + '\').remove();" data-toggle="tooltip" title="<?= lang('Product.removeAttribute'); ?>" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
$('#attribute tbody').append(html);
$(".attributeSelect").select2({
minimumInputLength: 3,
theme: 'bootstrap4',
width: 'auto',
ajax: {
url: "url",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term,
csrf_token: csfr_token // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
}).on("select2:select", function () {
data = $(".attributeSelect").select2('data')[0];
id = $('.attributeSelect').attr('id');
$(".attribute-name" + id).val(data.text);
});
attribute_row++;
}
</script>
in Action after search and select(on select) result i need to add select2 data.text into this input box:
<input type="text" name="product_attribute[' + attribute_row + '][name]" class="attribute-name' + attribute_row + '" value="">
my code work for first select box and add value to first input box But for second and more also add data to first input.
how do can i fix this problem?
You're always getting the first id when doing this for all the items with that class:
id = $('.attributeSelect').attr('id');
That's why it's setting always the result the first element. You should get the current id of the element receiving the event. You can probably receive that from the event object:
$('#mySelect2').on('select2:select', function (e) {
console.log(e);
});
I have this code in my javascript:
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option>');
I need value['code'] and value2['service'] in hidden inputs so i can save them in my DB, is that possible?
update
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
html
<div id="des"></div>
<div id="calcul" class="mb-20 mt-20">
<select name="postchoose" id="">
<option class="form-control" value="">Select Shiping Method</option>
</select>
<div id="courierinfo"></div> // i want my hidden input in this div
</div>
update 2
here is what i added to my ajax code and returning the result i want, but the problem is it return results like 30 times instead of only once:
$('select[name="postchoose"]').on('change',function(){
var selected = $(this).find('option:selected');
var code = selected.data('code');
var service = selected.data('service');
$('div#courierinfo').append('<input type="hidden" value="'+code+'" name="courier" > <input type="hidden" value="'+service+'" name="courier_service" >');
});
Hope this helps.
$('select[name="postchoose"]').append('<option id="postchoose"
class="form-control" value="'+ value3['value'] +'"
code="'+value['code']+'" service="'+value2['service']+'">'+
value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number)
+' Rp' + ' - ' + value3['etd'] +'</option>');
var code=$('select[name="postchoose"] option:selected').attr('code');
var service=$('select[name="postchoose"]
option:selected').attr('service');
You can add to data attribute of option
<div id="des"></div>
<div id="calcul" class="mb-20 mt-20">
<select name="postchoose" id="" onchange="addInputHidden(this)">
<option class="form-control" value="">Select Shiping Method</option>
</select>
<div id="courierinfo">
<!--i want my hidden input in this div-->
</div>
</div>
<script >
function addInputHidden(element) {
var $option = $(element).find('option:selected'),
code = $option.data('code'),
service = $option.data('service');
if (!jQuery('#courierinfo .code_' + code).length) {
jQuery('#courierinfo').append('<input class="code code_' + code + '" name="code[]" type="hidden" value="' + code + '"><input class="service code_' + code + '" name="service[]" type="hidden" value="' + service + '">');
} else {
jQuery('#courierinfo .code.code_' + code).val(code)
jQuery('#courierinfo .service.code_' + code).val(service)
}
}
jQuery(document).ready(function ($) {
$('body').on('change', 'select[name="city"]', function (e) {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if (cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/' + weight + '/' + encodeURI(cityID),
type: "GET",
dataType: "json",
success: function (data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] + '</p>'
);
$.each(data.data, function (key, value) {
$.each(value.costs, function (key2, value2) {
$.each(value2.cost, function (key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits: 0,
minimumFractionDigits: 0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="' + value3['value'] + '" data-code="' + value['code'] + '" data-code="' + value2['service'] + '">' + value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] + '</option>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
} else {
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
$('select[name="postchoose"]').on('change',function(){
var $option = $(this).find('option:selected),
code = $option.data('code'),
service = $option.data('service');
// you can use ajax to send
})
SOLVED
I added code below at the bottom of my ajax and it's working without looping results many times.
// show selected shipping information
$('select[name="postchoose"]').on('change',function(){
var selected = $(this).find('option:selected');
var code = selected.data('code');
var service = selected.data('service');
$('div#courierinfo').empty();
$('div#courierinfo').append('Shipping: <span name="courier">'+code+'</span> - <span name="courier_service">'+service+'</span><br><input type="hidden" name="courier" value="'+code+'"><input type="hidden" name="courier_service" value="'+service+'">');
});
Thanks to Bai Nguyen for the idea.
Hi how I can call a function in a bootbox jquery?
This is an example, at
select name="Status" I would if possible call a function that shows and hides tr of table called in html_form var. How would I do that?
function ChangeStatusDossier(UtenteCreatore) {
var html_form = '<form name="ChangeStatusDossier" id="ChangeStatusDossier" class="ChangeStatusDossier"><table><tr><th colspan="2"><h2 class="blue">Change Dossier Status</h2></th></tr><tr><td><strong>Choose status </strong> </td><td><select name="Status" onchange="Show(this.value);"><option value="0">Under process</option><option value="1">Under collection</option><option value="2">Cargo collected</option><option value="159">In Warehouse</option><option value="1485">To Destination</option></select></td></tr><tr id ="HubChoose" style="display:none;"><td>Choose hub</td><td><select name="Hub"><option>HUB MILANO</option></select></td></tr><input type="hidden" name="UtenteCreatore" value="' + UtenteCreatore + '"></table><form>';
bootbox.confirm(html_form, function (result) {
if (result) {
$('#ChangeStatusDossier').submit();
}
});
function Show(value) {
if (value == "159") {
$("#HubChoose").show();
}
}
}
In your case it's better to use the dialog method instead of confirm.
Here's how you could do that:
function ShowHub(value) {
if (value == "159") {
$("#HubChoose").show();
}
else {
$("#HubChoose").hide();
}
}
jQuery("#default").on("click", function() {
bootbox.dialog({
title: "This is a form in a modal.",
message:
'<form class="ChangeStatusDossier" id="ChangeStatusDossier" name="ChangeStatusDossier">' +
'<input name="UtenteCreatore" type="hidden" value="' + UtenteCreatore + '">' +
'<table>' +
'<tr>' +
'<th colspan="2">' +
'<h2 class="blue">Change Dossier Status</h2>' +
'</th>' +
'</tr>' +
'<tr>' +
'<td><strong>Choose status</strong> </td>' +
'<td><select name="Status" onchange="ShowHub(this.value);">' +
'<option value="0">' +
'Under process' +
'</option>' +
'<option value="1">' +
'Under collection' +
'</option>' +
'<option value="2">' +
'Cargo collected' +
'</option>' +
'<option value="159">' +
'In Warehouse' +
'</option>' +
'<option value="1485">' +
'To Destination' +
'</option>' +
'</select></td>' +
'</tr>' +
'<tr id="HubChoose" style="display:none;">' +
'<td>Choose hub</td>' +
'<td><select name="Hub">' +
'<option>' +
'HUB MILANO' +
'</option>' +
'</select></td>' +
'</tr>' +
'</table>' +
'</form>',
buttons: {
success: {
label: "Submit",
className: "btn-success",
callback: function () {
$('#ChangeStatusDossier').submit();
showResult("Form submitted!");
}
},
cancel: {
label: "Cancel",
className: "btn-danger",
callback: function() {
showResult("Canceled!");
}
}
} // buttons
}); // dialog
});
function showResult(result) {
if (typeof result !== "undefined" && result !== null) {
console.log(result);
}
}
Here's a working DEMO
I have added Address,city and locality using jQuery in a dynamic added div element where the binding event is not working as expected:
I have below jQuery code:
<script type="text/javascript">
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var elems = '<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
//('#addressDiv').append(elems);
$('#addressDiv').append(elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$('#city_name' + counter).html(html);
}
});
$(document).on('change', '#city_name' + counter, function (ev) {
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + counter).html(html);
}
});
});
//counter++;
return false;
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
</script>
My PHP Code for adding city in dropdown
city_load.php:
<?php
include("db.php");
$sql = "select * from city";
echo "<select name='city_name[]' id='city' class='city1'><option value='' selected ='selected'>Select City</option>";
$res = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($res)) {
echo "<option value='$row[city_id]'>$row[city_name]</option>";
}
echo "</select>";
?>
locality_load.php
<?php
include("db.php");
$city_id = $_POST['city_id'];
$sql = "select locality_id,locality_name,city_id from locality where city_id=$city_id";
$res = mysqli_query($con, $sql);
$result = mysqli_query($con, $sql) or die("query error");
while ($rows = mysqli_fetch_array($result)) {
$locality_id = $rows['locality_id'];
$locality_name = $rows['locality_name'];
echo "<option value=" . $locality_id . ">" . $locality_name . "</option>";
//echo '<option value="'.$locality_id.'">'.$locality_name.'</option>';
}
?>
The issue I am getting is that the first dynamic div is getting added and data is loading properly but for 2nd dynamic div it is not working.
Please have a look on screenshot:
save the counter value as a data-attr
eg
var elems = '<div class="col-lg-5 Address" data-id="' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group city" data-id="' + counter + '">' +
'<select name="city_name[]" data-id="' + counter + '" class="form-control city_name"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" data-id="' + counter + '" class="form-control locality_name"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" data-id="' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>';
use a class for each element , bind events on class .
like
$(document).on('change','.city_name', function (ev) {
counter_id = $(this).attr('data-id');
}
so you will get the counter value and hope it will work for every div you created. (code not tested )
$(document).ready(function () {
var counter = 0;
$(document).on('click', '#addButton', function (e) {
if (counter > 19) {
alert("Only 20 Address allowed");
return false;
}
e.preventDefault();
var $elems = $('<div class="col-lg-5" id="Address' + counter + '">' +
'<textarea class="form-control" name="alt_address[]" rows="3" placeholder="Address' + (counter + 1) + '"/><div class="col-lg-6 form-group col-lg-offset-6"> </div>' +
'<div class="col-lg-3 form-group" id="city' + counter + '">' +
'<select name="city_name[]" id="city_name' + counter + '" data-index="' + counter + '" class="form-control"><option value="" selected ="selected">Select City</option></select>' +
'</div><div class="col-lg-3 form-group"><select name="locality_name[]" id="locality_name' + counter + '" class="form-control"><option value="" selected="selected" >Select Locality</option></select></div></div>' +
'<div class="col-lg-1 form-group">' +
'<button type="button" class="removebtn" id="removeButton' + counter + '">' +
'<span class="glyphicon glyphicon-minus"></span></button>' +
'</div><div class="col-lg-6 form-group col-lg-offset-6"> </div>');
//('#addressDiv').append(elems);
$('#addressDiv').append($elems);
$.ajax({
type: "Post",
url: "city_load.php",
success: function (html) {
$elelms.find('select').html(html);
}
});
counter++;
return false;
});
$(document).on('change', 'select', function (ev) {
var cc = $(this).attr('data-index');
ev.preventDefault();
$city_id = $(this).val();
$.ajax({
type: "Post",
url: "ajax-dd3ck.php",
data: "city_id=" + $city_id,
cache: "false",
success: function (html) {
$('#locality_name' + cc).html(html);
}
});
});
$(document).on('click', '.removebtn', function () {
if (counter == 0)
{
alert("No more textbox to remove");
return false;
}
counter--;
$("#Address" + counter).remove();
$("#removeButton" + counter).remove();
});
});
There are maybe some problem!
When i debug my code i can see i have value but i don't get value to createCheckBoxPlatform FN
function createCheckBoxPlatform(data) {
var platform = "";
$.each(data, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>' + getOS();
});
$('#platform').append((platform));
}
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
I think you have to turn around your logic. The createCheckBoxPlatform loop will have completed before the getOS() ajax call returns, unless it's a synchronous call.
You could split the functions into pieces, gather the getOS data for each data point you have, then construct the checkboxes when your ajax call returns.
You can make your ajax call async and have to make no changes to your current logic. But your execution will stop till you don't get the callback to your ajax call.
function getOS() {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
async: true,
success: function (data) {
var os = '<div>';
$.each(data, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
return os;
}
});
}
the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value.
Maybe you could first, get the os list and then output what you need, like this:
function createCheckBoxPlatform(myDatas) {
$.ajax({
url: "/QRCNew/GetOS",
type: "post",
dataType: "Json",
success: function (osList) {
var os = '<div>';
$.each(osList, function (i, item) {
os += '<label><input type="checkbox" name="' + item.OperatingSystemName + ' value="' + item.OperatingSystemSK + '">' + item.OperatingSystemName + '</label> ';
});
os += '</div>';
$.each(myDdatas, function (i, item) {
platform += '<label><input type="checkbox" name="' + item.PlatformName + ' value="' + item.PlatformSK + '">' + item.PlatformName + '</label>'+os
});
$('#platform').append((platform));
}
});
}