How to populate a subcategory based on category - javascript

I am working on a form where subcategory is decided on basis of category but both category and subcategory are being fetched from database.
Earlier when database is not involved in it I used javascript populate method for the same where data is dummy
so i am trying to include the code for fetching subcategory from database in the same.
Here is my code uptill now
<label>Job Category*</label>
<?php
$dataset = $objCmn->getCat(); \\for getting category from database
?>
<select id="jb-category" class="form-control" name="jb_category" onchange="populate(this.id, 'sub-category')" required>
<option>Choose Category</option>
<?php
foreach ($dataset as $key => $cat) {
echo '<option value="' . $cat['maincategory_name'] . '">' . $cat['maincategory_name'] . '</option>';
}
?>
</select>
<label>Sub Category*</label>
<select id="sub-category" class="form-control" name="sub_category" required>
</select>
function for populating the subcategory on base of category
function populate(s1, s2)
{
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
var categoryValue = s1.value;
alert(categoryValue);
document.writeln(categoryValue);
<?php $category_name = "<script>document.writeln(categoryValue)</script>";
$categoryName = $objCmn->getSubCategory($category_name);
foreach($categoryName as $key=>$row)
{
?>
var optionArray = ["<?php $row['cat_name'] ?>|<?php $row['cat_name'] ?>",];
<?php
}
?>
for (var option in optionArray)
{
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
</script>
Is there any other way then embedding the php code inside JS for the same .
Previous i have tried to close script tag before php tag and open the same after php closing tag but it is also not working.

A more elegant way to do this is to get the identifier of the category that has been selected, send it to your php script via ajax, fetch it's corresponding subcategories, return them back to javascript and then populate your subcategory selection.
If you are not familiar with AJAX, this might be of some help.
You can also have a look at some jquery methods here;

Related

two dependent dropdowns php arrays

I'm trying to substitute the code that uses javascript and arrays which are visible in source code.
I want to be able to create this with php arrays, or use AJAX and have it stored in another file. I don't know how to make the proper php commands or arrays
var cars= new Array();
cars["OTHER"] = new Array("Heavy Machinery","Semi-Truck","Pickup Truck","Sedan","SUV","Misc");
cars["ATV"] = new Array("small","large");
cars["Boat"] = new Array("Under 20 Feet","Over 20 Feet");
cars["Motorcycle"] = new Array("250CC","500CC","700CC","900+");
cars["RV"] = new Array("Under 25 Feet","Over 25 Feet","5th Wheel");
cars["AC"] = new Array("Cobra");
cars["Acura"] = new Array("1.6 EL","1.7 EL","2.3 CL","2.5 TL","3.0 CL","3.2 TL","3.5 RL","CL","CSX","EL","ILX","Integra","Legend","MDX","NSX","NSX-T","RDX","RL","RSX","SLX","TL","TSX","Vigor","ZDX");
cars["Alfa Romeo"] = new Array("145","146","147","155","156","159","164","166","33","75","308","1900","2600","4C","6C","8C","Alfasud","Alfetta","Berlina","Bimotore","Canguro","Corsa","Disco Volante","Duetto","G1","GT","GTV","GTV-6","GTV6","Giulia","Guiletta","GP","Grand Prix","GTA","Iguana","Junior Z","Milano","Montreal","Navajo","P1","P2","P3","Quadrifoglio","RL","RM","Scarabeo","Spider","Sports Car","Sportwagon","Stradle","Tipo","Torpedo");
........................ALL OTHER MAKES AND MODELS ARE IN BETWEEN........................
cars["Yugo"] = new Array("55","Cabrio","GV");
jQuery(document).ready(function($){
$('span.text select').change(function(){
$(this).siblings('.value').text($(this).find('option[value="'+$(this).val()+'"]').text());
});
for ( make in cars )
{
$('#formmake').append('<option value="'+make+'">'+make+'</option>');
}
$('#formmake').change(function(){
var val = $(this).val();
$('#formmodel').html('<option value="">Select Model</option>');
for ( i in cars[val] )
{
$('#formmodel').append('<option value="'+cars[val][i]+'">'+cars[val][i]+'</option>');
}
$('#formmodel').append('<option value="Other">- Other -</option>');
});
$('#formmake, span.text select').each(function(){
var def = $(this).siblings('.value').text();
$(this).find('option[value='+def+']').attr('selected', 'selected');
$(this).change();
});
});
---------------------- this is what i want to do to HIDE the source on the site --------------------
here is my php to get the MAKE but how do I create the model array so that when a user chooses a car the appropriate MODELS will populate in the corresponding dropdown (called Select Model: )
<?php
$car_make = array('ATV','Boat','Motorcycle','Acura','Alfa Romeo','AM General'); //this is only a partial array, it will have all the makes
echo '<select name="car_make">';
for($i = 0; $i < count($car_make);$i++)
{
echo '<option value="'. ($i + 1) . '">' . $car_make[$i] . '</option>';
}
echo '</select>';
?>
how do i create a second array with vehicle models that will use the first array's option value to lookup a make and then pull the corresponding make's from the model array ?
Well you can use jQuery to select the value of the first select menu and then use it to compare with the specific value for make and then display its specific models
var model=new Array();
function getmodel() {
var make=$('select[name=make]').val();
if(make==='toyota'){$("select[name=model]").html('');$("select[name=model]").append("<option value='corolla'>Corolla</option><option value='camry'>Camry</option><option value='hilux'>Hilux</option>");}
if(make==='honda'){$("select[name=model]").html('');$("select[name=model]").append("<option value='civic'>Civic</option><option value='jazz'>Jazz</option><option value='accord'>Accord</option>");}
if(make==='suzuki'){$("select[name=model]").html('');$("select[name=model]").append("<option value='cultus'>Cultus</option><option value='vitara'>Vitara</option>");}
if(make==='bugatti'){$("select[name=model]").html('');$("select[name=model]").append("<option value='veyron'>Veyron</option><option value='chiron'>Chiron</option>");}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SELECT MAKE:
<select name='make' onchange='getmodel();'>
<option value='toyota'>TOYOTA</option>
<option value='honda'>HONDA</option>
<option value='suzuki'>SUZUKI</option>
<option value='bugatti'>BUGATTI</option>
</select>
<br/>
SELECT MODEL
<select name='model'>
</select>

Populate select box from database query based on another select box using only 1 table

Hi guys I am currently creating a website with the main function of booking cars. Therefore the user would be first able to select a car category from the database query which will output the selected car category names. After selecting the car category name, the second select box would then by dynamically updated with a new set of of car names that are associated with the category.
There may have been many similar questions to this however for the website NO jQuery or AJAX can be utilized. And other questions and examples often utilize 2 or more tables however I am using only 1 table for this function.
The example below should show how the Select box should be updated:
Dynamically updated select box.
The table utilized is this:
Table Utilized
My codes are as such:
<?php
session_start();
include "dbconn.php";
$query = "SELECT carid, brand FROM cars";
$result = $dbcnx->query($query);
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
}
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
Car Category:<br />
<select size="1" name="categoriesSelect" id="categoriesSelect">
<option> Select Car Category </option>
<option value="sedan"> Sedan </option>
<option value="mpv"> MPV </option>
<option value="hatch"> Hatchback </option>
</select><br /><br />
Car Brand:<br />
<select id='subcatsSelect'>
</select>
</body>
</html>
I may have identified the error to the php statement:
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
As I can only see the first select box query correctly consisting of the 3 car category of MPV, Sedan and Hatchback.
Currently the all the Car Brand name appears however the results do not correspond with the car category as shown in the database.
Thank You.
As both arrays in PHP follow the same pattern when created the json data will be similar also thus the method to traverse the data should follow that in loadCategories function - so perhaps this:
function updateSubCats(){
var oSelect = document.getElementById("subcatsSelect");
oSelect.options.length = 0;
for( var i in subcats ){
oSelect.options[ i ]=new Option( subcats[ i ].val, subcats[ i ].id );
}
}
Without using Ajax or over complicating things with complex json iteration you could try along these lines. It should be noted that embedding the $_GET variable directly in the sql is not the best option - prepared statements would be better but should give the idea.
<?php
session_start();
include "dbconn.php";
?>
<!docytpe html>
<html>
<head>
<title>Chained select</title>
<script type='text/javascript'>
function bindEvents(){
document.getElementById('categories').addEventListener( 'change', getSubcategories, false );
}
function getSubcategories(e){
var el=e.target ? e.target : e.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
location.search='?category='+value;
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<form>
<select id='categories'>
<?php
$query = "SELECT carcat FROM cars";
$result = $dbcnx->query($query);
while( $row = $result->fetch_assoc() ){
echo "<option value='{$cat['carcat']}'>{$cat['carcat']}";
}
?>
</select>
<select id='subcategories'>
<?php
if( !empty( $_GET['category'] ) ){
$sql = "SELECT carid, brand FROM cars where carcat='{$_GET['category']}';";
$result = $dbcnx->query( $sql );
if( $result ){
while( $row = $result->fetch_assoc() ){
echo "<option value='{$row['carid']}'>{$row['brand']}";
}
}
}
?>
</select>
</form>
</body>
</html>
Of course it won't, you're accessing your arrays wrong:
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
^^^^^ ^^^^^
Your subcats array is only 2-dimensional, yet you're accessing it as a 3-dimentional array here.

Checking if selected option is unique

I'm working on school project and I have a problem with validating select boxes. It's very simple trip planner and let's say that I have 3 places that user visited and now he has the option to determine the order of visits. For example: [1]cinema, [3]concert,[2]shopping mall. The select boxes are generated automatically by PHP. How can I write universal jQuery script that validates the select boxes that each of them is unique?
Here is PHP code that generates the select fields;
$title = $_GET['title'];
$elements = count($_GET['eventid']);
echo "<h5>Order your trip</h5>";
foreach($_GET['eventid'] as $index => $id)
{
echo"<strong>" .$title[$index] . "</strong><select name='".$id."'>";
for($i=1;$i<=$elements;$i++){
echo"<option value='". $i ."'>". $i ."</option>";
}
echo"</select><br><br>";
}
Now I would like to validate select boxes no matter how many events there are. I came up with this code. It works but can it be done easier?
$('#validate').click(function() {
var selectValues = new Array();
$('select.order').each(function() {
selectValues.push($(this).val());
});
var elements = selectValues.length;
var i;
for (i = 0; i < elements - 1; i++) {
if (selectValues[i] == selectValues[i + 1]) {
alert('error');
}
}
});

array, which has been sent by laravel, becomes backwards when I used it from javascript

I do this in controller
$actions = array('' => 'Select Action Name') + Action::lists('name' , 'id');
and then I send the $actions array to the view.
In the Javascript:
<script>
var actions = {{json_encode($actions) }};
/*for (var key in actions){
console.log(key, actions[key]);
}*/
var options = "";
for(var key in actions){
options = options+ ('<option value="'+key+'">'+actions[key]+"</option>");
}
var select = '<select name="action_id">' + options + "</select>";
console.log(select);
</script>
Print select results in:
<select name="action_id">
<option value="1">Remove White Space</option>
<option value="2">extract map latitude</option>
<option value="3">Extract map longitude</option>
<option value="">Select Action Name</option>
</select>
The array is backwards, as the first option should be the one with Select Action Name but is the last option.
You need to give your array element an index of 0:
$actions = array(0 => 'Select Action Name');
Since you are using string as keys to your array, you are not getting the ordering you would have had you used an integer based array
For your task, an easy solution would be to pass two arrays to your javascript, one containing
$actions = array('Select Action Name')
Send your names in another array
$names = Action::lists('name' , 'id');
Now modify your scripts like this
<script>
var actions = {{json_encode($actions) }};
var names = {{json_encode($names) }};
/*for (var key in actions){
console.log(key, actions[key]);
}*/
var options = "";
options = options+ ('<option value="''">'+actions[0]+"</option>");
for(var key in names){
options = options+ ('<option value="'+key+'">'+names[key]+"</option>");
}
var select = '<select name="action_id">' + options + "</select>";
console.log(select);
</script>

Adding params to the existing URL

Based on Adding a parameter to the URL with JavaScript i tried to make a script that adds parameters to the existing URL but kinda failed and i don't know why...
<script type="javascript">
function insertParam(key, value)
{
key = encodeURI(key); value = encodeURI(value);
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}
</script>
<label>
<select name="id" onchange="window.location='somepage.php?page=inserari-note&selected_value='+this.value">
<option>--Alege user--</option>
<?php
while($runrows = mysql_fetch_assoc($run))
{
$user = $runrows ['user_login'];
echo"<option value=\"$user\">$user</option>";
}
?>
</select>
</label>
<label>
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">
<option>--Alege Elev--</option>
<?php
while($runrows4 = mysql_fetch_assoc($run4))
{
$elev = $runrows4 ['Nume'];
echo"<option value=\"$elev\">$elev</option>";
}
?>
</select>
</label>
So the first select is populating the second select with students and also change the URL into somepage.php?page=inserari-note&selected_value='+this.value which works great but when i click on the options from the second select, nothing happens. In my opinion it should add at the existing URL which is the one i have mentioned before, the values &selected_valueelev="chosen-option" so that the URL should look like let's say somepage.php?page=inserari-note&selected_value=user&selected_valueelev=student. What am i doing wrong?
You should define script tag by the following:
<script type="text/javascript">
...
</script>
And also you have a syntax bug in the following:
// remove + before this.value
<select name="idelev" onchange="insertParam('selected_valueelev',+this.value)">

Categories

Resources