How to avoid ajax result on select box - javascript

As you in sample above I have placeholder (option without value) to say eg. Select Subcategory but as soon as I change my category value result of subcategories will show.
What I want is when I select category in subcategory dropdown still says Select Subcategory but under that be loaded result of chosen category. In simple words:
Instead of showing results directly, shows placeholder option and
results be under it.
here is my codes:
// HTML
<label for="specification_id">specifications</label>
<select name="specification_id" class="form-control">
<option value="">Select Specification</option>
</select>
// JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('select[name="subcategory_id"]').on('change', function() {
var subcategoryID = $(this).val();
if(subcategoryID) {
$.ajax({
url: '{{ url('getspecifications') }}/'+encodeURI(subcategoryID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="specification_id"]').empty();
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+ value['id'] +"'>"+ value['title'] +"</option>"
);
});
}
});
}else{
$('select[name="specification_id"]').empty();
}
});
});
</script>

After emptying out the item make sure to append the blank placeholder back in it:
else{
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
}
or just skip it when clearing the select in the first place:
else{
$('select[name="specification_id"]').not(':first').remove();
}
i forgot the empty() in the success: function:
success:function(data) {
$('select[name="specification_id"]').not(':first').remove();
//...
or:
success:function(data) {
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
//...

Here your option values are empty because you Call empty function.
So you can dynamically select option "Select specification "
Following procedure works fine for me, try this way
success:function(data) {
$('select[name="specification_id"]').empty();
$('select[name="specification_id"]').append("<option
class='form-control' selected value=' '>Select
Specification </option>" );
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+
value['id'] +"'>"+ value['title'] +"</option>"
);
});
Thank you

Related

how to take data[index] value in ajax?

Sorry but it's my first time with javascript and ajax
I have this code where i print a list from db in an html select
ajax
'''
$.ajax({
type: 'GET',
url: 'birthplace/list',
dataType: 'json',
success: function(data) {
$.each(data, function(i) {
$('#selectBirthplace').append(
'<option id="' + data[i] + '" value="' + data[i] + '">'
+ data[i].nome + '</option>'
);
});
}
});
'''
html
'''
<div class="item3">
<label for="">Birthplace</label>
<select required class="custom-input" id="selectBirthplace" >
<option value="" selected disabled hidden>Select birthplace</option>
</select>
</div>
'''
Birthplace is a parameter of User but it's still a class.
This is part of a user insert form page.
How can i save the value of data[i] in a variable when the select option was chosen?
i tried with data[i].variable, data[i].class but nothing.

Append a dynamic select box to a div after button click

I am trying to append an accordion div after a button click. That works fine. But inside the appended div I have a select box , that has to be dynamically populated. After getting the Json results I tried to append the option values, but it failed. When I alert, I am getting the exact results.
Here is my controller
public function getTypes(){
$types = AnsTypes::get();
return response()->json($types);
}
My Ajax
$.ajax({
url: site_base_url+ '/surveys/getquestiontypes',
type: "get",
contentType: "application/json",dataType: "json",
success: function(data){ // What to do if we succeed
if(data){
$(".group:last").after('<div class="group">' +
'<select class="custom-select" class="answer_datatype_id">' +
$.each(data, function(key, value){
'<option value="'+value.answer_datatype_id+'">' + value.type_name + '</option>'
}) +
'</select>'+
'</div>');
});
My response payload is:
JSON
0 {…}
answer_datatype_id 1
type_name Text
1 {…}
answer_datatype_id 2
type_name RadioButton
2 {…}
answer_datatype_id 3
type_name CheckBox
3 {…}
answer_datatype_id 4
type_name ListSingleSelection
4 {…}
answer_datatype_id 5
type_name ListMultiSelection
Response payload
[{"answer_datatype_id":1,"type_name":"Text"},{"answer_datatype_id":2,"type_name":"RadioButton"},{"answer_datatype_id":3,"type_name":"CheckBox"},{"answer_datatype_id":4,"type_name":"ListSingleSelection"},{"answer_datatype_id":5,"type_name":"ListMultiSelection"}]
My Result
this look like your $.each not return the <option> to your DOM. You can try to add the <option> to a variable called options :
let options = "";
$.each(data, function(key, value){
options +='<option value="'+value.answer_datatype_id+'">' + value.type_name + '</option>'
})
then you add your options to your DOM like this:
$(".group:last").after('<div class="group">' +
'<select class="custom-select" class="answer_datatype_id">' +
options
+
'</select>'+
'</div>');
this should work.
For the record I already tried this code and it works well, please let me know if you need something else.

on change from jquery is not doing what it supposed to do

I have 4 Ajax Scripts that update chained dropdowns based on other one selections
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#building');
//request the JSON data and parse into the select element
$.ajax({
url: '/api/get_building/',
dataType:'JSON',
success:function(data){
//clear the current content of the select
//iterate over the data and append a select option
$.each(data, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
function getunit() {
//get a reference to the select element
$select = $('#unit');
$id_lease = $('#id_lease');
$id_leaseterm = $('#id_leaseterm');
//request the JSON data and parse into the select element
var c_id = ($("select[name='building'] option:selected").attr('value'));
c_url = "/api/get_unit/"+c_id+"/";
$.ajax({
url: c_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1"> Select unit </option>');
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
getlease();
},
});
}
function getlease() {
//get a reference to the select element
$select = $('#id_lease');
$id_leaseterm = $('#id_leaseterm');
//request the JSON data and parse into the select element
var s_id = ($("select[name='unit'] option:selected").attr('value'));
s_url = "/api/get_lease/"+s_id+"/";
$.ajax({
url: s_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1"> Select lease</option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
function getleaseterm() {
//get a reference to the select element
$select = $('#id_leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
//var l_id = 13;
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
</script>
And the following controls in my form I am updating
<select name="building" id="building" onchange="getunit();">
<option id="-1">Select building</option>
</select>
<select name="unit" id="unit" onchange="getlease();">
<option id="-1">Select unit</option>
</select>
<select class="select" id="id_lease" name="lease">
<option value="" selected="selected">---------</option>
</select>
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="" selected="selected"></option>
</select>
My problem is that when I update the dropdown id_lease it dosent have the on change call. (it is automatically generated from backend)
So for this reason I am adding this line with jquery line in script
$("#lease_id").on("change", getleaseterm());
but it gives me an error 404 that cannot find the values for "get_leaseterm" since I assume it get triggered when page is loading. And all my script are not loading.
So problem is in this last line. How can I solve it?
As Pointy specified removing the () helped as well I was calling wrong id
final version that worked is:
$("#id_lease").on("change", getleaseterm);

jQuery...populating multiple dropdowns

I have an ajax call like so and for each result, I am displaying a dropdown menu like so:
$.each(results, function (key, value) {
html += "<select id='vendorDropdown'><option value='0'>-- Select Vendor --</option></select>"
}
and I am populating the dropdown with another ajax call:
$.ajax({
type: "GET",
url: "/vendorProject/api/connection/getVendors",
dataType: 'json',
cache: false,
success: function (results) {
var vendorDropdown = $("#vendorDropdown");
$.each(results, function (row, value) {
vendorDropdown.append($("<option />").val(value.Vendor_ID).text(value.Vendor_Name));
});
}
});
my problem is that this only populates the first dropdown and not any others, this is due because they all have the same id...what I am trying to do now is make the id unique with the value:
$.each(results, function (key, value) {
html += "<select id='vendorDropdown-" + value +"'><option value='0'>-- Select Vendor --</option></select>"
}
my question is, how would I target these dropdowns with the unique id in the other ajax call ?
Try this,
var cnt = 0;
$.each(results, function (key, value) {
html += "<select id='vendorDropdown-" + value + i +"'><option value='0'>-- Select Vendor --</option></select>"
i++;
}

How to make multiple dependent dropdowns using jquery + ajax

I'm trying to build a page where users can give worksheets to each other.
I am trying to do it with dependent dropdowns. Not sure if that is the right term for it so I will provide an example.
Roughly the set categorizations is as follows:
Types > Categories > Topics > Sheets
Roughly my idea is:
Page loads json for types and displays type dropdown
User sees Math, Science, English as Types and Picks Math
Page uses ajax to query database and populates Topics with grade 1, 2, 3, etc.
User picks grade 4
Page uses ajax to query database and populates with appropriate grade 4 topics
... and so on until the bottom of the chain
In the javascript section:
<script type="text/javascript" language="javascript">
var types;
var categories;
var topics;
var sheets;
//load the first types
$(document).ready(function(){
$.ajax({
async: false,
url: "base_url/json_get_all_wstypes",
type: 'POST',
dataType: 'json',
success: function(output_string){
types = output_string;
}
});
});
//by default - intialize types
$(document).ready(function(){
var t_choices = "<select name=\"type_id\" id=\"type_picker\" >";
t_choices += "<option value=\"\" selected=\"selected\">Select a Type</option>";
$.each(types, function(){
t_choices += "<option value=\"" + this.type_id.toString() + "\">";
t_choices += this.type_name.toString();
t_choices += "</option>";
});
t_choices += "</select>";
$('#type_choices').text('');
$(t_choices).appendTo('#type_choices');
});
//reaction to picking a type
$(document).ready(function(){
$('#type_picker').change(function(){
var url_arg = $('#type_picker').val().toString();
var full_url = "base_url/json_get_wscategories_by_type/" + url_arg;
$.ajax({
async: false,
url: full_url,
type: 'POST',
dataType: 'json',
success: function(output_string){
categories = output_string;
}
});
var choices = "<select name=\"category_id\" id=\"category_picker\" >";
choices += "<option value=\"\" selected=\"selected\">Select a category</option>";
$.each( categories, function() {
choices += "<option value=\"" + this.category_id.toString() + "\">";
choices += this.category_name.toString();
choices += "</option>";
});
choices += "</select>";
alert(choices.toString());
$('#category_choices').text('');
$(choices).appendTo('#category_choices');
});
});
//reaction to picking a category (initialize topic)
$(document).ready(function(){
$('#category_picker').change(function(){
var url_arg = $('#category_picker').val().toString();
var full_url = "base_url/json_get_wstopics_by_category/" + url_arg;
$.ajax({
async: false,
url: full_url,
type: 'POST',
dataType: 'json',
success: function(output_string){
topics = output_string;
}
});
var choices = "<select name=\"topic_id\" id=\"topic_picker\" >";
choices += "<option value=\"\" selected=\"selected\">Topic a category</option>";
$.each( topics, function() {
choices += "<option value=\"" + this.topic_id.toString() + "\">";
choices += this.topic_name.toString();
choices += "</option>";
});
choices += "</select>";
alert(choices.toString());
$('#topic_choices').text('');
$(choices).appendTo('#topic_choices');
});
});
//reaction to picking a topic (initialize sheet)
similar code pattern as method before it...
//reaction to picking a sheet (intialize page)
similar code pattern as the method before...
</script>
In the webform section:
<p>
<label for="type_id">Pick a sheet type:</label>
<div id="type_choices">
</div>
</p>
<p>
<label for="categories_id">Pick a category:</label>
<div id="category_choices">
</div>
</p>
<p>
<label for="topic_id">Pick a topic:</label>
<div id="topic_choices">
</div>
</p>
<p>
<label for="worksheet_id">Pick a worksheet:</label>
<div id="sheet_choices">
Please select a topic first to activate this section
</div>
</p>
This works for selecting the types and loads up the display for categories but once I select categories nothing happens. Also, if anyone could point me to what is called in the web world, I would be quite thankful. Dynamic dependent dropdown weren't that helpful and I'm not sure what else to call this.
Your code is unnecessarily dependent on jQuery and doesn't re-use code effectively. This solution may require a subtle rewrite of your server side code, but that should be more abstracted anyway. Try something more like this:
<html>
<body>
<select id="type" onchange="updateNext(this, 'category')">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
</select>
<select id="category" onchange="updateNext(this, 'topic')">
</select>
<select id="topic" onchange="updateNext(this, 'worksheet')">
</select>
<script>
function updateNext(el, nextName) {
var url_arg = el.value;
var full_url = "base_url/json_get_wstopics_by_category/" + url_arg;
var options, txtStrng;
//grab ajax data
$.ajax({
async: false,
url: full_url,
type: 'POST',
dataType: 'json',
success: function(output_string){
options= output_string;
}
});
//create the option list
$.each( options, function() {
txtStrng += "<option value=\"" + this.option_id.toString() + "\">";
txtStrng += this.option_name.toString();
txtStrng += "</option>";
});
//clear the option list
$('#'+nextName).text('');
//attach the option list
$(txtStrng).appendTo('#'+nextName);
}
</script>

Categories

Resources