Codeigniter 3 ajax calculating from another input using jquery - php

So the idea is to manipulate the value that is delivered by Ajax. This value should be divided by 20 and the result should be multiplied by the value from #nilai_hari input.
Here's my code
// trigger
<select class="form-control" id="id_anggota" name="id_anggota">
<option>-Pilih Karyawan</option>
<?php $no=1; foreach ($listAnggota as $l) {?>
<option value="<?php echo $l->id_anggota; ?>">
<?php echo $l->nama_lengkap; ?>
</option>
<?php $no++; }?>
</select>
// the effected
<select class="tunjangan_makan form-control total_tunjangan nominal" id="tunjangan_makan" name="tunjangan_makan"></select>
// another trigger
<input type="text" id="nilai_hari" name="nilai_hari" class="form-control">
And here's the script
$('#id_anggota').change(function() {
var id = $(this).val();
$.ajax({
url: "<?php echo base_url();?>hrd/penggajian/get_subpenggajian",
method: "POST",
data: {
id: id
},
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
if (data[i].flat_tunjangan == 1) {
html += '<option value="' + data[i].tunjangan_makan + '">' + number_format(data[i].tunjangan_makan, 0, '', '.') + '</option>';
} else {
$('#tunjangan_makan', '#nilai_hari').keyup(function() {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan / 20) * nilai_hari)
html += '<option value="' + makan + '">' + number_format(makan, 0, '', '.') + '</option>';
})
}
}
$('.tunjangan_makan').html(html);
}
});
});
So, the value of the data in which flat_tunjangan is 0 must be calculated from another input. Thanks in advance

You are doing it wrong. You should call other input onkey event and call same ajax request again and remove that onkey event inside $('#id_anggota').change().
$('#id_anggota').change(function(){
var id=$(this).val();
// perform ajax and get data
var data = [{'flat_tunjangan': '1', 'tunjangan_makan': '20'}, {'flat_tunjangan': '0', 'tunjangan_makan': '30'}];
var html = '';
var i;
for(i=0; i<data.length; i++){
if(data[i].flat_tunjangan == 1){
html += '<option value="'+data[i].tunjangan_makan+'">'+data[i].tunjangan_makan+'</option>';
} else {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan/20)*nilai_hari)
if (makan != '') {
html += '<option value="'+makan+'">'+makan+'</option>';
}
}
}
$('.tunjangan_makan').html(html);
});
$("#nilai_hari").keyup(function(){
var nilai_hari = $(this).val();
// again do ajax reqeust and fetch data using selected tunjangan_makan id
var id = $('#id_anggota').val();
var data = [{'flat_tunjangan': '1', 'tunjangan_makan': '20'}, {'flat_tunjangan': '0', 'tunjangan_makan': '30'}];
var html = '';
var i;
for(i=0; i<data.length; i++){
if(data[i].flat_tunjangan == 1){
html += '<option value="'+data[i].tunjangan_makan+'">'+data[i].tunjangan_makan+'</option>';
} else {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan/20)*nilai_hari)
if (makan != '') {
html += '<option value="'+makan+'">'+makan+'</option>';
}
}
}
$('.tunjangan_makan').html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="id_anggota" name="id_anggota">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
</select>
<select class="tunjangan_makan form-control total_tunjangan nominal" id="tunjangan_makan" name="tunjangan_makan"></select>
<input type="text" id="nilai_hari" name="nilai_hari" class="form-control">

Related

multiple dependent dropdown in add page and edit page in codeigniter

I need to add multiple dropdowns to my project and it also needs a dependent multiple dropdowns
The existing dropdown category should be changed to multiple dropdowns
Automatically they select values in its dependent subcategory multiple dropdowns it its possible ?
Current Single Choice Dependent Dropdown How To Make Multiple Choose Dependent Dropdown?
please help me
view page
<label for="category_id"><?php echo get_phrase('category'); ?> <span
class="text-danger">*</span></label>
<select class="form-control selectpicker" name="category_id" id="category_id" required multiple>
<option value="" hidden><?php echo get_phrase('select category'); ?></option>
<?php
$roles = $this->db->get('category_table')->result_array();
foreach($roles as $row):
?>
<option value="<?php echo $row['category_id'];?>">
<?php echo $row['category_name'];?>
</option>
<?php
endforeach;
?>
</select>
<label for="idsubcategory"><?php echo get_phrase('Sub_category'); ?>
<span class="text-danger"></span> </label>
<select class="form-control" name="idsubcategory" id="idsubcategory"
placeholder="subcategory" multiple>
<option value="" hidden><?php echo get_phrase('select subcategory'); ?></option>
<?php
$roles = $this->db->get('sub_category')->result_array();
foreach($roles as $row):
?>
<option value="<?php echo $row['idsubcategory'];?>">
<?php echo $row['subcategory_name'];?>
</option>
<?php
endforeach;
?>
</select>
ajax
$(document).ready(function()
{
$('#category_id').change(function() {
var category_id = $(this).val();
$.ajax({
url: "<?php echo site_url('admin/get_sub_category');?>",
method: "POST",
data: {
category_id: category_id
},
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<option value=' + data[i].idsubcategory + '>' + data[i]
.subcategory_name + '</option>';
}
$('#idsubcategory').html(html);
}
});
return false;
});
});
controller
function get_sub_category(){
$category_id = $this->input->post('category_id',TRUE);
$data = $this->Crud_model->get_sub_category($category_id)->result();
echo json_encode($data);
}
model
function get_sub_category($category_id){
$query = $this->db->get_where('sub_category', array('category_id' => $category_id));
return $query;
}
<select id="select1">
<option value='opt1'>Option 1</option>
<option value='opt2'>Option 2</option>
<option value='opt3'>Option 3</option>
</select>
<select id="select2">
<select>
<select id="select3">
<select>
<script>
$('#select1').change(function() {
var category_id = $(this).val();
$.ajax({
url: "<?php echo site_url('controller/function_for_second_dropdown');?>",
method: "POST",
data: {
category_id: category_id
},
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<option value=' + data[i].idsubcategory + '>' + data[i].your_option+ '</option>';
}
$('#select2').append(html);
}
});
$('#select2').change(function() {
var select2= $(this).val();
$.ajax({
url: "<?php echo site_url('controller/function_for_third_dropdown');?>",
method: "POST",
data: {
select2: select2
},
async: true,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
html += '<option value=' + data[i].your_option + '>' + data[i].your_option+ '</option>';
}
$('#select2').append(html);
}
});
</script>

Speed up the jQuery-ajax being used Custom filters and show results without delay

I'm using a filter based on jQuery ajax. Filter is working quite perfectly but the issue is because it's using the ajax call due to yearly based search so it's a bit slow , I mean when user selects year he/she have to wait for next option to enable and as options are based on year so they take some time to load in filter.
I need to sort this out quickly can you please help me out here ?
Below is the php and jQuery code for that please see and help me out . Thanks
Here is code for form which is working as filters:
<form id="search-product" method="GET" action="<? bloginfo('url') ?>/product/">
<div class="search-field">
<select id="select-yr" name="yr" required="">
<option value="">Year</option>
<?php foreach(get_data_yrs() as $yr) { ?>
<option<?= (isset($_GET['yr']) && $_GET['yr'] == $yr ? " selected" : "") ?>><?= $yr ?></option>
<?php } ?>
</select>
</div>
<div class="search-field">
<select id="select-make" name="make" required="" data-selected="<?= (isset($_GET['make']) ? $_GET['make'] : "") ?>">Select make</select>
</div>
<div class="search-field">
<select id="select-model" name="model" required data-selected="<?= (isset($_GET['model']) ? $_GET['model'] : "") ?>">Select model</select>
</div>
<div class="search-field">
<select id="select-qualifier" name="qualifier" data-selected="<?= (isset($_GET['qualifier']) ? $_GET['qualifier'] : "") ?>">Select qualifier</select>
</div>
<div class="search-sub">
<input type="submit" name="srh" value="Search">
<input type="reset" value="Reset">
</div>
</form>
And here is the jQuery :
$("#select-yr").on("change", onYearChange);
$("#select-make").on("change", onMakeChange);
$("#select-model").on("change", onModelChange);
$("#select-yr").each(function() {
if($(this).val() != "") {
$(this).trigger("change");
}
});
function onYearChange() {
var $selectors = $("#select-make, #select-model, #select-qualifier");
var $selector = $("#select-make");
var $yr = $("#select-yr").val();
var $selected = $selector.data("selected");
$selectors.empty();
$selector.append('<option>Please wait</option>');
// $selector.attr('disabled', 'disabled');
$.ajax({
url: ajax_url,
data: {
action: 'get_data_makes',
yr: $yr
},
dataType: 'JSON',
success: function(data) {
$selectors.empty();
$selector.append('<option value="">Select Make</option>');
if(data.length > 0) {
for(var i in data) {
$selector.append('<option'+(data[i] == $selected ? " selected" : "")+'>'+data[i]+'</option>');
}
}
if($selected) {
$selector.trigger('change');
}
$selector.removeAttr('disabled');
}
});
}
function onMakeChange() {
var $selectors = $("#select-model, #select-qualifier");
var $selector = $("#select-model");
var $make = $("#select-make").val();
var $yr = $("#select-yr").val();
var $selected = $selector.data("selected");
$selectors.empty();
$selector.append('<option>Please wait</option>');
$selector.attr('disabled', 'disabled');
$.ajax({
url: ajax_url,
data: {
action: 'get_data_models',
make: $make,
yr: $yr
},
dataType: 'JSON',
success: function(data) {
$selectors.empty();
$selector.append('<option value="">Select Model</option>');
if(data.length > 0) {
for(var i in data) {
$selector.append('<option'+(data[i] == $selected ? " selected" : "")+'>'+data[i]+'</option>');
}
}
if($selected) {
$selector.trigger('change');
}
$selector.removeAttr('disabled');
}
});
}
function onModelChange() {
var $selectors = $("#select-qualifier");
var $selector = $("#select-qualifier");
var $make = $("#select-make").val();
var $yr = $("#select-yr").val();
var $model = $("#select-model").val();
var $selected = $selector.data("selected");
$selectors.empty();
$selector.append('<option>Please wait</option>');
$selector.attr('disabled', 'disabled');
$.ajax({
url: ajax_url,
data: {
action: 'get_data_qualifiers',
make: $make,
yr: $yr,
model: $model
},
dataType: 'JSON',
success: function(data) {
$selectors.empty();
$selector.append('<option value="">Select Qualifier</option>');
if(data.length > 0) {
for(var i in data) {
$selector.append('<option'+(data[i] == $selected ? " selected" : "")+'>'+data[i]+'</option>');
}
}
if($selected) {
$selector.trigger('change');
}
$selector.removeAttr('disabled');
}
});
}

How to make comparison using JSON/jQuery and PHP data

I am currently using a JQuery code and a JSON file to load cities in a select> according to the chosen state/province. The JQuery is below.
$(document).ready(function() {
$.getJSON('../../../js/statesCities.json', function(data) {
var items = [];
var options = '<option value="">Selecione</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
});
$("#estados").html(options);
$("#estados").change(function() {
var options_cidades = '<option value="">Selecione</option>';
var str = "";
$("#estados option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.sigla == str) {
$.each(val.cidades, function(key_city, val_city) {
options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#cidades").html(options_cidades);
}).change();
});
});});
The JSON code I am using: https://gist.github.com/letanure/3012978
And the HTML selects:
<div>
<b>Estado:</b>
<select id="estados" class="form-control" name="estadoCliente" required>
<option value="">Selecione</option>
</select>
</div>
<div>
<b>Cidade:</b>
<select id="cidades" class="form-control" name="cidadeCliente" required>
<option value="">Selecione</option>
</select>
</div>
In fact, this code works just fine. But when I want to fill a form using PHP data, the code doesn't help. (The registration page is the same as editing. On the edition page, PHP loads user's information). If all the states and cities were pre-loaded in the HTML (Have all options typed), in order to check which state and city are in the database, I would use an inline PHP's if, considering the variable $state as the state of any user who filled in this form.
<option <?php echo $state=='AB'?'selected': ''?>>AB</option>
But It can't be used because the function $.each won't accept the variables from PHP. So, my question is how can I do this verification to each option, having the state and city saved in a database? I will use this code to load the data of a user, so I can edit information more easily.
PS: I don't know how I could better describe this question on the title.
Because you're loading the data on the frontend you will need to store the backend values somewhere, then once the data has loaded, use the JS to compare and select the correct option.
In your html you could do (supposing you're not using a templating engine):
<div>
<b>Estado:</b>
<select id="estados" class="form-control" name="estadoCliente" initial-val="<?php $estado; ?>" required>
<option value="">Selecione</option>
</select>
</div>
<div>
<b>Cidade:</b>
<select id="cidades" class="form-control" name="cidadeCliente" initial-val="<?php $cidade; ?>" required>
<option value="">Selecione</option>
</select>
</div>
Above you should see the use of initial-val="...", you can call this whatever you want. You will use these values when the data loads...
So, your JS would now use those, like so:
$(document).ready(function() {
$.getJSON('../../../js/statesCities.json', function(data) {
var items = [];
var options = '<option value="">Selecione</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
});
// always cache your jquery dom lookups in a var if queries more than once.
var $estados = $("#estados");
var $cidades = $("#cidades");
$estados.html(options);
$estados.change(function() {
var options_cidades = '<option value="">Selecione</option>';
var str = "";
$("option:selected", $estados).each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.sigla == str) {
$.each(val.cidades, function(key_city, val_city) {
options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$cidades.html(options_cidades);
$cidades.val($cidades.attr("initial-val"));
}).change();
// now set the value on the "estados" <select> and trigger the change event, so the above code runs to change "cidades"
$estados.val($estados.attr("initial-val")).trigger( "change" );
});
});});
That, I hope gets you a solution you can build upon.

Display correctly the selected value

I use an AJAX to display my categories. My problem is when I select a category, the dropdown come back always at this initial position
For example, if I click "Panneaux lumineux", the dropdown go back to "Select your categorie" automatically. in this case "Panneaux lumineux" is not selected.
Tk
<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input name="current_category_id" value="20" type="hidden" />
</div>
</div>
The issue you have occurs, because your dropdown list is replaced with a new one when you click on the dropdown. Even if the dropdown is visually the same, it isn't in the DOM.
To solve it, you need to save the selected category ID and select it after the dropdown has been replaced.
<div class="col-md-5">
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
var selectedCategory = $('select#category_id').val();
$.ajax({
url: 'http://Admin/products_categories_ajax.php',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '<option value="">-- Select your categorie --</option>';
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '"' + (category_id == selectedCategory ? ' selected' : '') + '>' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
<div id="myAjax">
<select name="move_to_category_id" id="category_id">
<option value="">-- Select your categorie --</option>
<option value="0">Haut</option>
<option value="25">Panneaux lumineux</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input name="current_category_id" value="20" type="hidden">
</div>
</div>
Above the
$.ajax function call
add
var selectedOptionVal = $('#category_id').val();
to save the value you selected.
then use that value to make the correct option selected when you recreate the html. So then try changing
for (index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
options_html += '<option value="' + category_id + '">' + category_name + '</option>';
}
to
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}

Populate the last selectbox based on the first

I tried to populate a select box based on the first but no result, no error but the second select box is not populate:
My html:
<div class="form-group">
<label>Firm:</label>
<select class="form-control marg-left-10" id="firm">
<?php if($all_firms): ?>
<?php foreach($all_firms as $firm): ?>
<option value="<?php echo $firm['id_firm']; ?>"><?php echo $firm['name_firm']; ?></option>
<?php endforeach; ?>
<?php endif; ?>
</select>
</div>
<div class="form-group">
<label>Administrator</label>
<select class="form-control marg-left-10" id="admin">
</select>
</div>
My php:
public function getAllFirms()
{
$this->load->database();
$all_firms = $this->db->query("SELECT *FROM firms");
if ($all_firms->num_rows())
{
$all_firms = $all_firms->result_array();
}
else
{
$all_firms = NULL;
}
return $all_firms;
}
public function getAdministrator($id)
{
$this->load->database();
$get_admin = $this->db->query("SELECT * FROM users,firms WHERE firms.id_firm = users.fk_firm and users.id = $id");
if ($get_admin->num_rows())
{
$get_admin = $get_admin->result_array();
}
else
{
$get_admin = NULL;
}
return $get_admin;
}
My script:
$("#firm").change(function() {
var selectedMark = $("#firm").val();
if (selectedMark != "") {
$.ajax({
type: "GET",
url: "<?php echo base_url() . 'user/getAdministrator'; ?>" + selectedMark,
success: function(data) {
$("#admin").html("");
$("#admin").append("<option value=''></option>");
$.each(data, function() {
$("#admin").append("<option value='" + this.id + "'>" + this.name + "</option>");
});
}
});
}
});
I use CodeIgniter as backend language, the first selectt box is populated but the second not.Please help me guys...HELP please!!!!! HELP ME GUYS!!Another idea to resolve this?
it looks like you've forgotten to add # when you calling 'admin' select. I.e. see 'success' section of your JS and change:
$('admin')...
to
$('#admin')...
you are looking like this:
<div class="form-group">
<label>Firm:</label>
<select class="form-control marg-left-10" id="firm">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="form-group">
<label>Administrator</label>
<select class="form-control marg-left-10" id="admin"></select>
</div>
<script>
$("#firm").change(function() {
var selectedMark = $("#firm option:selected").val();
var selectedMarkt = $("#firm option:selected").text();
if (selectedMark != "") {
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
$("#admin").append("<option value='" + selectedMark + "'>" + selectedMarkt + "</option>");
}
});
}
});
</script>
Looks like you need another "/" on this line:
url: "<?php echo base_url() . 'user/getAdministrator'; ?>" + selectedMark,
Right after 'user/getAdministrator'.

Categories