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>
Related
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.
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
When I edit my product, I want to my categories appear inside the dropdown. Currently it's just
-- Select your category --
For example, my $current_category_id = 2, the dropdown must display the good categories.
How to do that ?
tk
<div id="myAjax"><select name="move_to_category_id" id="category_id"><option value="0">-- Select your categorie --</option></div>
<script type="text/javascript">
jQuery(document).ready(function() {
$("#myAjax").on('click', function () {
var selectedOptionVal = $('#category_id').val();
$.ajax({
url: '<?php echo $categories_ajax; ?>',
dataType: 'json',
success: function (data) {
//data returned from php
var options_html = '';
for (var index in data) {
var category_id = data[index]['id'];
var category_name = data[index]['text'];
var selectedString = category_id == selectedOptionVal ? ' selected="selected"' : '';
options_html += '<option value="' + category_id + '"' + selectedString + '>' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
});
})
</script>
Your code says, while clicking on the div you are doing an ajax call based on the selected value in the select box. But there will not be any value while clicking since you are updating the select box after that.
Call the ajax on on ready and populate your drop down box.
I have a form which selects regions, provinces, and cities. The select options for provinces depends on the selected region and the options for cities depends on the selected province. All the options are from the database
I have already made the region show up with this code.
<select class="form-control" id="region" name="region">
<?php
if( isset($Region) && count($Region)>0 ){
foreach($Region as $Region){
echo '
<option>'.$Region['region'].'</option>
';
}
}else{
echo '
<option>NO RECORDS FOUND</option>
';
}
?>
</select>
Could you please help me on my next step which is to display the options for provinces?
<select class="form-control" id="province" name="province">
</select>
I believe after achieving this step I would be able to do the same for displaying cities. Thank you!
Database name: patrol
table name: geography
>id
>region
>province
>city
I've tried the same as this one by putting this script
<script>
$(function() {
$(document).ready(function () {
$('#region').change(function() {
var select = $('#province').empty();
$.get('script.php', {region: $(this).val()}, function(result) {
$.each(result, function(i, item) {
$('<option value="' + item.value + '">' + item.name + '</option>').
appendTo(select);
});
});
});
});
});
</script>
and having this script.php
<?php
if (isset($_GET['region'])) {
$sql = new mysqli('localhost','root','','patrol');
$region = mysqli_real_escape_string($sql,$_GET['region']);
$query = "SELECT * FROM geography WHERE region = $region";
$ret = $sql->query($query);
$result = array();
while ($row = $ret->fetch_assoc()) {
$result[] = array(
'value' => $row['id'],
'name' => $row['province']
);
}
echo json_encode($result);
}
?>
<option>'.$Region['region'].'</option>
You did not set any value in region select option.
It should be like below:
<option value="'.$Region['region'].'">'.$Region['region'].'</option>
also use console.log(result) to see you are getting expected data back or not.
Thank you for answering guys. However, I have found an answer and it did the fix. I'll post the script for others who have the same question as mine
<script type="text/javascript">
$(document).ready(function()
{
$("#region").change(function()
{
var region= document.getElementById("region").value;
var dataString = 'region='+ region;
$.ajax
({
type: "POST",
url: "get_province.php",
data: dataString,
cache: false,
success: function(html)
{
$("#province").html(html);
}
});
});
$("#region").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
$("#province").change(function()
{
var province= document.getElementById("province").value;
var dataString = 'province='+ province;
$.ajax
({
type: "POST",
url: "get_city.php",
data: dataString,
cache: false,
success: function(html)
{
$("#city").html(html);
}
});
});
});
</script>
m trying to add some <option> in existing <select> dynamically, but facing error "An attempt was made to reference a Node in a context where it does not exist." i have tried to resolve it failed...
HTML code:
<label class="control-label" for="selectError">Ayat/Hadith no.:</label>
<div class="controls">
<select id="ayat_selector" disabled >
<option id="all_ayat" selected>All </option>
</select>
</div>
javascript :
var selectHTML = "<option id='200'>Select Surah</option>";
alert("ajax going ");
$.ajax({
url: "../Surah_CRUD/Load_Surahs",
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
data: '',
success: function (result) {
var mera_obj = result.key;
for (var i = 0; i < 5; i++) {
selectHTML += "<option id='" + i + "'>" + mera_obj[i].Surah_Description + "</option>";
}
var qa = document.getElementById('ayat_selector');
qa.appendChild(selectHTML);
alert("done"+qa.className);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("3> " + thrownError);
},
});
The problem is that you trying to select an element by id that isn't exist.
try to change this:
var qa = document.getElementById('surah_selector');
to this:
var qa = document.getElementById('ayat_selector');
UPDATE
try to change this
var qa = document.getElementById('ayat_selector');
qa.appendChild(selectHTML);
alert("done"+qa.className);
With this code in jQuery:
$('#ayat_selector').append(selectHTML);
alert('done');