how to enter dynamic data to a javascript function after page load - javascript

I have a select box which options are coming from database depending on another selected option using ajax
$(document).ready(function(){
$("select.entity").change(function(){
var selectedEntity = $(".entity option:selected").val();
$.ajax({
type: "POST",
url: "entityName.php",
data: { entity : selectedEntity }
}).done(function(data){
$("#entityName").html(data);
});
});
});
// This is the select box where options are dynamic.
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
</select>
This works fine but now i want a search box for the options. I am using this function for search.
var select_box_element = document.querySelector('.select_box');
dselect(select_box_element, {
search: true
});
As options are dynamic and loaded after the page load that's why this function doesnot work.
I need to push dynamic options into dselect function based on the selection.

Something like this might work for you. I've used CSS and JS for the dselect library, as shown in the official GitHub repo. In the example, Bootstrap 5 files are also included, since dSelect seems to be relying on Bootstrap 5 files.
The API used is from the free Pokemon API.
Some notes on the slight rewriting on how the AJAX is handled:
no need to call the AJAX, if there's nothing inside the first select element, and if we revert to the default #entityType value. We just need to clear the previous contents of the #entityName. That is what the if does right inside the change event handler
the AJAX call contains a predefined dataType attribute. This was done because I know in advance that the response in my example (response of Pokemon API) will be in JSON format. You can also do that in your specific case, if you control the back-end / the way entityName.php works and outputs its results. If you don't have that kind of control, you may want to omit this AJAX config parameter, and handle the results differently
instead of using $.ajax({...}).done(...), the example uses separate success and error handlers. This was just a preference choice. For differences between the use of success and done, please refer to this SO answer. In your specific case, .done(...) would have worked as well, with additional testing if the received data matches what you expect it to match, like this:
$.ajax({
// your ajax setup
}).done(function(data){
if(data) {
$("#entityName").html(data);
} else {
$("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
}
dselect($("#entityName")[0], { search: true });
});
the example also uses config, as shown in the official GitHub repo. Again, if you're happy with the way you're initializing your dselect, you can skip the configuration
$(document).ready(function(){
const config = {
search: false, // Toggle search feature. Default: false
creatable: false, // Creatable selection. Default: false
clearable: false, // Clearable selection. Default: false
maxHeight: '360px', // Max height for showing scrollbar. Default: 360px
size: '', // Can be "sm" or "lg". Default ''
}
dselect($("#entityName")[0], config);
$("#entityType").change(function(){
let entityType = $(this).val();
if(!entityType) {
$("#entityName").html('<option value="" disabled selected>Select Entity Type First</option>');
dselect($("#entityName")[0], config);
return false;
}
$.ajax({
type: "GET",
url: "https://pokeapi.co/api/v2/type/" + entityType,
dataType: "json",
success: function(data) {
let pokemon = data.pokemon;
let pokeList = '<option value="" selected>Please choose your Pokemon</option>';
console.log(pokemon[0].pokemon.name);
for(var i = 0; i < pokemon.length; i++) {
let pokeName = pokemon[i].pokemon.name;
let pokeUrl = pokemon[i].pokemon.url;
pokeList += '<option value="' + pokeUrl + '">' + pokeName + '</option>';
}
$("#entityName").html(pokeList);
dselect($("#entityName")[0], config);
},
error: function(desc, err) {
alert("Error: " + JSON.stringify(desc) + ", " + JSON.stringify(err));
}
});
});
});
label {
margin-left: 15px;
}
#entityType {
margin: 15px 0 15px 15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/#jarstone/dselect/dist/css/dselect.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
<script src="https://unpkg.com/#jarstone/dselect/dist/js/dselect.js"></script>
<label for="entityType">Select Entity Type:</label>
<select id="entityType" name="entityType" class="select_box" required>
<option value="">Choose</option>
<option value="water">Water</option>
<option value="fire">Fire</option>
<option value="ground">Ground</option>
<option value="electric">Electric</option>
<option value="flying">Flying</option>
</select>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
</select>
<div id="list"></div>

I use $("#entityName")[0] to get at the DOM element from the jQuery Object
}).done(function(data){
$("#entityName").html(data);
dselect($("#entityName")[0], { search: true });
});
Example - you need to add some CSS I think
const $select_box_element = $('#entityName');
const $entity = $('#entityType');
$("select.entity").change(function(){
if (this.value === "one") {
$select_box_element.html(`<option value="one">One</option><option value="oneone">OneOne</option>`)
dselect($select_box_element[0], { search: true });
}
else {
$select_box_element.html(`<option value="two">Two</option><option value="twotwo">TwoTwo</option>`)
dselect($select_box_element[0], { search: true });
}
});
dselect($entity[0], { search: true });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/#jarstone/dselect/dist/css/dselect.css">
<script src="https://unpkg.com/#jarstone/dselect/dist/js/dselect.js"></script>
<label>Select Entity Type:</label>
<select id="entityType" name="entityType" class="entity" required>
<option value="" disabled selected>Select Entity Type</option>
<option value="one">One</option>
<option value="two">Two</option>
</select>
<label>Select Entity Name:</label>
<select id="entityName" name="entityName" class="select_box" required>
<option value="" disabled selected>Select Entity Type First</option>
<option value="one">One</option>
<option value="one">One</option>
</select>

Related

How to show selected value using javascript in laravel

i want to show the selected value to the select option, the value actually selected but cannot show that value on select option form.
for example i have a 3 value it can be choose is anyaman, cendana, and bakulan. when 1 edit that form with value cendana, the showed value is the first sequence (anyaman) but when i open that select option that focused on the true data value (cendana).
This is HTML Script :
<div class="mb-1">
<label class="form-label" for="user-role">Asal Kelompok</label>
<select id="editkelompok_id" name="kelompok_id" class="select2 form-select">
<option disabled="" value=""> <b> Pilih asal kelompok </b></option>
#foreach($kelompok as $data)
<option value="{{$data->id}}">{{$data->nama_desa}} - {{$data->nama_kelompok}} </option>
#endforeach
</select>
</div>
The Controller
public function detaildataanggota($id)
{
$status = anggota::findOrfail($id);
return $status;
}
Java Script
<script type="text/javascript">
function detaildataanggota(id){
$.ajax({
url: "{{url('admin/pendataan/dataanggota/detail')}}" + "/" + id,
dataType: "json",
success: function(status) {
$('#editid').val(status.id);
$('#editnama_anggota').val(status.nama_anggota);
$('#editnik').val(status.nik);
$('#editjabatan').val(status.jabatan);
$('#editjenis_kelamin').val(status.jenis_kelamin);
$('#edittanggal_lahir').val(status.tanggal_lahir);
$('#editalamat').val(status.alamat);
$('#editkelompok_id').val(status.kelompok_id);
},
});
}
</script>
The problem is on #editkelompok_id
Try this
let select = $('#editkelompok_id');
select.on('change',()=>{
// Your stuff
})
or
let options = $('#editkelompok_id').children();
options.each(function() {
let option = $(this);
option.on('change', () => {
select.val(option.val());
})
})
I hope it was useful

Bind API returned data to dropdownlist

I am trying to bind a dropdown list via javascript/jquery (anyone will work). Here is my code I tried -
$(document).ready(function () {
$.ajax({
type:"POST",
url: "function.php",
//dataType: "json"
success: function(result){
alert(result);
for (var i in result) {
$("#dropdownlist").append('<option value="'+result[i]+'">'+result[i]+'</option>');
};
}
});
});
On alert, it is showing data like this -
{"BU_CODE_RU":"DK"}{"BU_CODE_RU":"PL"}{"BU_CODE_RU":"SA"}{"BU_CODE_RU":"SP"}{"BU_CODE_RU":"RS"}{"BU_CODE_RU":"IS"}{"BU_CODE_RU":"SE"}{"BU_CODE_RU":"LT"}{"BU_CODE_RU":"GR"}{"BU_CODE_RU":"AT"}{"BU_CODE_RU":"DE"}{"BU_CODE_RU":"TR"}{"BU_CODE_RU":"CZ"}{"BU_CODE_RU":"US"}{"BU_CODE_RU":"TW"}{"BU_CODE_RU":"TH"}{"BU_CODE_RU":"EG"}{"BU_CODE_RU":"SI"}{"BU_CODE_RU":"HU"}{"BU_CODE_RU":"JP"}{"BU_CODE_RU":"IN"}{"BU_CODE_RU":"CA"}{"BU_CODE_RU":"UNK"}{"BU_CODE_RU":"MA"}{"BU_CODE_RU":"NL"}{"BU_CODE_RU":"RU"}{"BU_CODE_RU":"HK"}{"BU_CODE_RU":"ID"}{"BU_CODE_RU":"FR"}{"BU_CODE_RU":"IT"}{"BU_CODE_RU":"ES"}{"BU_CODE_RU":"NO"}{"BU_CODE_RU":"BE"}{"BU_CODE_RU":"KR"}{"BU_CODE_RU":"MY"}{"BU_CODE_RU":"FI"}{"BU_CODE_RU":"DO"}{"BU_CODE_RU":"KW"}{"BU_CODE_RU":"SK"}{"BU_CODE_RU":"GB"}{"BU_CODE_RU":"AE"}{"BU_CODE_RU":"IL"}{"BU_CODE_RU":"BG"}{"BU_CODE_RU":"AUW"}{"BU_CODE_RU":"SG"}{"BU_CODE_RU":"BH"}{"BU_CODE_RU":"QA"}{"BU_CODE_RU":"LV"}{"BU_CODE_RU":"AU"}{"BU_CODE_RU":"HR"}{"BU_CODE_RU":"CY"}{"BU_CODE_RU":"IE"}{"BU_CODE_RU":"UA"}{"BU_CODE_RU":"CE"}{"BU_CODE_RU":"CN"}{"BU_CODE_RU":"CH"}{"BU_CODE_RU":"RO"}{"BU_CODE_RU":"PT"}{"BU_CODE_RU":"PH"}{"BU_CODE_RU":"JO"}
How to bind those values to Dropdown List (Only Value). It will be better if I can add Default Value something like "Select Country".
If response is a string, you can use a regex
const data = `{"BU_CODE_RU":"DK"}{"BU_CODE_RU":"PL"}{"BU_CODE_RU":"SA"}{"BU_CODE_RU":"SP"}{"BU_CODE_RU":"RS"}{"BU_CODE_RU":"IS"}{"BU_CODE_RU":"SE"}{"BU_CODE_RU":"LT"}{"BU_CODE_RU":"GR"}{"BU_CODE_RU":"AT"}{"BU_CODE_RU":"DE"}{"BU_CODE_RU":"TR"}{"BU_CODE_RU":"CZ"}{"BU_CODE_RU":"US"}{"BU_CODE_RU":"TW"}{"BU_CODE_RU":"TH"}{"BU_CODE_RU":"EG"}{"BU_CODE_RU":"SI"}{"BU_CODE_RU":"HU"}{"BU_CODE_RU":"JP"}{"BU_CODE_RU":"IN"}{"BU_CODE_RU":"CA"}{"BU_CODE_RU":"UNK"}{"BU_CODE_RU":"MA"}{"BU_CODE_RU":"NL"}{"BU_CODE_RU":"RU"}{"BU_CODE_RU":"HK"}{"BU_CODE_RU":"ID"}{"BU_CODE_RU":"FR"}{"BU_CODE_RU":"IT"}{"BU_CODE_RU":"ES"}{"BU_CODE_RU":"NO"}{"BU_CODE_RU":"BE"}{"BU_CODE_RU":"KR"}{"BU_CODE_RU":"MY"}{"BU_CODE_RU":"FI"}{"BU_CODE_RU":"DO"}{"BU_CODE_RU":"KW"}{"BU_CODE_RU":"SK"}{"BU_CODE_RU":"GB"}{"BU_CODE_RU":"AE"}{"BU_CODE_RU":"IL"}{"BU_CODE_RU":"BG"}{"BU_CODE_RU":"AUW"}{"BU_CODE_RU":"SG"}{"BU_CODE_RU":"BH"}{"BU_CODE_RU":"QA"}{"BU_CODE_RU":"LV"}{"BU_CODE_RU":"AU"}{"BU_CODE_RU":"HR"}{"BU_CODE_RU":"CY"}{"BU_CODE_RU":"IE"}{"BU_CODE_RU":"UA"}{"BU_CODE_RU":"CE"}{"BU_CODE_RU":"CN"}{"BU_CODE_RU":"CH"}{"BU_CODE_RU":"RO"}{"BU_CODE_RU":"PT"}{"BU_CODE_RU":"PH"}{"BU_CODE_RU":"JO"}`
// success: function(data) {
var options = data.match(/:"(\w+)/g)
.map(cc => {
cc = cc.replace(/\W+/g,""); // remove non-letters
return `<option value="${cc}">${cc}</option>`;
});
$("#dropdownlist").append(options);
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdownlist">
<option value="">Please select</option>
</select>
Even more elegant using lookbehind, pointed out to me by Jonathan Lam
const data = `{"BU_CODE_RU":"DK"}{"BU_CODE_RU":"PL"}{"BU_CODE_RU":"SA"}{"BU_CODE_RU":"SP"}{"BU_CODE_RU":"RS"}{"BU_CODE_RU":"IS"}{"BU_CODE_RU":"SE"}{"BU_CODE_RU":"LT"}{"BU_CODE_RU":"GR"}{"BU_CODE_RU":"AT"}{"BU_CODE_RU":"DE"}{"BU_CODE_RU":"TR"}{"BU_CODE_RU":"CZ"}{"BU_CODE_RU":"US"}{"BU_CODE_RU":"TW"}{"BU_CODE_RU":"TH"}{"BU_CODE_RU":"EG"}{"BU_CODE_RU":"SI"}{"BU_CODE_RU":"HU"}{"BU_CODE_RU":"JP"}{"BU_CODE_RU":"IN"}{"BU_CODE_RU":"CA"}{"BU_CODE_RU":"UNK"}{"BU_CODE_RU":"MA"}{"BU_CODE_RU":"NL"}{"BU_CODE_RU":"RU"}{"BU_CODE_RU":"HK"}{"BU_CODE_RU":"ID"}{"BU_CODE_RU":"FR"}{"BU_CODE_RU":"IT"}{"BU_CODE_RU":"ES"}{"BU_CODE_RU":"NO"}{"BU_CODE_RU":"BE"}{"BU_CODE_RU":"KR"}{"BU_CODE_RU":"MY"}{"BU_CODE_RU":"FI"}{"BU_CODE_RU":"DO"}{"BU_CODE_RU":"KW"}{"BU_CODE_RU":"SK"}{"BU_CODE_RU":"GB"}{"BU_CODE_RU":"AE"}{"BU_CODE_RU":"IL"}{"BU_CODE_RU":"BG"}{"BU_CODE_RU":"AUW"}{"BU_CODE_RU":"SG"}{"BU_CODE_RU":"BH"}{"BU_CODE_RU":"QA"}{"BU_CODE_RU":"LV"}{"BU_CODE_RU":"AU"}{"BU_CODE_RU":"HR"}{"BU_CODE_RU":"CY"}{"BU_CODE_RU":"IE"}{"BU_CODE_RU":"UA"}{"BU_CODE_RU":"CE"}{"BU_CODE_RU":"CN"}{"BU_CODE_RU":"CH"}{"BU_CODE_RU":"RO"}{"BU_CODE_RU":"PT"}{"BU_CODE_RU":"PH"}{"BU_CODE_RU":"JO"}`
// success: function(data) {
$("#dropdownlist").append(
data.match(/(?<=:")(\w+)/g)
.map(cc => `<option value="${cc}">${cc}</option>`)
)
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdownlist">
<option value="">Please select</option>
</select>
Note: Browser support for JS RegExp lookbehind (ES2018 draft) is still low. See the compatibility table on MDN for more details.
Original answer for simpler format ({"DK"}{"PL"}{"SA"}....) :
var options = data.match(/[A-Z]{2,}/g).map(cc => `<option value="${cc}">${cc}</option>`)
const data = `{"DK"}{"PL"}{"SA"}{"SP"}{"RS"}{"IS"}{"SE"}{"LT"}{"GR"}{"AT"}{"DE"}{"TR"}{"CZ"}{"US"}{"TW"}{"TH"}{"EG"}{"SI"}{"HU"}{"JP"}{"IN"}{"CA"}{"UNK"}{"MA"}{"NL"}{"RU"}{"HK"}{"ID"}{"FR"}{"IT"}{"ES"}{"NO"}{"BE"}{"KR"}{"MY"}{"FI"}{"DO"}{"KW"}{"SK"}{"GB"}{"AE"}{"IL"}{"BG"}{"AUW"}{"SG"}{"BH"}{"QA"}{"LV"}{"AU"}{"HR"}{"CY"}{"IE"}{"UA"}{"CE"}{"CN"}{"CH"}{"RO"}{"PT"}{"PH"}{"JO"}`
// success: function(data) {
var options = data.match(/[A-Z]{2,}/g).map(cc => `<option value="${cc}">${cc}</option>`)
$("#dropdownlist").append(options);
// }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="dropdownlist">
<option value="">Please select</option>
</select>

Dependent Dropdown using Java script works only on change primary dropdown, It must work on page load if primary dropdown already selected

I have One Primary drop-down (Country) and second dependent dropdown. (State). This code works fine only when we select primary dropdown. but doesnt work if primary dropdown already selected on page load.
Primary Dropdown Country:
<select class="select4" name="country" id="country">
<option value="">Please Select</option>
#foreach($country_data as $country)
<option value="{{$country->country_id}}" {{$profile_data->country == $country->country_id ? 'selected' : ''}}>{{$country->country_name}}</option>
#endforeach
</select>
Dependent Dropdown State:
<select class="select4" name="state" id="state">
<option value="">Please Select</option>
#foreach($state_data as $state)
<option value="{{$state->state_id}}" {{$profile_data->state == $state->state_id ? 'selected' : ''}}>{{$state->state_name}}</option>
#endforeach
</select>
Java Script code to fill dependent dropdown.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="country"]').on('change', function() {
var countryID = $(this).val();
if(countryID) {
$.ajax({
url: 'family/state/'+countryID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="state"]').empty();
$.each(data, function(key, value) {
$('select[name="state"]').append('<option value="'+ value.state_id +'">'+ value.state_name +'</option>');
});
}
});
}else{
$('select[name="state"]').empty();
}
});
});
How Ajax code must work on page load also?
You're going to need to manually trigger the change event.
After your:
$('select[name="country"]').on('change', function() { ... }
Force trigger:
$('select[name="country"]').trigger('change');
That way when your document.ready function is about to wrap up, you can force trigger the event and if its set, it'll fire the ajax call

Fetching data through ajax and then apply filter using select

I have 3 different select menu: 1.Category 2.State 3.City
I am using ajax to fetch the data on "#searchresult" by using jquery on change method that send data on PHP.
Fetching is going properly but only for one "select" option.
What I want is when user change another "select" option, it will update the current "#searchresult" fetched data.
Like: Suppose, on changing "category" to "car", it fetch all the data of "cars" on "#searchresult" and now on "state" change to "new york", it update the "#searchresult" that are in new york.
I tried many different approches like using multiple if statements to find whether the select is choosen or not, but reached no where.
Thanks in advance.
My code is:
$(document).ready(function() {
$("#category").change(function() {
var data = $("#category option:selected").val();
var category = $("#category option:selected").text();
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "category",
data: {
data: data
},
dataType: 'json',
cache: false,
success: function(response) {
$("#searchresult").html("");
for (var i = 0; i <= 5; i++) {
$("#searchresult").append('<div class="col-12 col-sm-10 col-md-4 col-lg-3 col-xl-2 merchant" style="background-image: url(https://im.proptiger.com/1/1543935/6/green-villa-elevation-7990949.jpeg?width=380&height=285);"> <div class="filter"></div> <span class="category">' + category + '</span> <div class="col align-self-end"> <p>' + response.contractor[i].first_name + '</p> <span>' + response.contractor[i].city_name + ',' + response.contractor[i].state_name + '</span> </div> <div class="slideup"> <p>More info?</p> Profile </div> </div>');
}
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
and PHP is sending data in the form of json.
Thanks
#user5745970 here is sample fiddle I created to give you an idea on what needs to be done. Link to the fiddle is below
The idea is to have 3 different change events for each of your select and trigger a call to your server. What you need to do is send the other select values as data if selected. For example, if you're changing the City when the category is already selected, you need to send both category and city to your server to get you the response. If all 3 server side calls return the same JSON structure, then you can have only 1 success and error callback.
Do change the urls, method types and callbacks accordingly to match what you need.
$(document).ready(function() {
var category = '';
var state = '';
var city = '';
$("#category").on('change', function() {
category = $("#category option:selected").text();
// here you need to check if state or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', category, handleCategorySuccess, handleCategoryError)
});
$("#state").on('change', function() {
state = $("#state option:selected").text();
// here you need to check if category or city is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', state, handleStateSuccess, handleStateError)
});
$("#city").on('change', function() {
city = $("#city option:selected").text();
// here you need to check if state or category is selected, you need to send those values as the data to your server
ajax('https://jsonplaceholder.typicode.com/posts/1', 'GET', city, handleCitySuccess, handleCityError)
});
});
var ajax = function(url, method, data, successCallBack, errorCallBack) {
$.ajax({
type: method,
url: url,
data: data,
dataType: 'json',
cache: false,
success: successCallBack,
error: errorCallBack
});
}
function handleCategorySuccess(response) {
alert(response);
}
function handleCategoryError() {
alert('error');
}
function handleStateSuccess(response) {
alert(response);
}
function handleStateError() {
alert('error');
}
function handleCitySuccess(response) {
alert(response);
}
function handleCityError() {
alert('error');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="category" id="category" class="chosen">
<option value="0" default>category</option>
<option value="1">Car</option>
<option value="2">Van</option>
</select>
<select name="state" id="state" class="chosen">
<option value="0" default>state</option>
<option value="1">Any</option>
<option value="2">other</option>
</select>
<select name="city" id="city" class="chosen">
<option value="0" default>city</option>
<option value="1">New york</option>
<option value="2">Chicago</option>
</select>
<div id="searchresult"></div>
JSFiddle

Show/Hide div send all data to database

I have this show/hide div. And I am running into couple issues. I am using CodeIgniter by the way.
First : When I select real-estate the div shows. But if I select Service, the real-estate div won't hide. (Service has no div).
Second : If I select real-estate and fill out the form, and I change my mind and select automobile and fill out the form then send to database, I get all the fields from real-estate and automobile into my database. Which is not what I want.
Third : Is there a different approach if I wanna add more categories and more divs show/hide?
<select id="catid_1" name="catid_1">
<option value=""></option>
<option value="5">Real-Estate</option>
<option value="8">Automobile</option>
<option value="10">Service</option>
</select>
<!--Auto-->
<div id="8" class="forms">
Energie :
<select name="energy">
<option></option>
<option value="Gasoline">Gasoline</option>
<option value="Diesel">Diesel</option>
<option value="GPL">GPL</option>
<option value="Electric">Electric</option>
<option value="Hybrid">Hybrid</option>
</select><br />
Transmission :
<select name="tans">
<option></option>
<option value="Manuel">Manuel</option>
<option value="Automatic">Automatic</option>
</select><br />
Miles :
<input type="text" name="mile"/><br />
Year :
<input type="text" name="year"/><br />
</div>
<!--Realestate-->
<div id="5" class="forms">
Room :
<input type="text" name="room"/><br />
Surface :
<input type="text" name="surface"/><br />
</div>
<!--End Tech-->
$(function() {
$(".forms").hide();
$("#catid_1").change(function() {
var e = $(this).val();
if(e == '8' || e == '5') {
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
});
// Bind to the submit
$('#submit').click(function(e){
e.preventDefault();
// Parse the data only for the displayed div.
var resolve_data = function() {
var output = {};
// Here you place the acceptable fields.
$('.form-active input, .default input').each(function() {
output[$(this).attr('name')] = $(this).val();
});
return output;
};
// Submit the form here.
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: resolve_data(),
beforeSend: function(xhr, settings){
// Before sending, check the data.
alert(settings.data);
},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
});
});
first: service show/hide is not working because you're putting a conditional on the ID:
if(e == '8' || e == '5') { // <<-- remove this conditional
$(".forms").hide().parent().find('#' + e).show().addClass('form-active');
}
second: When you're doing your update, check the value of the drop down box and only update the fields that belong to that choice. Your form should be sending along the value of the option, so that's not to hard to do. For instance, if the select value is 5, only update the room and surface fields in your database. Don't try to clear the form when switching choices, it's safer to do this in the back end.
If you insist on doing it front end, put an actual form in there and .reset() it when changing options.
third: probably, but this seems OK no? Are you not happy with it?
http://jsfiddle.net/zf9BN/1/

Categories