I have two dropdown. I am using Jquery to load second dropdown. without jqyery My php code is working fine. but when I use with jquery second dropdown becomes empty on selection of first drop down.
First Dropdown ( Education )
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
Second Drop Down ( Degree)
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
</select>
Second dropdown is using juery to load on selection of first dropdown Education.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#education').on('change',function(){
var educationID = $(this).val();
if(educationID){
$.ajax({
type:'POST',
url:'education-career.php',
data:'education_id='+educationID,
success:function(html){
$('#degree').html(html);
}
});
}else{
$('#degree').html('<option value="">Select Education first</option>');
}
});});</script>
Try change below line
data:'education_id='+educationID,
to
data:{education_id : educationID},
Try this.(second select tag have to place in first page in order to use $('#degree').html(...))
First Dropdown
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
</select>
Second Dropdown
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
Here in ajax, you are using the
data:'education_id='+educationID,
Which is used to post the data. and the variable name will be here education_id.
And in your second page you are trying to get:
isset($_POST["education"])
this only. So on second page you have to replace education with education_id.
change:
$('#education').on('change',function(){
To:
$('select#education').change(function(){
Related
I'm using a Bootstrap multiselect plugin (https://davidstutz.github.io/bootstrap-multiselect/). The documentation says to call the plugin to the forms select id by the following:
$('#example').multiselect();
However my page is a timetable with multiple cells that are actually generated by a loop statement. Days (Mon-Sun) looped by how many units are in the database. Inside each box, is a separate form which works fine. Now i've wanted to add the multiselect plugin to add a select dropdown into the forms however I can't seem to call the plugin.
I have a $i value that increases on each loop but this will only loop the amount of times a vehicle has been added (5 vehicles, 5 loops etc.). So if I have ms_ this will work, however only for the first column as thats where it stops being unique. I have another value of $thisdate which gives me the date the current cell is on. So technically I thought I should be able to have the following:
<?php
$currentlocation = $i . $thisdate;
?>
<script type="text/javascript">
$('#ms-<?php echo ''.$currentlocation.''; ?>').multiselect();
</script>
This doesn't work. However the below does, but only for the first column.
<?php
$currentlocation = $i;
?>
<script type="text/javascript">
$('#ms-<?php echo ''.$currentlocation.''; ?>').multiselect();
</script>
Or this which works for the top column
<?php
$currentlocation = $thisdate;
?>
<script type="text/javascript">
$('#ms-<?php echo ''.$currentlocation.''; ?>').multiselect();
</script>
$i and $thisdate together would be the unique cell value.
EDIT: This was fixed by using $('.example').multiselect();
This code is working perfectly.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<?php
for($i = 0; $i < 7; $i ++) {
$date=date("Y-m-d");
?>
<div class="">
<strong>Select Language:</strong>
<select id="ms-<?php echo $i?>-<?php echo $date; ?>" multiple="multiple">
<option value="php">PHP</option>
<option value="javascript">JavaScript</option>
<option value="java">Java</option>
<option value="sql">SQL</option>
<option value="jquery">Jquery</option>
<option value=".net">.Net</option>
</select>
</div>
<script>
$(document).ready(function() {
var i = '<?php echo $i; ?>';
var current_date = '<?php echo (string) $date; ?>';
$(`#ms-${i}-${current_date}`).multiselect({
includeSelectAllOption: true,
});
});
</script>
<?php
}
?>
Give all the select elements in each cell from the same class and then call
$('.<common class name of elements>').multiselect();
Sample code:
<select class="example-getting-started" multiple="multiple">
<option value="cheese">Cheese</option>
<option value="tomatoes">Tomatoes</option>
<option value="mozarella">Mozzarella</option>
<option value="mushrooms">Mushrooms</option>
<option value="pepperoni">Pepperoni</option>
<option value="onions">Onions</option>
</select>
<br>
<select class="example-getting-started" multiple="multiple">
<option value="potatto">Potatto</option>
<option value="cucumber">Cucumber</option>
<option value="apple">Apple</option>
<option value="amazone">Amazone</option>
</select>
<script>
$(document).ready(function(){
$('.example-getting-started').multiselect();
});
Working example: https://jsfiddle.net/m1nra8uh/
I had created a simple on change event in Ajax and trying to get data on the change of select tag [HTML] in another select tag.
All's work fine I got the result on test.php
test.php
<div class="row">
<div class="input-field col s12">
<select name="category" id="category">
<option value="" disabled selected>Choose Category</option>
<?php
include "db-connect/db-connect.php";
$qry = mysqli_query($conn, "SELECT * FROM `category`");
while ($row=mysqli_fetch_assoc($qry)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select name="subcategory" id="subcategory">
<option value="">Choose Sub Category</option>
</select>
</div>
</div>
and the ajax code for this html :-
<script type="text/javascript">
$(document).ready(function(){
$('#category').on('change',function(){
var categoryID = $(this).val();
if(categoryID){
$.ajax({
type:'POST',
url:'ajax/category.php',
data:'category_id='+categoryID,
success:function(html){
$('#subcategory').html(html);
//$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#subcategory').html('<option value="">Choose category first</option>');
//$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
When I run it I got the result but after that, I want to implement it into my project template I got nothing.
But, I get data in the inspect element [F12] -> Network
Ajax data file ajax/category.php:-
<?php
//Include the database configuration file xD
include "../db-connect/db-connect.php";
if(!empty($_POST["category_id"])){
//Fetch all data
$query = mysqli_query($conn,"SELECT * FROM `sub_category` WHERE `category_id` = ".$_POST['category_id']."");
//option list
if(mysqli_num_rows($query) > 0){
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_assoc($query)){
echo '<option value="'.$row['sub_category'].'">'.$row['sub_category'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
?>
I have a view that that I have written in HTML and PHP that is like the following:
<select name="category" id="_category" class="_cateogry" onchange="submitTheForm() >
option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
<option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>
Now, I want to get <?php echo $contents->name;?> when the onChange function is called.
I tried to resolve it unsuccessfully in JS, and here is the JS code that I attempted:
function submitTheForm () {
var selectElement = document.getElementById('_category');
var selected = selectedElem.options[selectedElem.selectedIndex];
console.log(selected.text);
}
I want to console.log the selected <?php echo $contents->name;?> when the onchange function is called.
There is a missing " after the javascript function and your code could be modified a little like this - to use event rather than rely upon names or ids
<select name="category" id="_category" class="_cateogry" onchange="submitTheForm(event)" >
<option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
<option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>
function submitTheForm( event ) {
var value=event.target.value;
var text=event.target.options[event.target.options.selectedIndex].text;
console.log('%s -> %s',value,text);
}
<select name="category" id="_category" class="_cateogry" onChange="submitTheForm(this);" >
<option value="">Please select</option>
<option value="1">First</option>
<option value="2">Second</option>
</select>
<script>
function submitTheForm(sel)
{
console.log(sel.options[sel.selectedIndex].text);
}
</script>
You can do as per below
// select box code whch one you have alredy
<select name="category" id="_category" class="_cateogry" onChange="submitTheForm(this);" >
<option value="">Please select</option>
<?php foreach ($categories as $contents ) {?>
<option value="<?php echo $contents->id;?>" selected="selected"><?php echo $contents->name;?></option>
<?php }?>
</select>
//Javascript code to get selected options text value
<script>
function submitTheForm(sel)
{
console.log(sel.options[sel.selectedIndex].text);
}
</script>
Use the function addEventListener to bind the event change.
This is an alternative.
You can get the value and text using the context this.
document.getElementById('_category').addEventListener('change', function() {
console.log(this.value);
console.log(this.options[this.selectedIndex].text);
});
<select name="category" id="_category" class="_cateogry">
<option value="">Please select</option>
<option value="1595">Ele</option>
</select>
You can use jquery easily rather than javascript:
function submitTheForm () {
var optionName = jQuery('#_category option:selected').text();
alert(optionName);
}
I am using a select tag from html to show some list. Now when I select one of the option from select tag, I want to load the form again and by the selected option I am running another query and showing the values of another query in another select tag.
Its working properly after selecting any option I am posting a type from which I am getting another data in another select tag, but when I click suppose option TSgt and the form reloads with the TSgt type data, but the option selected in select tag shows as MSgt which is not the one I selected.
If I don't check if the $type is set in _POST array and just show the select tag without an select value like follow :
<option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
Then, default selected value shows SSgt,I want to show the value in select tag which user has selected.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MCQ Questions</title>
</head>
<body>
<?php
session_start();
$dbh = new PDO('mysql:host=174.75.54;dbname=handbook', 'airman', 'airman');
$type = $_POST['type'];
$question = $_SESSION["question"];
$optionA = $_SESSION["opt1"];
$optionB = $_SESSION["opt2"];
$optionC = $_SESSION["opt3"];
$optionD = $_SESSION["opt4"];
$ans = $_SESSION["ans"];
$chapter = $_SESSION["chapter"];
?>
<form method="post" action="mcq.php" enctype="multipart/form-data">
<p> Enter the question :</p> <input name="question" type="text"> <br><br>
Select question type :
<select name="type" id="type" onchange="this.form.submit()">
<?php if(isset($_POST['type']))
{ ?>
<option value="1" selected=<?=($type==1?"checked":"");?>>SSgt</option>
<option value="2" selected=<?=($type==2?"checked":"");?>>TSgt</option>
<option value="3" selected=<?=($type==3?"checked":"");?>>MSgt</option>
</select>
<?php
}
else
{
?>
<option value="1">SSgt</option>
<option value="2">TSgt</option>
<option value="3">MSgt</option>
</select>
<?php
}
?>
<br><br>
<?php if(isset($optionA))
{ ?>
<p> Enter options :</p>
Enter option A : <input name="opt1" type="text" value = "<?php echo $optionA?>"</input> <br><br>
<?php
}
else{
?>
<p> Enter options :</p>
Enter option A : <input name="opt1" type="text"> <br><br>
<?php
}
?>
Enter option B : <input name="opt2" type="text"> <br><br>
Enter option C : <input name="opt3" type="text"> <br><br>
Enter option D : <input name="opt4" type="text"> <br><br>
Select correct answer :
<select name="ans" id="type">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<br><br>
Select Chapter :
<select name="chapters" id="chapters">
<?php
if(isset($_POST['type']))
{
$stmt = $dbh->prepare("SELECT * FROM chapters where type = :type");
$stmt->bindParam("type", $type);
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results > 0)){
foreach($results as $row):?>
<option value="<?php echo $row['id'];?>"><?php echo $row['title'];?></option>
<?php
endforeach;
}else{?>
<option value="0">No data found</option>
<?php
}
}
else{
$stmt = $dbh->prepare("SELECT * FROM chapters where type = 1");
$stmt->execute();
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if(count($results > 0)){
foreach($results as $row):?>
<option value="<?php echo $row['id'];?>"><?php echo $row['title'];?></option>
<?php
endforeach;
}else{?>
<option value="0">No data found</option>
<?php
}
}
?>
</select> <br><br>
<input type="submit" value = "Submit">
</form>
</body>
</html>
<?php
// escape post variables
$question = $_POST['question'];
$option1 = $_POST['opt1'];
$option2 = $_POST['opt2'];
$option3 = $_POST['opt3'];
$option4 = $_POST['opt4'];
$ans = $_POST['ans'];
$chapter = $_POST['chapters'];
if(!empty($ans) and !empty($question) and !empty($option1) and !empty($option2) and !empty($option3) and !empty($option4) and !empty($type) and !empty($chapter))
{
$stmt = $dbh->prepare("INSERT INTO questions (question,answer_a,answer_b,answer_c,answer_d,answer,type,chapterId) VALUES (?, ?, ?, ?, ?, ?, ?,?)");
$stmt->execute(array($question, $option1, $option2, $option3, $option4, $ans,$type,$chapter));
if ($dbh->lastInsertId())
{
echo 'Question submitted.';
echo 'Upload another question.';
session_destroy();
}
else
{
echo 'Question could not submit.';
}
}
else{
$_SESSION["question"] = $question;
$_SESSION["chapter"] = $chapter;
$_SESSION["ans"] = $ans;
$_SESSION["opt1"] = $option1;
$_SESSION["opt2"] = $option2;
$_SESSION["opt3"] = $option3;
$_SESSION["opt4"] = $option4;
echo 'Fill all fields.';
}
?>
I dont know what is going wrong here. Can anyone help me out please?
Thank you.
selected=checked is wrong. selected is enough.
The syntax is <option value="1" selected>SSgt</option>
Change the code to
<option value="1" <?php echo($type==1?"selected":"");?>>SSgt</option>
<option value="2" <?php echo($type==2?"selected":"");?>>TSgt</option>
<option value="3" <?php echo($type==3?"selected":"");?>>MSgt</option>
i have 4 selectbox ,first one is vehicle selectbox and other three are sub of that vehicle select box ,if i select vehicle select box and click button i want to show a error message ,because one of the sub select is also i want to selected .... any one help ..i am just beginner in jquery/javascript
in simplest words :p ..check one of the sub select box(cars , caravans,buses select box) is selected if i selected main vehicle selectbox...
my code :
<div class="members-wrap-vehicle">
<label>Vehicle</label>
<select name="reservation[vehicle]">
<option value="0">Select</option>
<?php for($i=1;$i<11;$i++) { ?>
<option <?php if($_POST['reservation']['vehicle'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?></option>
<?php } ?>
</select>
</div>
<div class="members-vehicle-list" <?php if($_POST['reservation']['vehicle'] == 0) { echo 'style="display: none;"'; } ?> >
<div class="members-wrap-adult">
<label>Cars</label>
<select name="reservation[cars]">
<option value="0">Select</option>
<?php for($i=1;$i<11;$i++) { ?>
<option <?php if($_POST['reservation']['cars'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?></option>
<?php } ?>
</select>
</div>
<div class="members-wrap-child">
<label>Caravans</label>
<select name="reservation[caravans]">
<option value="0">Select</option>
<?php for($i=1;$i<11;$i++) { ?>
<option <?php if($_POST['reservation']['caravans'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?></option>
<?php } ?>
</select>
</div>
<div class="members-wrap-infant">
<label>Buses</label>
<select name="reservation[buses]">
<option value="0">Select</option>
<?php for($i=1;$i<5;$i++) { ?>
<option <?php if($_POST['reservation']['buses'] == $i) { echo 'selected="selected"'; }?> value="<?php echo $i;?>"><?php echo $i;?> </option>
<?php } ?>
</select>
</div>
Take a look at this SO question: How to check if an option is selected?
Using what is suggested in that link, add an alert with whatever message you want if no option has been selected.
There are new lines of code but have certain changes for better understanding for you and test.
HTML code
<div class="members-wrap-vehicle">
<label>Vehicle</label>
<select name="reservation[vehicle]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="members-vehicle-list">
<div class="members-wrap-adult">
<label>Cars</label>
<select name="reservation[cars]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="members-wrap-child">
<label>Caravans</label>
<select name="reservation[caravans]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="members-wrap-infant">
<label>Buses</label>
<select name="reservation[buses]">
<option value="0">Select</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
jQuery Code
$(function(){
$('.members-wrap-vehicle select').change(function(){
var cars = $('.members-wrap-adult select option:selected').val();
var caravans = $('.members-wrap-child select option:selected').val();
var buses = $('.members-wrap-infant select option:selected').val();
if ( cars == 0 || caravans == 0 || buses == 0 ){
alert('please select any of cars or caravans or buses');
}
});
});
Hope this works for you. THank YOu
This should work but there are some caveats. You have to change your <select> element names to ids (id = 'xxx'). Also, this function assumes that the number of vehicles in the sub menus totals the number in the vehicles menu. Please let me know if you need anything further! Cheers
$('#BUTTON_ID').on('click', function() {
var vehicle = $('#reservation[vehicle]').val();
var cars = $('#reservation[cars]').val();
var caravans = $('#reservation[caravans]').val();
var buses = $('#reservation[buses]').val();
if (vehicle == (cars + caravans + buses)) {
//do something
} else {
//error message
alert('Error has occurred.');
};
});