I am getting problem while populating select box options depend on previous select box
Problem is Whenever I select the value from first select box (i.e. #city) it gives me the result of city value which is fine but as soon as I select the second value it gives me the result of second values as well as first values.
below is my code
HTML CODE
<lable>City</lable>
<select id="city" style="width:100%;text-align:left;" onchange="getSchool()"></select>
<span id='paymentform_city_errorloc' class='error'></span>
<br>
<br>
<lable>School</lable>
<select id="school" style="width:100%;">
</select>
<span id='paymentform_school_errorloc' class='error'></span>
<br>
<br>
JS CODE
var cityname, city, schoolname, schooldata, cityid, city1;
var cityarray = [];
var schoolarray = [];
function getCity() {
jQuery.ajax({
url: baseurl + "getcity.php",
async: true
, success: function (data) {
data = $.trim(data);
if (data == "false") {
console.log(data);
} else {
var myArray = jQuery.parseJSON(data);
jQuery(myArray).each(function (index, element) {
cityname = element.cityname;
cityid = element.city_id;
cityarray.push([cityname, cityid])
});
for (var i = 0; i < cityarray.length; i++) {
city1 += '<option value="' + cityarray[i][1] + '">' + cityarray[i][0] + '</option>';
}
$('#city').html("<option disabled selected></option>" + city1);
}
}
});
}
function getSchool() {
var city_id = $('#city').val();
jQuery.ajax({
url: baseurl + "getschool.php"
, data: 'cityid=' + city_id
, type: "POST"
, success: function (response) {
response = $.trim(response);
if (response == "false") {
$('#school').prop('disabled', 'disabled');
} else {
$('#school').prop('disabled', false);
console.log(response);
$('#school').append(response);
}
}
, error: function () {}
});
}
function getSchool() {
var city_id = $('#city').val();
schoolarray = []; //Add this code.
Make the above change. And your school array will reset every-time a new city is selected.
Related
I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>
First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.
I have 3 dropdowns containing values that are populated on page load
<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
I have a function that updates the values in the 'other' dropdowns that aren't clicked, based on the value of the dropdown that is clicked - but I have this function repeated 3 times, for each dropdown
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: {model: selectedModel},
success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
And the PHP looks something like this:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake, mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn, $sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(), true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel, SQLSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake, $updateModel, $updateVersion));
...and this all works fine,
Basically, I'm looking for a simpler solution for reusing the function (both JS & PHP) instead of rewriting it 3 times!
In terms of what I have attempted,
$('#make, #model, #version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},
success:function(data)
{$(this).html(''); //this doesn't work obviously!
After this I'm snookered
This one should work for JS side, you will have to check mapping function for response
$('#make, #model, #version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: data,
success:function(data)
{
let options = ['make', 'model', 'version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),
model: JSON.parse(data[1].map(make => make.mModel)),
version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
}
});
});
function setDropdown(id, data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}
i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');
I need to solve one issue regarding csv. I have read all the values from csv (I have three fields like region,state,acc_name) and loaded into corresponding dropdown list.but my issue is if i select the region i need to get the corresponding state values from csv I have done something but not even get any single line code please help me to do that task.
My code is:
$(document).ready(function() {
// AJAX in the data file
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function(data) {
processData(data);
}
});
// Let's process the data from the data file
function processData(data) {
var table = $("<table />");
var rows = data.split(/\r\n|\n/);
for (var i = 1; i < rows.length - 1; i++) {
var row = $("<tr />");
var cells = rows[i].split(/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/);
for (var j = 0; j < rows.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
var usedNames = {};
$("select[name='company1'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company2'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
$("select[name='company3'] > option").each(function() {
if (usedNames[this.text]) {
$(this).remove();
} else {
usedNames[this.text] = this.value;
}
});
var newvalue = cells[1].replace("\"", "");
//var newvalue=cells[1].trim();
var final1 = newvalue.replace("\"", "");
var pandu = cells[0];
$("#region").append("<option value =" + cells[0] + "> " + cells[0] + " </option>");
$("#state").append("<option value =" + final1 + "> " + final1 + "</option>");
$("#accname").append("<option value =" + cells[2] + ">" + cells[2] + "</option>");
table.append(row);
}
}
});
function getstate()
{
...
}
HTML:
Region:
<select id="region" class="select" name="company1" onchange="getstate()"></select>
<br> State:
<select id="accname" class="select" name="company3"></select>
<br> Acct_Name:
<select id="state" class="select" name="company2"></select>
<br>
I want to add input whit js and send value whit jQuery but value dosnt send.
Actually fields value dosn't define in jQuery.
function addElement(myDiv, type) {
var ni = document.getElementById(myDiv);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my' + num + 'Div';
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<input class="name" name="name[]" value="" placeholder="عنوان"><input class="value" name="value[]" value="" placeholder="توضیحات"><input type="hidden" class="type" name="type[]" value="' + type + '"><input type="hidden" class="position" name="position[]" value="' + myDiv + '">'
ni.appendChild(newdiv);
}
$('#add_field').live('click', function() {
var id = $('#id').val();
var name = $('#name').val();
var value = $('#value').val();
var type = $('#type').val();
var position = $('#position').val();
var name = [];
var value = [];
var type = [];
var position = [];
$(".name").each(function() {
name.push($(this).val());
});
$(".value").each(function() {
type.push($(this).val());
});
$(".position").each(function() {
size.push($(this).val());
});
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: {
name: name,
type: value,
size: type,
position: position
},
success: function(data) {
$('#result').html(data);
}
});
});
PHP
print_r($_POST['name']);
print_r($_POST['value']);
print_r($_POST['type']);
print_r($_POST['position']);
echo $_GET['id'];
Notice: Undefined index: name
Notice: Undefined index: value
Notice: Undefined index: type
Notice: Undefined index: position
Use this ajax. Note that the $('form') selector needs to be a valid selector that targets your <form> tag. If you serialize, the arrays will be passed as arrays in HTTP, not as a javascript array value. With this mode, PHP will recognize them as arrays, not as [OBJECT object] value
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: $('form').serialize(); // that's the change
success: function(data) {
$('#result').html(data);
}
});
EDIT
Test with serializeArray():
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: $('form').serializeArray(); // that's the change
success: function(data) {
$('#result').html(data);
}
});
More info: https://api.jquery.com/serializeArray/
EDIT 2
As I said in comments, you can make it with serialize():
http://jsfiddle.net/tZPg4/15519/
It works perfectly.