Laravel Date Range Search using Ajax jQuery datatables using Yajra - javascript

I'm trying to make Date Range Search after I completed making CRUD system in Laravel from this tutorial:
https://www.webslesson.info/2018/02/delete-or-remove-mysql-data-in-laravel-using-ajax.html
After this I looked at this tutorial:
https://www.webslesson.info/2019/02/laravel-date-range-search-using-ajax-jquery.html
The problem is that I can't implement this in the first tutorial.
1st my opinion is to integrate it in this function in the AjaxdataController
function getdata()
{
$students = Student::select('id', 'first_name', 'last_name');
return Datatables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-edit"></i> Edit<i class="glyphicon glyphicon-remove"></i> Delete';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
But i have this:
function fetch_data(Request $request)
{
if($request->ajax())
{
if($request->from_date != '' && $request->to_date != '')
{
$data = DB::table('students')
->whereBetween('created_at', array($request->from_date, $request->to_date))
->get();
}
else
{
$data = DB::table('students')->orderBy('created_at', 'desc')->get();
}
echo json_encode($data);
}
}
In the view file i have script:
<script>
$(document).ready(function(){
var date = new Date();
$('.input-daterange').datepicker({
todayBtn: 'linked',
format: 'yyyy-mm-dd',
autoclose: true
});
var _token = $('input[name="_token"]').val();
fetch_data();
function fetch_data(from_date = '', to_date = '')
{
$.ajax({
url:"{{ route('daterange.fetch_data') }}",
method:"POST",
data:{from_date:from_date, to_date:to_date, _token:_token},
dataType:"json",
success:function(data)
{
var output = '';
$('#total_records').text(data.length);
for(var count = 0; count < data.length; count++)
{
output += '<tr>';
output += '<td>' + data[count].first_name + '</td>';
output += '<td>' + data[count].last_name + '</td>';
output += '<td>' + data[count].created_at + '</td></tr>';
}
$('tbody').html(output);
}
})
}
$('#filter').click(function(){
var from_date = $('#from_date').val();
var to_date = $('#to_date').val();
if(from_date != '' && to_date != '')
{
fetch_data(from_date, to_date);
}
else
{
alert('Both Date is required');
}
});
$('#refresh').click(function(){
$('#from_date').val('');
$('#to_date').val('');
fetch_data();
});
});
</script>
Can anyone suggest something?
2nd try:
I edit the get data function AjaxdataController
function getdata(Request $request)
{
if($request->start_date != '' && $request->end_date != '')
{
$students = Student::whereBetween('created_at', array($request->start_date, $request->end_date));
} else {
$students = Student::select('id', 'first_name', 'last_name', 'created_at');
};
return Datatables::of($students)
->addColumn('action', function($student){
return '<i class="glyphicon glyphicon-edit"></i> Edit<i class="glyphicon glyphicon-remove"></i> Delete';
})
->addColumn('checkbox', '<input type="checkbox" name="student_checkbox[]" class="student_checkbox" value="{{$id}}" />')
->rawColumns(['checkbox','action'])
->make(true);
}
and ajaxdata.blade.php:
var date = new Date();
$('.input-daterange').datepicker({
todayBtn: 'linked',
format: 'yyyy-mm-dd',
autoclose: true
});
var _token = $('input[name="_token"]').val();
getdata();
function getdata(start_date='', end_date='')
{
$('#student_table').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url:"{{ route('ajaxdata.getdata') }}",
type:"POST",
data:{
start_date:start_date, end_date:end_date, _token:_token
}
},
"columns":[
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "created_at" },
{ "data": "action", orderable:false, searchable: false},
{ "data":"checkbox", orderable:false, searchable:false}
]
});
}
$('#search').click(function(){
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if(start_date != '' && end_date != '')
{
$('#student_table').DataTable().destroy();
getdata(start_date, end_date);
}
else
{
alert('Both Date is required');
}
});
With error
POST http://laravel.localhost/ajaxdata/getdata 405 (Method Not Allowed)

Related

How to move (append) all rows into another table with js

I want to select all my data rows and automatically goes into another table,
but i didnt find a way to do it.
my current condition using Jquery to move it 1 by 1 using code below
$("#tblcandidate").on("change", ".chkCheckBoxId", function () {
if ($(".chkCheckBoxId").is(":checked")) {
$(".fail").hide();
var trItem = $(this).closest("tr");
trItem.find(".chkCheckBoxIdFail").closest("td").remove();
trItem.add("<tr>").append("</tr>");
$("#tblcandidateprocess").append(trItem);
}
});
and my target is making function that can append all my row into another table using button
EDIT:
My datatables come from ajax belox
function loadData(monthyear) {
return $.ajax({
url: "#Url.Action("ListCandidate", "Recruitment")?monthyear=" + monthyear,
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
beforeSend: function () {
swal.fire({
title: "Please wait a moment",
text: "Loading data...",
showConfirmButton: false,
allowOutsideClick: false,
willOpen: () => {
Swal.showLoading()
},
});
},
success: function (data) {
var getTemp = "#TempData["Allert"]";
if (getTemp === "Data successfully selected") {
Swal.fire({
text: getTemp,
icon: "success",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else if (getTemp === "Something Went Wrong") {
Swal.fire({
text: getTemp,
icon: "error",
buttonsStyling: false,
confirmButtonText: "Ok, got it!",
customClass: {
confirmButton: "btn btn-primary"
}
});
}
else {
swal.close();
}
var html = '';
// delete existing row if any
table.clear().draw();
$.each(data, function (key, item) {
var TglLahir = item.TglLahir;
var cvTglLahir = moment(TglLahir).format('YYYY-MM-DD') ;
if (item.NamaS2 != null || item.NamaS2 != "") {
var namas2 = item.NamaS2;
}
else {
var namas2 = "A";
}
if (item.NamaS1 != null || item.NamaS1 != "") {
var namas1 = item.NamaS1;
}
else {
var namas1 = "A";
}
if (item.NamaD3 != null || item.NamaD3 != "") {
var namad3 = item.NamaD3;
}
else {
var namad3 = "A";
}
html += '<tr class="text-capitalize">';
html += '<td><span class="d-none">' + "'" + '</span> <div class="d-flex flex-column justify-content-start fw-bold">' + item.NomorKTP+'</div></td>';
html += '<td class="text-gray-800 text-hover-primary mb-1">' + item.NamaLengkap.toLowerCase() + '</td>';
html += '<td class="text-gray-800 text-hover-primary mb-1">' + item.PosisiYangDilamar.toLowerCase() + '</td>';
and etc
Then I want to move the shown row from this table A to my Table B
Here is an updated version of my Vanilla-JavaScript implementation that transfers individual <tr>s between the <tbody>s of the two tables:
document.querySelectorAll("button").forEach(b=>b.onclick=ev=>{
let tr=b.closest("tr");
document.querySelector((tr.closest("table").id=="source"?"#target":"#source")+" tbody").append(tr);
});
<div id="content">
<table id="source">
<thead>
<tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>
</thead>
<tbody>
<tr><td>1 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>2 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>3 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
<tr><td>4 one</td><td>two</td><td>three</td><td>four</td><td><button>transfer</button></td></tr>
</tbody>
</table>
<hr>
<table id="target">
<thead>
<tr><th>A</th><th>B</th><th>C</th><th>D</th></tr>
</thead>
<tbody></tbody></table>
</div>

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

How to addClass if autocomplete input is empty?

I would like to know how to add a class if autocomplete input is empty? There's a function which autocompletes the address when putting the post code. If for example address_1 is empty, it adds the class form-control, else it adds the class sem-bordas.
I tried:
$('#input-address-1').on('change', function() {
if ($(this).val() == '') {
$(this).next().removeClass("form-control");
} else {
$(this).next().addClass("sem-bordas");
}
});
But without success.
Thats all the function
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
$(document).on('input','#input-address-1', function() {
if ($(this).val() == '') {
$(this).next().addClass("sem-bordas");
} else {
$(this).next().removeClass("sem-bordas");
}
});
Let me explain, thats all my function to verify if the address exist or not
$(function(){
$('input[name="postcode"]').blur(function(){
var cep = $.trim($('input[name="postcode"]').val().replace('-', ''));
//$.getScript ("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+cep, function(){
$.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados){
if(!("erro" in dados)){
$('input[name="address_1"]').val(dados.logradouro);
$('input[name="address_1"]').parent().parent().fadeIn('slow');
$('input[name="address_2"]').val(dados.bairro);
$('input[name="address_2"]').parent().parent().fadeIn('slow');
$('input[name="city"]').val(unescape(dados.localidade));
$('input[name="city"]').parent().parent().fadeIn('slow');
$('select[name="zone_id"]').parent().parent().fadeIn('slow');
$('select[name="country_id"]').find('option[value="30"]').attr('selected', true);
$.post('index.php?route=account/register/estado_autocompletar&estado=' + unescape(dados.uf), function(zone_id){
$.ajax({
url: 'index.php?route=account/register/country&country_id=30',
dataType: 'json',
beforeSend: function() {
$('select[name=\'country_id\']').after(' <i class="fa fa-circle-o-notch fa-spin"></i>');
},
complete: function() {
$('.fa-spin').remove();
},
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
var html = '<option value=""><?php echo $text_select; ?></option>';
if (json['zone'] != '') {
for (i = 0; i < json['zone'].length; i++) {
html += '<option value="' + json['zone'][i]['zone_id'] + '"';
if (json['zone'][i]['zone_id'] == zone_id) {
html += ' selected="selected"';
}
html += '>' + json['zone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'zone_id\']').html(html);
}
});
});
}
});
});
});
Soon after putting the postcode and an address was not found, I would like to add a class to the fields that were not filled. The goal is to highlight fields that have not been filled
I found the solution
After
success: function(json) {
if (json['postcode_required'] == '1') {
$('#postcode-required').parent().parent().addClass('required');
} else {
$('#postcode-required').parent().parent().removeClass('required');
}
Put this code
if($.trim($('#input-address-1').val()) == ''){
$('#input-address-1').addClass('form-control');
}else {
$('#input-address-1').removeClass('form-control');
$('#input-address-1').addClass('sem-bordas');
}
Thanks everyone for helping. I think thats the solution

Codeigniter Smiley Not Showing Up In Preview Area

I have created a area where user can type in some text and also add smiley into the text area. smiley helper
How ever when I click on my preview button it does not show the generated smiley.
Question how to make sure on the preview are if has any smiles on
question will show up in preview properly. I use preg_replace_callback on my preview function on controller. and also .replace on script Update I found this on user guide but not sure where to add it on code
Generate the smiles here.
<?php
class Question extends CI_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->helper('smiley');
}
public function create() {
$this->load->library('table');
$image_array = get_clickable_smileys(base_url('assets/img/smiley'), 'question');
$col_array = $this->table->make_columns($image_array, 8);
$data['smileys'] = $this->table->generate($col_array);
$this->form_validation->set_rules('title', 'title', 'trim|required');
$this->form_validation->set_rules('question', 'question', 'trim|required|callback_question');
if ($this->form_validation->run() == true) {
}
$data['page'] = 'question/create';
$this->load->view($this->config->item('config_template') . '/template/template_view', $data);
}
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = $new_data;
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}
}
Script On View
<script type="text/javascript">
$('#preview-question').on('click', function (e) {
$.ajax({
url: "<?php echo base_url('question/preview');?>",
type: 'POST',
data: {
question: $('#question').val(),
'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>'
},
dataType: 'json',
success: function(response){
if (response.success) {
$('#preview').html(response.question);
if ($("#preview").find("pre").length > 0){
var html = $('#preview pre').html().replace(/</g, "<").replace(/>/g, ">");
$('#preview pre').html(html);
$('pre').each(function(i, block) {
hljs.highlightBlock(block);
});
}
} else {
}
}
});
e.preventDefault();
});
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$(document).ready(function(){
$('#bold').click(function() {
wrapText('question', "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("question", "<i>", "</i>");
});
$('#underline').click(function() {
wrapText("question", "<u>", "</u>");
});
$('#pre').click(function() {
wrapText("question", "<pre>", "</pre>");
});
});
</script>
Got it working
I had to use $data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
public function preview() {
$data = array('success' => false, 'question' => '', 'tag' => '');
if ($_POST) {
$string = $this->input->post('question');
$match = array(
'<' => '<',
'>' => '>',
);
$new_data = preg_replace_callback("#</?(pre|code|h1|h2|h3|h4|h5|h6|b|strong|i|u|hr)>|[<>]#", function ($match) {
return $match[0] == '<' ? '<' : ($match[0] == '>' ? '>' : $match[0]);
}, $string);
$data['question'] = parse_smileys($new_data, base_url('assets/img/smiley'));
$data['success'] = true;
}
$this->output
->set_content_type('application/json')
->set_output(json_encode($data));
}

Ajax function onload

I use this code:
var selected = {
country_id: <?php echo (int)$country_id;?>,
state_id: <?php echo (int)$state_id;?>,
city_id: <?php echo (int)$city_id;?>
},
countryMap = '<?php echo $countryMap;?>',
stateMap = '<?php echo $stateMap;?>',
cityMap = '<?php echo $cityMap;?>';
$("select.event-shipping-country").off().on("change", function() {
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
});
$("select.event-shipping-state").off().on("change", function() {
var $self = $(this);
cityMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'city', 'action' => 'get-cities' ], 'shipping_c_a') ?>',
data: { state: $self.val(), country: $("select.event-shipping-country").val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-city").find("option:gt(0)").remove();
selected.state_id = $self.val();
if(!result.length)
{
return;
}
var html = '';
for(var idx in result)
html += '<option ' + (selected.city_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-city").append(html);
stateMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
},
type: 'POST'
});
stateMap = $self.val() ? $self.text() : '';
});
$("select.event-shipping-city").off().on("change", function() {
selected.city_id = $(this).val();
cityMap = $(this).val() ? $(this).find('option[value="' + $(this).val() + '"]').text() : '';
});
This function select states based on selected country. Problem is that I have only one country with ID 117. But even if I have only one default option selected I must select it again to and only than will show states, but I need that states loads on page loading by selecting country id 117.
Thank you.
$("select.event-shipping-country").off().on("change", function() {
Above line will be called only on change of country.
Call the same function on document.ready() or document.onload also for first time loading and on change will remain same for change on country.
The way to do this is keep the whole code inside separate function and call that function on document.ready() or document.onload and on change of country also
function onCountryChange() {
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
}
$("select.event-shipping-country").off().on("change", onCountryChange );
document.ready(function() {
onCountryChange();
});
Try Like This, Just pass ur code inside a function and call those function at document.ready()
var selected = {
country_id: <?php echo (int)$country_id;?>,
state_id: <?php echo (int)$state_id;?>,
city_id: <?php echo (int)$city_id;?>
},
countryMap = '<?php echo $countryMap;?>',
stateMap = '<?php echo $stateMap;?>',
cityMap = '<?php echo $cityMap;?>';
function onCountryChange(){
var $self = $(this);
if(!$self.val()) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
}
countryMap = cityMap = stateMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'state', 'action' => 'get-states' ], 'shipping_c_a') ?>',
data: { id: $self.val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-state, select.event-shipping-city").find("option:gt(0)").remove();
selected.country_id = $self.val();
if(!result.length)
{
$("select.event-shipping-state").change();
return;
}
countryMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
var html = '';
for(var idx in result)
html += '<option ' + (selected.state_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-state").append(html);
},
type: 'POST'
});
}
$("select.event-shipping-country").off().on("change", function() {
onCountryChange();
});
function onStateChange(){
var $self = $(this);
cityMap = '';
$.ajax({
url: '<?php echo $this->url([ 'controller' => 'city', 'action' => 'get-cities' ], 'shipping_c_a') ?>',
data: { state: $self.val(), country: $("select.event-shipping-country").val() },
dataType: 'json',
success: function (result) {
$("select.event-shipping-city").find("option:gt(0)").remove();
selected.state_id = $self.val();
if(!result.length)
{
return;
}
var html = '';
for(var idx in result)
html += '<option ' + (selected.city_id == result[idx].id ? 'selected="selected"' : '') + ' value="' + result[idx].id + '">' + result[idx].name + '</option>';
$("select.event-shipping-city").append(html);
stateMap = $self.val() ? $self.find('option[value="' + $self.val() + '"]').text() : '';
},
type: 'POST'
});
stateMap = $self.val() ? $self.text() : '';
}
$("select.event-shipping-state").off().on("change", function() {
onStateChange();
});
function onCityChange(){
selected.city_id = $(this).val();
cityMap = $(this).val() ? $(this).find('option[value="' + $(this).val() + '"]').text() : '';
}
$("select.event-shipping-city").off().on("change", function() {
onCityChange();
});
$(document).ready(function () {
onCountryChange();
onStateChange();
onCityChange();
});

Categories

Resources