php codeigniter - get back the default value using ajax - javascript

I am working on a module where two drop downs will be available for the user to select, the values of second drop down will be auto-populated based on the first drop down and for fetching the values from db I am using AJAX.
Initially on page load there will be a text box in readonly mode in the place of second drop down (inside the span tag with id="model_inner_list"), this is the case when first drop down value is 0.
When first dropdown's value changes to other than 0 the span tag id="model_inner_list" text box will be replaced by second drop down (populated with values from db)
Now the problem is when I change back the first drop down value to 0 the second drop down in span tag with id="model_inner_list"is not getting replaced with default text box. i.e. when ever the value of first drop down is 0 the second drop down should be replaced by default text box. Below are the code level details of what I am trying
Look of drop downs
HTML version on drop downs (included in View file)
<div class="form-group input-group barnch_emp">
<span class="input-group-addon mylable">Make</span>
<select name="bv_vech_name_id" id="bv_vech_name_id" required="" class="form-control user-success" onchange="javascript:get_model_list(this.value)">
<option value="0">Select Vehicle Make</option>
<option value="1">HERO</option>
<option value="2">TVS</option>
<option value="3">SUZUKI</option>
<option value="4">BAJAJ</option>
<option value="5">HONDA</option>
<option value="6">YAMAHA</option>
<option value="7">MAHINDRA</option>
<option value="8">ROYAL ENFIELD</option>
</select>
</div>
<div class="form-group input-group barnch_emp">
<span class="input-group-addon mylable">Model</span>
<span id="model_inner_list">
<input type="text" class="form-control" value="Please Select Make" readonly="">
</span>
</div>
I am using the below javascript function to call the php function using AJAX
function get_model_list(vm_vechile_id) {
document.getElementById('model_inner_list').innerHTML = '<img src="<?php echo base_url();?>assest/img/loader_small.gif"/>';
var url = '<?php echo base_url();?>index.php/order/get_model_list_ajax?vm_vechile_id=' + vm_vechile_id;
$.post(url, function(result) {
document.getElementById('model_inner_list').innerHTML = result;
});
}
Controller function called by AJAX
function get_model_list_ajax($vm_vechile_id = "", $ba_city = "") {
if ($vm_vechile_id == '0') {
echo '<input type="text" class="form-control" value="Please Select Make" readonly>';
} else {
$this->load->model('Order_model');
if (!isset($_REQUEST['vm_vechile_id']))
$_REQUEST['vm_vechile_id'] = $vm_vechile_id;
if (!isset($_REQUEST['ba_city']))
$_REQUEST['ba_city'] = "";
$result = $this->Order_model->get_option_list_state('vechile_model', 'vm_vechile_id', $_REQUEST['vm_vechile_id']);
$cat1[''] = 'Select Model';
if ($result) {
foreach ($result as $item) {
$cat1[$item->vm_id] = $item->vm_model_name;
}
}
if ($vm_vechile_id)
return form_dropdown('bv_vech_model_id', $cat1, $ba_city, 'id="bv_vech_model_id" class="form-control"');
else
echo form_dropdown('bv_vech_model_id', $cat1, $_REQUEST['ba_city'], 'id="bv_vech_model_id" class="form-control"');
}
}`
Model function called by above Controller
public function get_option_list_state($table_name = "", $field_name = "", $id = "") {
$res = array();
if ($id)
$this->db->where($field_name, $id);
$q = $this->db->get($table_name);
if ($q->num_rows() > 0) {
foreach (($q->result()) as $row) {
$data[] = $row;
}
return $data;
}
}

You can change the get_model_list function like this:
function get_model_list(vm_vechile_id) {
if ( vm_vechile_id > 0 ) {
//ajax request goes here
}
else {
document.getElementById('model_inner_list').innerHTML = '<input type="text" class="form-control" value="Please Select Make" readonly="">';
}
}

Related

How to populate multiple textbox based on dropdown selection?

I have to populate my 2 textboxes based on the dropdown value from a single table.
Here is my table structure:
When I select the product name from the dropdown I want the 2 textboxes values to populate 1.sale_price 2.tax_amt. I have already populated the dropdown value from DB, please help me with the textboxes value.
DROPDOWN:
<select name="select_services[]" class="form-control select_services">
<option value="">--SelectProduct--</option>
<?php
$sql= "SELECT * from products where delete_status='0' ORDER BY id DESC";
$result=$conn->query($sql);
foreach ($result as $r_service) { ?>
<option value="<?php echo $r_service['id'];?>"><?php echo $r_service['name'];?></option>
<?php } ?>
</select>
Textboxes that I need to populate
<div class="col-sm-2">
<input type="text" class="form-control" id="unit_price" name="unit_price[]" placeholder="Sale Price" required>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" id="tax" name="tax[]" placeholder="Tax" required>
</div>
JAVASCRIPT
<script type="text/javascript">
$('div.mydiv').on("change",'select[name^="select_services"]',function(event){
var currentRow=$(this).closest('.subdiv');
var drop_services= $(this).val();
$.ajax({
type : "POST",
url : 'ajax_service.php',
data : {drop_services:drop_services },
success: function(data){
currentRow.find('input[name^="quantity"]').val(0);
currentRow.find('input[name^="unit_price"]').val(data);
var quantity =currentRow.find('input[name^="quantity"]').val();
var unitprice=currentRow.find('input[name^="unit_price"]').val();
var total = parseInt(quantity) * parseInt(unitprice);
currentRow.find('input[name^="total"]').val(total);
//var total=+currentRow.find('input[name^="total"]').val(total);
// $('#subtotal').val(total);
var sum = 0;
$('.total').each(function() {
if($(this).val()!='')
{
sum += parseInt($(this).val());
}
});
var sub = $('#subtotal').val(sum);
var fsub = $('#final_total').val(sum);
var tot_commi = 0;
}
});
});
</script>
PHP: ajax_service.php
<?php
include('connect.php');
if(isset($_POST['drop_services']))
{
$sql_service1 ="SELECT * FROM products WHERE id = '".$_POST['drop_services']."'";
$result1=$conn->query($sql_service1);
$service1 = mysqli_fetch_array($result1);
echo $service1['sale_price']; exit;
}
?>

Retain selected value of the dropdown after page refreshes

I need to retain selected value of the dropdown after page refreshes on click.
What is happening:
After I select an item from the dropdown the page reloads by itself and the value of the dropdown go to starting position though the value displays on the end of the url.
This is my code:
<script>
function refreshPage(passValue){
window.location="index.php?cat_page=admin_post&sw_cat=sw_catn="+passValue;
}
</script>
<div class="form-group col-md-4">
<label for="inputState">Your health proplem</label>
<select name="illness_id_cat" class="form-control" onchange="refreshPage(this.value);" >
<?php
while(mysqli_stmt_fetch($stmt)){
echo "<option value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
</select>
</div>
This option doesn't work too:
<script>
var selectedItem = sessionStorage.getItem("SelectedItem");
$('#dropdown').val(selectedItem);
$('#dropdown').change(function() {
var dropVal = $(this).val();
sessionStorage.setItem("SelectedItem", dropVal);
});
</script>
<div class="form-group col-md-4">
<label for="inputState">Your health proplem</label>
<select name="illness_id_cat" class="form-control" id="dropdown" >
<?php
while(mysqli_stmt_fetch($stmt)){
echo "<option value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
</select>
</div>
This I don't know how to implement, what is a "itemname":
<script>
var text = localStorage.getItem("itemname");
if(text !== null) {
$("select option").filter(function() {
return this.text == text;
}).attr('selected', true);
}
</script>
A more conventional way to do this would be using PHP, and getting the querystring value you're passing in via the window.location command:
<script>
function refreshPage(passValue){
window.location="index.php?cat_page=admin_post&sw_cat="+passValue;
}
</script>
<div class="form-group col-md-4">
<label for="inputState">Your health problem</label>
<select name="illness_id_cat" class="form-control" onchange="refreshPage(this.value);" >
<?php
while(mysqli_stmt_fetch($stmt)){
echo "<option";
//get the category value from the querystring and check it against the current category value in the loop. If it matches, pre-set the option as selected
if (isset($_GET["sw_cat"])) {
if ($_GET["sw_cat"] == $illness_id_cat) echo " selected";
}
echo " value='{$illness_id_cat}'>{$illness_name_cat}</option>";
}
?>
</select>
</div>

Option Menu with 2 Values

I have the following option menu in a form that will insert the fields into a table:
<option value="">select staff</option>
<?php
do {
?>
<option value="<?php echo $row_Staff['Staff_Name']."||".$row_Staff['Email']?>">
<?php echo $row_Staff['Staff_Name']?></option>
<?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
I have 2 fields from source table in value of option from technique explained in How to post two values in an option field?: Staff_Name and Email.
I am trying to insert both fields from the form into a table using:
<input type="hidden" name="Staff_Name" class="form-control" id="Staff_Name" value=<?php
$staff =$_POST['Staff_Data'];
$staff_name = explode("||", $staff);
echo $staff_Name[0];
?> />
and
<input type="hidden" name="Email" class="form-control" id="Email" value=<?php
$staff =$_POST['Staff_Data'];
$email = explode("||", $staff);
echo $email[1];
?> />
Unfortunately, I can see the 2 fields separated by "||" in the table if I insert the option menu value but cannot seem to insert Staff_Name or Email into individual fields. On insert both fields are blank. Any help would be appreciated.
Instead of combine staffname and staffemail in the dropdown value. Please staffname in dropdown value and staffemail in the property of dropdown and onchange of the dropdown set those values in the hidden inputs so you will easily get those values on the form submission.
Please go through below code and let me know if you have any query.
//Dropdown
<select id="ddStaff">
<option value="">select staff</option>
<?php
do { ?>
<option value="<?php echo $row_Staff['Staff_Name']; ?>" staff-email = "<?php echo $row_Staff['Email'];?>">
<?php echo $row_Staff['Staff_Name']?>
</option> <?php
} while ($row_Staff = mysql_fetch_assoc($Staff));
$rows = mysql_num_rows($Staff);
if($rows > 0) {
mysql_data_seek($Categories, 0);
$row_Staff = mysql_fetch_assoc($Staff);
}
?>
</select>
//Input hidden fields to store staff name and staff email
<input type="hidden" id="txtStaffName" name="txtStaffName">
<input type="hidden" id="txtStaffEmail" name="txtStaffEmail">
//Jquery code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#ddStaff").on('change',function(){
var staffName = $(this).val();
var staffEmail = $('option:selected', this).attr('staff-email');
$("#txtStaffName").val(staffName);
$("#txtStaffEmail").val(staffEmail);
});
});
</script>
Please check it on https://jsfiddle.net/z4a0fywp/
For testing purpose I have not made the inputs hidden in the fiddle.

How can we set options in select tag using jquery

I have two drop-down in my ui page. The second drop-down is generated when I select the first one.Here is my html code
<td width="100"><label for="type">Menu Category Name:</label></td>
<td width="200">
<select name="type" id="type" class="target dropdown required" onchange = getSubCategory(); tabindex="3" >
<?php echo $typeOption;?>
</select>
</td>
<tr height="50">
<td width="100"><label for="sub_type">Menu Sub Category Name:</label></td>
<td width="200">
<select name="sub_type" id="sub_type" class="sub dropdown required" tabindex="3" >
</select>
</td>
<tr height="50">
And my getSubCategory() function is
function getSubCategory(){
alert($("#type").val());
var catId = $("#type").val();
ajax(url,{id:catId,action:"getAllSubcategory"},function (response){
$("div.sub").val(response);
});
}
and this is my backend php code.Here I am setting every option
function getAllSubcategory(){
global $db;
$data = $_REQUEST;
$getProductSubType = "SELECT id, name FROM cp_reference_master WHERE active = 'Y'
AND mode='item_type_subcat'AND parent_id = '".$data['id']."' ORDER BY name ASC";
$resultType = $db->func_query($getProductSubType);
$subTypeOption = '<option value="">Select Category</option>';
$subTypeList = array();
if(is_array($resultType) && count($resultType)>0){
foreach($resultType as $key => $details){
$subTypeOption .= '<option value="'.$details['id'].'">'.$details['name'].'</option>';
$subTypeList[$details['id']] = $details['name'];
}
}
return $subTypeOption;
}
I need to set the response to my subcategory select tag. I am unable to set the same. What is wrong in my code. I have tried 2 or 3 solutions already.
you need to use append() or html() instead of val()
also you do not have a div.sub element in the code you've shown us, so I assume you want to add the response to the second select tag:
function getSubCategory(){
var catId = $("#type").val();
ajax(url,{id:catId,action:"getAllSubcategory"},function (response){
$("#sub_type").append(response);
});
});

How to get all the selected options in a drop down list with JavaScript?

I have a drop down list, and user can select multi options.
So this is part of my code in firtfile.inc
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select name="SearchIn[]" multiple="multiple" onchange="javascript:this.form.Heading.value=this.options[this.selectedIndex].text;" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php
//Loop over the options
for($i=0;$i<sizeof($SearchCriteria);$i++){
?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php
}//!End of looping over search criteria
?>
</select>
<!-- Hidden heading field for search report -->
<input type="hidden" name="Heading" valtue="" />
</div>
in another php file, I have included firstfile.inc, and i want to get the list of options that user has selected from drop down list.
so I have the folloing in the php file to get the selected options.
$Heading = $dat->if_default('Heading', '');
but it only gives me the first option that the user has selected, but I need all of them. How can I get them?
First of all, I highly recommend that you use jQuery, it will make any DOM manipulation a lot easier.
It's not clear what output you expect, but supposing you're expecting a comma separated string like:
Criteria1, Criteria2, Criteria3
You could:
1) Just use PHP to give you that, with something like:
$SearchIn = $_POST["SearchIn"];
$selectedArr = array();
foreach($SearchCriteria as $item) {
if (in_array($item["value"], $SearchIn)) {
$selectedArr[] = $item["display"];
}
}
$criteria = implode(", ", $selectedArr); // will contain: Criteria1, Criteria2, Criteria3
2) If you want to do it on the client and store the values in <input id="heading"/>, you can use jQuery and do this (your HTML would change a little, to include the IDs):
<form action="index.php" method="POST">
<div class="col-md-8">
<!-- Change report heading so we can grab it on the report page -->
<select id="section" name="SearchIn[]" multiple="multiple" required="required" title="Section">
<option value="" disabled selected>Select</option>
<?php for($i = 0; $i < sizeof($SearchCriteria); $i++) { ?>
<option value="<?php echo $SearchCriteria[$i]['value'];?>"<?php if($SearchCriteria[$i]['value']=='FacultyName'){echo ' selected="selected"';}?>>
<?php echo $SearchCriteria[$i]['display'];?>
</option>
<?php } ?>
</select>
<!-- Hidden heading field for search report -->
<input id="heading" type="hidden" name="Heading" value="" />
</div>
<input type="submit">
</form>
<script>
$('#section').on("change", function() {
selectedArray = new Array();
$(this).find("option:selected:not([disabled])").each(function() {
selectedArray.push(this.text);
});
$("#heading").val(selectedArray.join(", "));
});
</script>
3) For a pure JavaScript solution (use the same HTML as above):
<script>
document.getElementById("section").onchange=function(){
selectedArray = new Array();
for (x = 0; x < this.length; x++) {
if (this[x].selected && !this[x].disabled) {
selectedArray.push(this[x].text);
}
}
document.getElementById("heading").value = selectedArray.join(", ");
};
</script>

Categories