Dependent select menu in Jquery Ajax - javascript

I want to create a form so that when the user selects the State, the office box will show the number of offices in that State, when the user selects the specific City will show the number of offices in that City and when the user selects the Hometown, the number of offices in that Home Town will only show in the select box. Please see the attached picture for a better understanding. I am completely new in this field so I can't do.
This is my HTML code
<div class="row">
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">State</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">City</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">Home Town</label>
<select name="" id="" class="form-control"></select>
</div>
<div class="col-md-3 mb-3">
<label for="" class="col-form-label">Office</label>
<select name="" id="" class="form-control"></select>
</div>
</div>
This is jquery code
$(document).ready(function () {
$('#division-dd').on('change', function () {
var idDivision = this.value;
$("#office-dd").html('');
$.ajax({
url: "{{url('get-division-offices')}}",
type: "POST",
data: {
division_id: idDivision,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (result) {
$('#office-dd').html('<option value="">Select City</option>');
$.each(result.division_offices, function (key, value) {
$("#office-dd").append('<option value="' + value
.id + '">' + value.office_name + '</option>');
});
$('#office-dd').html('<option value="">Select Hometown</option>');
}
});
});
$('#distric-dd').on('click', function () {
var idDivisionOffice = this.value;
$("#office-dd").html('');
$.ajax({
url: "{{url('get-distric-offices')}}",
type: "POST",
data: {
distric_id: idDivisionOffice,
_token: '{{csrf_token()}}'
},
dataType: 'json',
success: function (res) {
$('#office-dd').html('<option value="">Select Hometown</option>');
$.each(res.distric_offices, function (key, value) {
$("#office-dd").append('<option value="' + value
.id + '">' + value.office_name + '</option>');
});
}
});
});
});

Related

create a new function

I have a new Order page, in this page, user should select the category, then, select the service and then, fill quantity field for the order.
I want create a change, I want to define a function with #if and #else
In this function, let's say if the service is not selected, the quantity field is not displayed
But if it was selected, the quantity field would appear
But I do not know how to define this function.
this is my code:
#extends('user.layouts.master')
#section('site_title', 'New Order')
#section('page_title')
<i class="fa fa-first-order"></i>New Order
#endsection
#section('body')
<div class="row">
<div class="col-md-6 offset-md-3">
#include('user.layouts.flash')
<div class="card">
<div class="card-header d-flex align-items-center">
<h3 class="h4">Submit new order</h3>
</div>
<div class="card-body">
<form action="{{ route('newOrder.store') }}" method="post">
#csrf
<div class="form-group">
<label class="form-control-label"><b>category</b></label>
<select class="form-control" id="category" name="category" required>
<option>Select category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="form-control-label"><b>Service</b></label>
<select class="form-control input-lg" id="service" name="service" required>
</select>
</div>
#if ($item->service)
<div class="form-group">
<label for="details" class="control-label">Details</label>
<textarea name="details"
id="details"
rows="5"
style="height: 150px"
class="form-control" readonly></textarea>
<div class="form-group">
<label class="form-control-label"><b>quantity</b></label>
<input class="form-control" name="quantity" id="quantity" required>
</div>
<div class="row">
<div class="col-md-6">
<label style="color: #080B6A"><b>Min:</b><span id="min">0</span></b></label>
</div>
<div class="col-md-6">
<label style="color: #080B6A"><b>Max: </b><span id="max">0</span></b></label>
</div>
</div><br>
<div class="row">
<div class="col-md-6">
<label class="btn btn-success">Total price: <span
id="price">0</span> {{ $general->base_currency }}</label>
</div>
</div><br>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script type="text/javascript">
$(document).ready(function () {
// fetch Service
$(document).on('change', '#category', function () {
var serId = $('option:selected', this).val();
$.ajax({
type: 'POST',
url: '{{ route('get.pack') }}',
data: {id: serId},
success: function (data) {
$('#service').html('');
$('#service').append('<option>Select service</option>');
$.each(data, function (index, value) {
$('#service').append('<option value="' + value.id + '">' + value.name + '</option>');
});
var total = 0;
$('#details').text();
$('#min').text(0);
$('#max').text(0);
$('#price').text(total.toFixed(2))
},
})
});
//package price and quantity
var price = 0;
var quantity = 0;
$(document).on('change', '#service', function () {
var serviceId = $('option:selected', this).val();
if (!isNaN(serviceId)) {
$.ajax({
type: 'POST',
url: '{{ route('get.pack.details') }}',
data: {id: serviceId},
success: function (data) {
$('#details').text(data.details);
$('#min').text(data.min);
$('#max').text(data.max);
price = data.price_per_k;
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
},
});
} else {
$('#details').text(0);
$('#min').text(0);
$('#max').text(0);
price = 0;
quantity = 0;
var total = 0;
$('#price').text(total.toFixed(2))
}
});
$(document).on('keyup', '#quantity', function () {
quantity = $(this).val();
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
});
});
</script>
#endsection
you can do this using javascript
// first we hide what we want using style="display:none" and add a calss or attribute to the hidden elements ex: hidden-elements
<div class="form-group hidden-elements" style="display:none">
<label class="form-control-label"><b>quantity</b></label>
<input class="form-control" name="quantity" id="quantity" required>
</div>
// when we change the value of the service
$(document).on('change', '#service', function () {
var serviceId = $('option:selected', this).val();
if (!isNaN(serviceId)) {
// here we show the hidden elements after we choose the service
$('.hidden-elements').show();
$.ajax({
type: 'POST',
url: '{{ route('get.pack.details') }}',
data: {id: serviceId},
success: function (data) {
$('#details').text(data.details);
$('#min').text(data.min);
$('#max').text(data.max);
price = data.price_per_k;
var total = (price * quantity) / 1000;
$('#price').text(total.toFixed(2))
},
});
} else {
$('#details').text(0);
$('#min').text(0);
$('#max').text(0);
price = 0;
quantity = 0;
var total = 0;
$('#price').text(total.toFixed(2))
}
});

How to store onchange selected dropdown value into hidden input field?

This is my jquery ajax code where i have done dropdown populated things and storing onchange id into hidden input field.Why is it not storing into id field? I checked in alert if the value is coming or not. Value is coming but it's not storing into hidden field.
<script type="text/javascript">
$(document).ready(function() {
$("#village").change(function(){
$('#hiddenVillage').val( $(this).val());// this code to store id into this field
});
$('#taluka').change(function()
{
var myObject = {talukaid: $(this).val(),districtid: $('#district').val(), state_id:$('#stateDrop').val()};
var cpytaluka= $(this).val();
$('#hiddenTaluka').val($(this).val(cpytaluka));// this code to store id into this field
$.ajax({
type : "get",
url : "villages.htm",
data : myObject,
success : function(response) {
$('#village').append(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
$('#district').change(function()
{
var myObject = {districtid: $(this).val(), state_id:$('#stateDrop').val()};
var cpydistrict= $(this).val();
$("#hiddenDistrict").val($(this).val(cpydistrict));// this code to store id into this field
$.ajax({
type : "get",
url : "taluka.htm",
data : myObject,
success : function(response) {
$('#taluka').append(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
$('#stateDrop').change(function()
{
var state = $(this).val();
$("#hiddenstate").val(state);// this code to store id into this field
$.ajax({
type : "get",
url : "district.htm",
data : "State_ID=" + state,
success : function(response) {
$('#district').append(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
});
});
</script>
This is my form where i have included input field below every dropdown field
<form action="search-Leaders-list" id="searchleader" method="GET">
<div class="row">
<div class="form-group col-lg-3">
<select id="stateDrop"
title="State <i class="fa fa-angle-down"></i>">
<option value="small">State</option>
<c:forEach items="${stateList}" var="state">
<option value="${state.state_Id}">${state.state_Name}</option>
</c:forEach>
</select> <input type="hidden" id="hiddenstate">
</div>
<div class="form-group col-lg-3">
<select id="district">
<option value="small">District</option>
</select> <input type="hidden" id="hiddenDistrict">
</div>
<div class="form-group col-lg-2">
<select id="taluka">
<option value="small">Taluka</option>
</select> <input type="hidden" id="hiddenTaluka">
</div>
<div class="form-group col-lg-2">
<select id="village"
title="Villages <i class="fa fa-angle-down"></i>">
<option value="small">Villages</option>
</select> <input type="hidden" id="hiddenVillage">
</div>
<div class="form-group col-lg-2">
<input type="submit" value="Search" class="submit">
</div>
</div>
</form>
Kindly please help me.
i don't really get your question. if you want to get the id of this dropdown box and save it in the hidden field.
$('#taluka').change(function()
{
$('#hiddenTaluka').val(this.id);
or
using
$('#hiddenTaluka').val($(this).attr('id'));
if you want to store the value of dropbox selected item.
var cpydistrict= $(this).val();
$("#hiddenDistrict").val(cpydistrict);

How to populate a modal box SELECT form control before it is shown using the shown.sb.modal event

I have a simple modal popup that edits an item retrieved from the back end. The for has several input and select controls. The input form controls work properly but the select controls are not pre-populated as intended.
The basic architecture of my functions as follows:
function BootboxEditItem(id) {
$.ajax({
// Load back end data
})
.done(function(data) {
var itemData = data;
$.ajax({
// Load form template for modal
url: '/modal/item/edit-item.html',
......
})
.success: function (data) ({
var box = bootbox.confirm({
// Set up bootbox buttons;
},
callback: function(result){
// Post edited data back to the server
}
)};
box.on("shown.bs.modal", function(e) {
// Populate the modal here using data from the backend.
// This is where the problem lies!
})
box.modal("show");
});
}
Below is the full JavaScript code:
function BootboxEditItem(id) {
var itemDao = '';
$.ajax({
type: "GET",
contentType: "application/json",
url: "/api/item/edit/" + id,
dataType: "json",
cache: false
})
.done(function (data) {
itemDao = data;
$.ajax({
type: "GET",
url: '/modal/item/item-edit-form.html',
success: function (data) {
console.log(itemDao);
var box = bootbox.confirm({
message: data,
title: "Edit Item: [" + itemDao.item.sysId + "]",
buttons: {
cancel: {
label: "Cancel",
className: "btn-danger btn-fixed-width-100"
},
confirm: {
label: "Save",
className: "btn-success btn-fixed-width-100"
}
},
callback: function (result) {
}
});
box.on("shown.bs.modal", function(e) {
console.log(e.currentTarget);
var selectItemLevel = document.getElementById('editItemLevel');
console.log(selectItemLevel);
$(selectItemLevel).empty();
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt);
});
$(e.currentTarget).find('select[name="editItemLevel"]').val(selectItemLevel);
$(e.currentTarget).find('input[name="editIdentifier"]').val(itemDao.item.identifier);
$(e.currentTarget).find('textarea[name="editItemValue"]').val(itemDao.item.itemValue);
});
box.modal('show');
}
});
});
}
Here is the code for the HTML file:
<form id="editItem" action="/api/items/save" method="post">
<input type="hidden" name="artifactId" id="artifactId" value="" />
<input type="hidden" name="editId" id="editId" value="" />
<input type="hidden" name="editSysId" id="editSysId" value="" />
<input type="hidden" name="editSortIndex" id="editSortIndex" value="" />
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemLevel">Item level:</label>
<select class="form-control" id="editItemLevel" name="editItemLevel"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="editItemClass">Item class:</label>
<select class="form-control" id="editItemClass" name="editItemClass" onchange="itemEditClassChange();"></select>
</div>
</div>
</div>
<div class="row" id="editRequirementRow">
<div class="col-sm-6">
<div class="form-group">
<label for="editItemType">Requirement type:</label>
<select class="form-control" id="editItemType" name="editItemType"></select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="createIdentTemplate">Identifier prefix:</label>
<select class="form-control" id="editIdentTemplate" name="editIdentTemplate" onchange="itemEditIdentTemplateChange();"></select>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="createMediaType">Media type:</label>
<select class="form-control" id="editMediaType" name="editMediaType"></select>
</div>
</div>
<div class="col-sm-6" id="editIdentField">
<div class="form-group">
<label for="editIdentifier">Identifier:</label>
<input type="text" class="form-control" id="editIdentifier" name="editIdentifier" />
</div>
</div>
</div>
<div class="form-group">
<label for="editItemValue">Item details:</label>
<textarea class="form-control" rows="5" cols="50" id="editItemValue" name="editItemValue"></textarea>
</div>
And here is the output intended for one of the SELECT controls as printed by console.log();
<select class="form-control" id="editItemLevel" name="editItemLevel">
<option value="1">Level 1</option>
<option value="2">Level 2</option>
<option value="3">Level 3</option>
<option value="4">Level 4</option>
<option value="5">Level 5</option>
<option value="6">Level 6</option>
<option value="7">Level 7</option>
<option value="8">Level 8</option>
<option value="9">Level 9</option>
<option value="10">Level 10</option>
It seems your each loop is not properly appending the <option></option>.If you have chrome developer tools and you know how to use it, put a breakpoint in this function and make sure the select options are being created and added to the DOM:
$.each(itemDao.itemLevels, function (key, index) {
var opt = document.createElement('option');
opt.value = index;
opt.innerHTML = 'Level ' + index;
selectItemLevel.appendChild(opt); //breakpoint here
});
Also, since you are already using jQuery, you could add them to the DOM like this:
$.each(itemDao.itemLevels, function (key, index) {
$(selectItemLevel).append('<option value="'+index+'">Level '+index+'</option>');
});
Thanks to #nilerafetr24, but the problem was not about appending properly. Rather it was about how to get hold of the SELECT control before being shown.
Certainly, the following doesn't work document.getElementById('editItemLevel'), but the following works $(e.currentTarget).find('select[name="editItemLevel"])'.
So, my final solution is to rewrite the loop thus; after combining with the solution suggested by #nilerafetr24 which seems more efficient:
$.each(itemDao.itemLevels, function (key, index) {
$(e.currentTarget).find('select[name="editItemLevel"]).append('<option=value="'+index'">Level '+index+'</option');
});

ajax 'change' is not fired when value 'select value is set from php

I have a form with city, state and country.
the upon selecting a city - I automatically populate the state and country via ajax from the a mysql database.
However, when I try to select from the database to the form, the ajax change is not fired.
please What am i doing wrong? How do i read from db to select and still autpopulate dependent field?
Here is my code
< script type = "text/javascript" >
function profileLocationFunction() {
$('#profilecity').change(function() {
var id = $(this).val();
var dataString = id;
$.ajax({
type: "GET",
url: "locationautocomplete.php",
dataType: 'json',
data: {
datatext: dataString,
type: 'cityselect'
},
cache: false,
success: function(data) {
$('#profilestate').html(data.message1);
$('#profilecountry').html(data.message2);
},
error: function(xhr, status, error) {
alert("Hello! ERROR!" + error);
}
});
});
}
$(document).ready(function() {
profileLocationFunction();
}); < /script>
<?PHP require_once("include/DbConfig.php");
if($_GET['type']=='cityselect') {
$stateid="";
$statedata="";
$countryid="";
$countrydata="";
//fetch state from city
$id=$_GET['datatext'];
$city_query="SELECT DISTINCT CITY.STT_ID, STATE.STT_ID, STATE.STT_NAME FROM CITY, STATE WHERE CITY.CTY_ID='".$id."' AND CITY.STT_ID = STATE.STT_ID";
$result=mysqli_query($DB_con, $city_query);
while ($row=mysqli_fetch_assoc($result)) {
$stateid=$row['STT_ID'];
$statedata=$row['STT_NAME'];
}
//fetch country
$country_query="SELECT DISTINCT STATE.CTR_ID, COUNTRY.CTR_ID, COUNTRY.CTR_NAME FROM STATE, COUNTRY WHERE STATE.STT_ID='".$stateid."' AND STATE.CTR_ID = COUNTRY.CTR_ID";
$countryresult=mysqli_query($DB_con,
$country_query);
while ($row=mysqli_fetch_assoc($countryresult)) {
$countryid=$row['CTR_ID'];
$countrydata=$row['CTR_NAME'];
}
//send result
echo json_encode(array("message1"=>'<option value="'.$stateid.'">'.$statedata.'</option>',
"message2"=>'<option value="'.$countryid.'">'.$countrydata.'</option>'));
}
?>
<div class="form-group">
<label for="city" class="col-sm-3 control-label">City*</label>
<div class="col-sm-7">
<input type="hidden" name="profileselectedcityid" id="profileselectedcityid" value='' />
<select type="text" class="form-control" name="profilecity" id="profilecity" placeholder="City">
<option selected="selected">--Select City--</option>
<?php if(!$site->FetchAllCities()) { echo '
<script type="text/javascript">
alert("ERROR");
</script>'; } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="state" class="col-sm-3 control-label">State*</label>
<div class="col-sm-7">
<input type="hidden" name="profileselectedstateid" id="profileselectedstateid" value='' />
<select type="text" class="form-control" name="profilestate" id="profilestate" placeholder="City">
<option selected="selected">--Select State--</option>
</select>
</div>
</div>
<div class="form-group">
<label for="country" class="col-sm-3 control-label">Country*</label>
<div class="col-sm-7">
<input type="hidden" name="profileselectedcountryid" id="profileselectedcountryid" value='' />
<select type="text" class="form-control" name="profilecountry" id="profilecountry" placeholder="City">
<option selected="selected">--Select Country--</option>
</select>
</div>
</div>
Try to replace your javascript code to:
function profileLocationFunction() {
var id = $(this).val();
var dataString = id;
$.ajax({
type: "GET",
url: "locationautocomplete.php",
dataType: 'json',
data: {
datatext: dataString,
type: 'cityselect'
},
cache: false,
success: function(data) {
$('#profilestate').html(data.message1);
$('#profilecountry').html(data.message2);
},
error: function(xhr, status, error) {
alert("Hello! ERROR!" + error);
}
});
}
$(document).ready(function() {
$('#profilecity').change(profileLocationFunction).change();
});
I just remove the event from function, maybe it's better.

How to get the file value in Jquery and pass value in AJAX [duplicate]

This question already has answers here:
Uploading both data and files in one form using Ajax?
(13 answers)
Closed 6 years ago.
Here I want insert the values in Database here normal value like name, email, area... This value getting and after that value passed in next through AJAX and doing insertion part but while file uploading I can't get consloe.log(file); I am getting like this C:\fakepath\Penguins.jpg I don't know how to resolve this,i want get the file value and pass in next page thrugh AJAX and move to tmp folder how can do.
function add_menu() {
var name = $("#name").val();
var address = $("#address").val();
var area = $("#area").val();
var file = $("#file").val();
var gender = $("input[name=gender]:checked").val();
var checkValues = $('input[name=fecility]:checked').map(function() {
return $(this).val();
}).get();
if (name == '') {
$("#span-error").html(' Fill Menu Name. ');
} else if (gender == '') {
$("#span-error").html(' Select Gender. ');
} else if (area == '') {
$("#span-error").html(' Fill area. ');
} else if (checkValues == '') {
$("#span-error").html(' Select Fecilities. ');
} else {
$.ajax({
type: "POST",
url: "ajax_add_menu.php",
data: "name=" + name + "&area=" + area + "&address=" + address + "&gender=" + gender + "&checkbox=" + checkValues,
success: function(data) { // alert(data);
if (data == "success") {
window.location = 'pg_details.php';
}
}
});
}
}
<form class="form-horizontal" role="form" id="formid" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Name<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Name" name="name" id="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Area<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="text" class="form-control" placeholder="Area" name="area" id="area">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Address<span class="require">*</span>
</label>
<div class="col-sm-8">
<textarea class="form-control" placeholder="Enter Address" name="address" id="address" style="min-height:100px;"></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Room Standereds<span class="require">*</span>
</label>
<div class="col-sm-8" style="margin-top:10px">
<?php $sqlf="SELECT * FROM pg_fecilitys" ; $resultf=m ysql_query($sqlf); while($rowf=m ysql_fetch_array($resultf)) { echo '<input type="checkbox" id="fecility" name="fecility" value="'.$rowf[ "f_id"]. '" required style="margin: 0px 2px 0px 18px;">'.$rowf[
"f_name"]; } ?>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Gender<span class="require">*</span>
</label>
<div class="col-sm-8">
<label class="radio-inline">
<input type="radio" id="gender" name="gender" value="male">Male</label>
<label class="radio-inline">
<input type="radio" id="gender" name="gender" value="female">Female</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">PG Image<span class="require">*</span>
</label>
<div class="col-sm-8">
<input type="file" class="form-control" placeholder="PG Image" name="file" id="file">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="tcb">
<label>
<span id="span-error" style="color:#f00;"></span>
</label>
</div>
</div>
</div>
<div class="form-actions">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-primary" onclick="add_menu()">Submit</button>
<!-- <button type="submit" class="btn">Cancel</button> -->
</div>
</div>
</div>
</form>
If you want value of the file, use - var file = $("#file").val(); ,
But if you want file then use - var file = $("#file").get(0).files[0];
Also if you want to pass file with ajax, then use jquery FormData() like:
function add_menu() {
var name = $("#name").val();
var address = $("#address").val();
var area = $("#area").val();
var file = $("#file").val();
var gender = $("input[name=gender]:checked").val();
fd = new FormData();
fd.append('file', $("#file").get(0).files[0]);
fd.append('name ', name );
fd.append('address', address);
fd.append('area', area);
fd.append('gender', gender);
// remaining codes - checking and ajax
////
$.ajax({
type: "POST",
url: "ajax_add_menu.php",
data: fd,
success: function(data) { // alert(data);
if (data == "success") {
window.location = 'pg_details.php';
}
}
});
Try to using form data object instead of string
data: new FormData('#formid'),
Replace this with above line
data: "name=" + name + "&area=" + area + "&address=" + address + "&gender=" + gender + "&checkbox=" + checkValues,
You could not upload file via ajax like this you need metadata, instead of json object, you can code ajax like below:-
// have a look..
formdata= new FormData($('#formid')[0]);
// to console data you do it with just get method on form data like
console.log(formdata.get('file')); // for file
console.log(formdata.get('name')); // name will be displayed
$.ajax ( {
method : 'POST',
url : 'ajax_add_menu.php',
data : formdata,
cache : false,
processData: false,
contentType: false,
success : function ( data, textStatus, jqXHR ) {
// do what ever in your success in code
},
error : function ( jqXHR, textStatus, errorThrown ) {
// do what ever in failure
}
} );

Categories

Resources