Is This jQuery Bug On First Option Selected? - javascript

I have weird situation with Select2 plugins :
When, #state is changed, it will do ajax request to get list of #city. once #city is selected, it will do ajax request to get #area list.
if I select #city option number 2, 3, etc... it will trigger #area to get the list. but if I choose option number 1, none will happen.
but once, I choose option number 2, 3, etc... then go back to choose option number 1, then it will run ajax perfectly.
pic 1 : Badung (option #1) is selected for the first time, not trigerring AJAX to get #area
pic 2 : Bangli (option #2) is selected, it's trigerring AJAX to get #area
pic 3 : Back to Badung (option #1), now it's trigerring AJAX to get #area
here's my HTML structure :
<div class="row">
<div class="col-sm-12">
<div class="form-group form-group-default form-group-default-select2 required">
<label class="">State</label>
<select id="state" class="full-width" data-init-plugin="select2" name="state">
<option select="selected"></option>
<?
for ($i = 0; $i < $num_propinsi; $i++) {
$value = $propinsi[$i]['province_id'];
$text = $propinsi[$i]['province'];
echo '<option value="'.$value.'">'.$text.'</option>';
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<label>City</label>
<select id="city" class="full-width" data-init-plugin="select2" name="city" disabled>
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-group-default form-group-default-select2 required">
<label>Area</label>
<select id="area" class="full-width" data-init-plugin="select2" name="area" disabled>
</select>
</div>
</div>
</div>
and here's my jquery :
<script>
$(function() {
$("#form-flogin").validate();
$("#state").change(function() {
$("#city").html("");
$("#s2id_city").find("#select2-chosen-2").html("");
$("#s2id_area").find("#select2-chosen-3").html("");
$("#area").prop("disabled", true);
$("#flogin-submit").prop("disabled", true);
var propinsi = $("#state").val();
$.ajax({
url: "controller/ctrl.getcityarea.php?req=city&val="+propinsi,
dataType: "JSON",
success: function(json){
var city = "";
$.each(json, function(i,o){
city += "<option value="+o.id+">"+o.city_name+"</option>";
});
$("#city").append(city);
event.preventDefault();
$("#city").prop("disabled", false);
}
})
});
$("#city").change(function() {
$("#area").html("");
$("#s2id_area").find("#select2-chosen-3").html("");
var city = $("#city").val();
$.ajax({
url: "controller/ctrl.getcityarea.php?req=area&val="+city,
dataType: "JSON",
success: function(json){
var area = "";
$.each(json.rajaongkir.results, function(i,o){
area += "<option value="+o.subdistrict_id+">"+o.subdistrict_name+"</option>";
});
$("#area").append(area);
event.preventDefault();
$("#area").prop("disabled", false);
}
});
});
$("#area").change(function() {
event.preventDefault();
$("#flogin-submit").prop("disabled", false);
});
})
</script>
any idea why .change method is not working on first attempt? but works on next attempt. thank you for your help

This is because you have written a change event listener for city dropdown and first city is default selected hence when you select it again it won't change the value therefore change event listener won't get fire.
You can do one of following two options
Option 1 : put extra option as "Select City" and then select first city of your choice.
$("#city").append("<option value=''>Select City</option>");
$("#city").append(city);
Opetion 2 : trigger change event through code
$("#city").append(city).change();

Related

dynamic drop down while allowing multiple option select for the child drop down

I need to load data dynamically into two child drop downs according to the selected value in a parent drop down. At the same time child drop down boxes should allow multiple option select. for example, if i select value 1 then data should be loaded to one child drop down. if i select value 2 then other child drop down should be loaded. if I select value 3 then both child drop downs should load data. I have succeeded that. but the problem is when I use selectpicker with multiple attribute in select tag, above mentioned mechanism is working, but do not show data in child drop downs. I can't figure out what is the problem in there.
My html code is below
<div class="form-group row">
<label class="col-sm-4" for="sel4">Designation:</label>
<select name="designation" id="designation" class="form-control col-sm-5">
<option value="">Select</option>
#foreach($type as $items)
<option value="{{$items->id}}">{{$items->type}}</option>
#endforeach
</select>
</div>
<div class="form-group row">
<label class="col-sm-4">Registrar Division:</label>
<label class="col-sm-4">Birth and Death Division:</label>
<select name="birth_death_div[]" multiple id="birth_death_div" class="form-control col-sm-4 selectpicker">
<option value="">Select a Birth and Death Division</option>
</select>
<label class="col-sm-4"></label>
<label class="col-sm-4 mt-2">Marriage Division:</label>
<select name="marriage_div[]" multiple id="marriage_div" class="form-control col-sm-4 mt-2 selectpicker">
<option value="">Select a Marriage Division</option>
</select>
</div>
first drop down is the parent.
following is the javascript code
$('#designation').change(function(){
var desig_type = $(this).val();
var ds= $('#ds').val();
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('addregistrar.fetchdiv') }}",
method:"POST",
data:{desig_type:desig_type, ds:ds, _token:_token},
success:function(data){
data = JSON.parse(data);
if(data.division_type=="1"){
$('#marriage_div').html(data.output);
$('#birth_death_div').html('');
}
if(data.division_type=="2"){
$('#birth_death_div').html(data.output);
$('#marriage_div').html('');
}
if(data.division_type=="3"){
$('#marriage_div').html(data.output_m);
$('#birth_death_div').html(data.output_bd);
}
}
})
});
controller code
$data_m = DB::table('registrar_division') //get marriage divisions
->where('divisional_secretariat_id', $ds)
->where('div_type',$marriage_div)
->get();
$output_m = '<option value="">Select a Division</option>';
foreach($data_m as $row_m)
{
$output_m .= '<option value="'.$row_m->$id.'">'.$row_m->$name.'</option>';
}
output, output_bd are also same as output_m
Data is passing correctly to child drop downs. but not showing any data.
My controller code is much long and it is working fine. Problem occurred when added selectpicker class to select tag.
Any help would be grateful.

Unable to fill the other fields on the basis of option selected

I want to fill the other fields on the form from database on the basis of option selected, but unable to do using php and javascript.I have attached json data I received in question. I want to fill other form fields when i select option from the form field houseowner_select and i want to show div app_houseowner when i select option from the select box having id applicant_is.
$("#applicant_id").on("change", function() {
var selected = $(this).val();
makeAjaxRequest1(selected);
});
function makeAjaxRequest1(opts) {
$.ajax({
type: "POST",
data: {
opts: opts
},
url: "get_houseownerinfo_applicant.php",
success: function(res) {
console.log(res);
debugger;
$("#applicant_wardno").val(res.ho_wardno);
$("#applicant_citizenship_no").val(res.ho_citizenship_number);
$("#applicant_phone").val(res.ho_phone);
}
});
}
<select name="applicant_is" class="form-control" ng-model="applicant.applicant_is" ng-change="callback_change_applicant_is($event)">
<option value="">--select--</option>
<option value="app_houseowner">घरधनी</option>
<option value="landowner">जग्गाधनी</option>
<option value="waris">वारिश</option>
</select>
<div class="app_houseowner">
<select class="form-control" name="houseowner_select" id="applicant_id">
<option value="">--Select--</option>
<option value="<?php if (isset($row11['id'])){ echo $row11['id'];}?>">
<?php if (isset($row11['ho_name_en'])){ echo $row11['ho_name_en'];}?>
</option>
</select>
</div>
<input type="text" name="applicant_phone" class="form-control" id="applicant_phone">
<select name="applicant_wardno" class="form-control" id="applicant_wardno">
<option value="">--Select--</option>
<?php for ($x = 1; $x <= 19; $x++) {
echo "<option value=".$x.">".$x."</option>";
}?>
</select>
<input type="text" name="applicant_citizenship_no" class="form-control" id="applicant_citizenship_no">
First of all remove or comment $("#applicant_salutation").val(res.ho_salutation) and $("#applicant_district").val(res.ho_citizenship_district) line in from your javascript code bcoz both id is not available in your html.
Also add dataType: 'json' in you ajax request
As i have checked applicant_wardno is select box and you have to set selected for displaying value in the select box instead of setting val.
check this link for setting selected value
You can debbug with an alert: alert(res.ho_wardno); and see if the value is being returned from the ajax query;
$("#applicant_wardno").val(res.ho_wardno);
alert(res.ho_wardno);
$("#applicant_citizenship_no").val(res.ho_citizenship_number);
$("#applicant_phone").val(res.ho_phone);

jquery about attributes ( load from loaded html )

I have a 2 select options. When I select the first one it posts to a link using javascript then return full options to the second one with data from a database.
I have an attributes in the second select called data-price. When I'm trying to use it, it shows nothing:
var x = $("#services").find(':selected').attr('data-price');
However when I'm trying with the first select attribute it works correctly. Anyone know how to fix ? Thanks
<script type="text/javascript">
$(document).ready(function(){
var category = document.getElementById("category").value;
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
$('#category').on('change',function(){
var category = $(this).val();
if(category){
$.ajax({
type:'POST',
url:'<?=base_url();?>dashboard/ajaxData',
data:'main_category='+category,
success:function(html){
$('#services').html(html);
}
});
}else{
$('#services').html('<option value="">Select category first</option>');
}
});
});
var x = $("#services").find(':selected').attr('data-price');
document.getElementById("demo").innerHTML = x;
</script>
<div class="form-group">
<label>Category</label>
<select name="category" id="category" class="form-control">
<?php foreach($categories->result() as $cat): ?>
<option data-price="55" value="<?=$cat->id;?>">- <?=$cat->title;?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Service</label>
<select name="service" id="services" class="form-control">
<option data-price=""></option>
</select>
</div>
<div id="demo"></div>
To find the selected one you do:
$("#services option:selected")
then you can get whatever you want from that option.
For a data attribute it can be:
$("#services option:selected").data('price');
or alternatively
$("#services option:selected").attr('data-price');
This answer is based on the assumption that your select as an id attribute of services, if it is not all the above code will fail
Based on the updated code you posted you probably are looking to update the selected value when the user changes the selection.
I'd do it binding the change event like this:
$("#services option:selected").change(function(){
var price = $(this).attr('data-price');
$('#demo').html(price);
});

Append chosen plugin placeholder text on change event

I am using the jquery chosen plugin for my select elements. This is working well apart from the fact that whatever i try I cannot amend the placeholder text after a change event. I would appreciate it if someone could check my code point out my error. Many thanks
html
<div class="form-group">
<label for="rtvcompany" class="labelStyle">Company</label>
<select class="form-control chosen-select" name="rtvcompany" id="rtvcompany" data-placeholder="Select a Company...">
<option value=""></option>
<?php
while ($row = mysqli_fetch_assoc($resultcmp)) {
$name = $row["idcode_usr"];
echo "<option value=\"$name\">$name</option>";
}
?>
</select>
<div id="compmessage"></div>
<div class="servicesHelp">
<lead id="serviceHelp" class="form-text text-muted">Please select a company to proceed.</lead></div>
</div>
<div class="form-group">
<label for="rtvdept" class="labelStyle">Department</label>
<select class="form-control chosen-select" name="rtvdept" id="rtvdept" data-placeholder="Select a Dept...">
<option value=""></option>
</select>
<div id="deptmessage"></div>
<div class="servicesHelp">
<lead id="serviceHelp" class="form-text text-muted">Please select a department where your box is stored for retrieval.</lead></div>
</div>
js
$(function() {
$(document).on('change', '#rtvcompany', function() {
$(this).after('<div id="loader"><img src="/domain/admin/images/loader.gif" alt="loading files" /></div>');
$.get('/domain/admin/requests/boxes/retrieve/loadboxRtvaddr.php?rtvcompany=' + $(this).val(), function(data) {
//console.log(data);
$("#rtvdept").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
$('#rtvdept').attr('data-placeholder', 'Please select your department....');
// $("#rtvdept").data("chosen").default_text = "New Default Text"
$("#rtvdept").trigger("chosen:updated");
});
});
});
});
You are creating options without value, change this :
echo "<option>$name</option>";
to this :
echo "<option value=\"$name\">$name</option>";

PHP get selected value of select form

I'm using Laravel and currently creating a form, where users can first choose a category, and then choose a relating subcategory.
A category has an id and a name, a subcategory has an id and a name, as well as a parent_id (so that's the id of the parent category).
Now I try the following:
The user can pick a category, after he did that, the second select appears and the user can choose the subcategory from the subcategories that belong to the parent category (and only those!).
Therefore, the view gets all categories and all subcategories from the controller.
Then, for the categories I did this:
<div class="form-group{{ $errors->has('category') ? ' has-error' : '' }}">
<label for="category" class="col-md-4 control-label">Kategorie</label>
<div class="col-md-6">
<select>
#foreach($categories as $category)
<option value="<?php echo $category['id'];?>">{{$category->name}}</option>
#endforeach
</select>
</div>
</div>
And for the subcategories I have the same, just with subcategories:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select>
#foreach($subCategories as $subCategory)
<option value="<?php echo $subCategory['id'];?>">{{$subCategory->name}}</option>
#endforeach
</select>
</div>
</div>
Now the question is: What I need to do is (in the subcategory foreach) a #if and check for the value of the chosen option of the category select and then check if($subcategory->parent_id == $chosenOptionID), to say it in pseudo code. How can I do this? I don't want to send the form or something, before somebody didn't choose the subcategory as well.... Of course, I maybe could send an ajax request to the controller whenever a category is chosen, then check the value of the option in the controller and send back the id. But this would cause very much traffic and would propably not be the best solution, so I'd like to do this only, if I don't get a better way to do....
PS: The question is not about hiding the subcategories when no category is chosen, thats basic js, I know how to do that. I only want to know, if it is possible to read the value of the category select while form is not sent yet.
EDIT: I now tried the AJAX thing but there seems to be a little error...
What I changed:
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id);
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
But it doesn't work.. The ajax request is defintely sent on selecting an option, as well the correct id is sent. But somehow nothing is outputted... Any ideas why?
I finally got it working with AJAX. This is my initial subCategorySelect.
<div class="form-group{{ $errors->has('subCategory') ? ' has-error' : '' }}">
<label for="subCategory" class="col-md-4 control-label">Unterkategorie</label>
<div class="col-md-6">
<select class="form-control" id="subCategorySelect">
</select>
</div>
</div>
The select is now empty and has an ID. Then in the same file I have the following JS:
<script>
$().ready(function(){
$('#categorySelect').change(function(){
var selectedOption = $('#categorySelect').find(":selected").val();
$.ajax({
url: '/getSubCategories',
data: {'id': selectedOption},
type: 'GET',
success: function (data) {
$('#subCategorySelect').html(data);
}
});
});
});
</script>
/getSubcategoriesroute points to the following function in my controller:
public function returnSubCategories(Request $request){
$subCategories = Subcategory::where('parent_id', '=', $request->id)->get();
foreach($subCategories as $subCategory){
echo "<option value='$subCategory->id'>$subCategory->name</option>";
}
}
And it works perfectly.
hope this will help you understand how it works with php anyway for one selected option:
<div class="form-group">
<label class="control-label" for="country">Country:<span>*</span></label>
<select name="country" type="text" class="form-control" id="country">
<option value="">--Country--</option>
<?php
include "../db/db.php"; //db-connection cause i want to load a country list
$sql = "SELECT id, country_name FROM apps_countries ORDER BY country_name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //check if an entry is there
while($row = $result->fetch_assoc()) { //get the values from the db
//now this is the part you have to implement in your script
if(isset($_POST["country"]) && $row["id"] == $_POST["country"]) { //check if country isset so if the user selected something
$optionSelected = "selected='selected'";
} else{
$optionSelected = "";
}
//your foreache loop goes here / add the value that is selected here
/*#foreach($categories as $category)
<option value="<?php echo $category['id']; ?>">{{$category->name}}</option> // get the associative array with "" and change it to $category["id"]
#endforeach*/
/**for my attempt it was this
{the id like as your category[id]} {set the selected here inside the option tag}
↓ ↓ */
$countrySet = "<option value='" .$row["id"]. "' ".$optionSelected.">".$row["country_name"]."</option>";
echo $countrySet;
}
}
$conn->close();
?>
</select>
</div>

Categories

Resources