Php / JQuery / Javascript - Select Parent child dependency - javascript

- - Check out this image.
I want that when someone selects any category then the sub category displays choices based on that particular category that was selected. I'm learning PHP/MySQL but I know the basics of Javascript. Can any teach me in a simple way how it can be done with JavaScript or JQuery?
Categories and sub categories are showing perfectly in the dropdown but are showing all the Sub-Categories and Categories.
<div>
<label>Category</label>
<select name="category">
<option value="0" disabled selected>Select Category</option>
<?php
$cdata = $dbobj->getCategories(0);
while($crow = mysql_fetch_array($cdata)){?>
<option value="<?php echo $crow["categoryid"]; ?>"><?php echo $crow["category_name"]; ?></option>
<?php } ?>
</select>
</div>
<div>
<label>Sub Category</label>
<select name="subcategory">
<option value="0" disabled selected>Select Category</option>
<?php
$scdata = $dbobj->getSubCategories(0);
while($scrow = mysql_fetch_array($scdata)){?>
<option value="<?php echo $scrow["subcategoryid"]; ?>"><?php echo $scrow["subcategory_name"]; ?></option>
<?php } ?>
</select>
</div>
Thanks
Categories & Sub Categories
Men
Clothes
Shoes
Women
Jewelry
Sarees
Shoes
Kids
Toys
Clothes
Books
Language
Fiction
What I want is - whenever someone chooses the category Men, only two subcategories, Clothes and Shoes show up.

Using JQuery :
$(function(){
$(".category option").click(function(){
$(".category").parent().css("display", "none"); // Targetting the parent and hide
$(".subcategory").parent().css("display", "block"); // Targetting the parent and show
});
$(":not(.category option)").click(function(){
// If click on other thing than category option then show
$(".category").parent().css("display", "block");
});
});
EDIT : Added the possibility to return to category

Related

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

Filter Dropdown Based on Another Dropdown Selection

I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>

List item not hidden by jQuery hide function

I have added a leaderboard feature to my website, but unfortunately the minimum score functionality for the leaderboard is not fully working.
So I have created a select element that triggers the setMinScore function which looks through each list element and hides it if its input.dial-list contains a value that is less than the minimum score - basically I want to show only list items that have scores greater than the minimum score.
However, two of my list items that have scores of "8" are still shown in the list when I select any minimum score apart from 80 and 90 (e.g. if I select 70 the list items are shown though they have inputs with values less than 70; but if I select 80 or 90, the items are not shown anymore so the functionality is working only for 80 and 90).
<select name="candList<?php echo $job['jobId']; ?>" onchange="setMinScore(this)">
<option value="0">0</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50" selected>50</option>
<option value="60">60</option>
<option value="70">70</option>
<option value="80">80</option>
<option value="90">90</option>
</select>
<li>
<span class="list-content">
<div class="dial-list-holder">
<input type="text" value="<?php echo $row['score']; ?>" class="dial-list">
</div>
<div class="dial-list-holder">
<input type="text" value="<?php echo $row['matchScore']; ?>" class="dial-list-match">
</div>
<div class="name">
<h5><?php echo $row['name']; ?></h5>
</div>
</span>
</li>
And this is the javascript function:
function setMinScore(selectEl)
{
var minScore = $(selectEl).val();
var candList = "."+$(selectEl).attr('name');
$(candList).find('li').each(function() {
if($(this).find('input.dial-list').val() < minScore) {
$(this).hide();
}
else {
$(this).show();
}
});
}
Thanks guys, your help is highly appreciated!
I would add an id to select element and get the selected value in this was:
var minScore = $("#id option:selected").val();
instead of yours:
var minScore = $(selectEl).val();

Javascript on screen calculations from select / radio box

Currently I am working on a reservations website, I have implemented select boxes and radio buttons to enable the user to select their party size and if they want VIP seating. I have also implemented a price factor based off of these two selections.
I have enabled php to perform the calculations once the submit button is pressed by the user, however I would much prefer for these calculations to be performed automatically on screen as well, using javascript, once the user makes a selection.
Here is the html code for the party size selection:
<select name="party" value="<?php echo $party;?>">
<option value="">Please Select</option>
<option <?php if (isset($party) && $party=="5") echo "selected";?> value="5">1 Person (£5)</option>
<option <?php if (isset($party) && $party=="10") echo "selected";?> value="10">2 People (£10)</option>
<option <?php if (isset($party) && $party=="15") echo "selected";?> value="15">3 People (£15)</option>
<option <?php if (isset($party) && $party=="20") echo "selected";?> value="20">4 People (£20)</option>
<option <?php if (isset($party) && $party=="25") echo "selected";?> value="25">5 People (£25)</option>
<option <?php if (isset($party) && $party=="30") echo "selected";?> value="30">6 People (£30)</option>
<option <?php if (isset($party) && $party=="35") echo "selected";?> value="35">7 People (£35)</option>
<option <?php if (isset($party) && $party=="40") echo "selected";?> value="40">8 People (£40)</option>
<option <?php if (isset($party) && $party=="45") echo "selected";?> value="45">9 People (£45)</option>
<option <?php if (isset($party) && $party=="50") echo "selected";?> value="50">10+ People (£50)</option>
</select>
<span id="party" class="error"><?php echo $partyErr;?></span>
Here is the html code for the VIP selection:
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
Heres the line I wish to display the total price on:
<strong>Total booking cost based on party size & VIP selection: £<span id="price">0</span></strong>
Here is the javascript I have thus far:
$(document).ready(function(){
$(document).on('change', '#party', function(e) {
$('#price').html(parseInt($(this).val()) + parseInt($('input[name="vip"]').val()));
});
$(document).on('click', 'input[name="vip"]', function(e) {
$('#price').html(parseInt($('#party').val()) + parseInt($(this).val()));
});
});
Currently the totals of each price aren't being calculated. When the user clicks a party size, the total cost shows blank and if the user selects to be seated in a VIP area, no change is made either. There is probably a simple error in my coding so if anyone knows how I can fix this to make it function properly, please help.
Thank you.
Your are selecting the span element, not the select. To correct this, you can change the "on" statement as follows:
$("select[name=party]").on("change", function() {
//your handler code
});
The selector you are using is wrong since "party" is the name of the select and not the ID.
$(document).on('change', '#party', function(e) {
Change your select element to
<select id="party" value="<?php echo $party;?>">
and change the id of your span below to something else.
Same thing applies to your VIP input.

show or hide component with a trigger from multiplied combo box

I can't show or hide a component from a multiplied combo box, but I can show or hide it from an original combo box(the first combo box)
what should I do..?
this is function to multiply the combo box
function addEmploy() {}
$('#addEmploy').click(function(){
$('#comboEmploy')
.append('<br />')
.append($('#comboEmploy select').first().clone());
});
this is script to show or hide the component
$("#employ").change(function() {
if($(this).val() == "2"){
$("#comboStudy").show("slow");
}else{
$("#comboStudy").hide("slow");
}
});
This is the combo box
<span id="comboEmploy">
<select name="employ[]" id="employ">
<option value="NULL" selected >Choose one</option>
<?php foreach ($employs as $employ) :?>
<option value="<?php echo $employ->employ_id; ?>">
<?php echo $employ->employ_name; ?></option>
<?php endforeach; ?>
</select>
</span>
Add Employ
This is the component that I want to show/hide
<span id="comboStudy">
<select name="study[]" id="study">
<option selected value=NULL>Choose one</option>
<?php foreach ($studies as $study) :?>
<option value="<?php echo $study->study_id; ?>">
<?php echo $study->study_name; ?></option>
<?php endforeach; ?>
</select>
</span>
Can anyone help me. thanks before.
When you clone the select box, you need to tell jQuery to clone the events along with it:
.clone(true);
As you are appending elements to the DOM after page load you need to use the live() function to attach their events:
$("#employ").live("change", function() {
...
}

Categories

Resources