onchange dynamic dropdown values using php - javascript

I have written a code for two dropdown boxes. The first dropdown contains a list of main category dynamic values. when i select any one of the value in main category list the second dropdown should appear with corresponding sub category values. How can i do this?
Here is my code:
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
Please Choose Your Category
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
<select class="form-control" name="category_name" onchange="mainInfo(this.value);">
<option value="" selected>Please Select</option>
<option value="Birds">Birds</option>
<option value="Animals">Animals</option>
<option value="Notinlist">Category Not in list</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
Please Choose Your Sub Category
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
<select class="form-control" name="album_name">
<option value="" selected>Please Select</option>
<option value="Birds">Sub Birds</option>
<option value="Animals">Sub Animals</option>
<option value="Notinlist">Category Not in list</option>
</select>
</div>
</div>
</div>
php code to fetch sub category for main category
<?php
$album_category = $_POST['category_name'];
$sql=$conn->prepare("select * from `albums` where album_category=:album_category");
$sql->bindParam(":album_category",$album_category);
$sql->execute();
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
echo $row['album_sub_category'];
}
?>

Change your code to something like that :
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
Please Choose Your Category
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
<select class="form-control" name="category_name" id="category_name" onchange="mainInfo(this.value);">
<option value="" selected>Please Select</option>
<option value="Birds">Birds</option>
<option value="Animals">Animals</option>
<option value="Notinlist">Category Not in list</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
Please Choose Your Sub Category
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-4 col-md-offset-1">
<div class="form-group">
<select class="form-control" name="album_name" id="album_name">
<option value="">Please Select</option>
</select>
</div>
</div>
</div>
Add this ajax function :
<script>
function mainInfo(str)
{
var n;
if (str=="0")
{
document.getElementById("album_name").innerHTML="<option>--Select --</option>";
return;
}
if (window.XMLHttpRequest)
{
n=new XMLHttpRequest();
}
else
{
n=new ActiveXObject("Microsoft.XMLHTTP");
}
n.onreadystatechange=function()
{
if (n.readyState==4 && n.status==200)
{
document.getElementById("album_name").innerHTML=n.responseText;
}
}
n.open("GET","sub_category.php&category_name="+str,true);
n.send();
}
</script>
And on the php page which is sub_category.php
<?php
$album_category = $_POST['category_name'];
$sql=$conn->prepare("select * from `albums` where album_category=album_category");
$sql->bindParam(":album_category",$album_category);
$sql->execute();?>
<option value="">--Select State--</option>
<?php
while ($row = $sql->fetch(PDO::FETCH_ASSOC))
{
?>
<option value="<?php echo $row['album_sub_category'];?>"><?php echo $row['album_sub_category'];?></option>
<?php
}
?>

Unless the items in the list are small enough preload load into the page, you're going to have to make an http endpoint for fetching the raw data using AJAX and then draw it on the client with JavaScript. jQuery would make light work of it.
The other option would involve reloading the page for each change... Yuck...
You're client code could be something like this with jQuery:
$.ajax({url: '/categories.json', data: {cat:'category name'}}).done(function(cats){
$.each(cats, function(){
$('#Target').append($('<option>', {value:this}).text(this));
})
}).fail(function(){
// Handle error
});
Since no method id specified it will default to GET and the data object will be converted to GET variables which you can use for the DB query to get the applicable sub categories and return them in JSON with proper JSON headers.

Related

On change of a selected value show an input

I am trying to choose yes value in this dropdown, so I can show another input field to add discount.
I am trying but nothing is showing. Can you please help me?
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onclick="myFunction()" required>
<option value="" disabled selected >--Choose--</option>
<option value="yes" >Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
<script>
function myFunction() {
if (document.getElementById('is_offer').value = 'yes') {
document.getElementById('offer').innerText = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
}
</script>
function myFunction() {
if (document.getElementById('is_offer').value = 'yes') {
document.getElementById('offer').innerText = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
}
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onclick="myFunction()" required>
<option value="" disabled selected>--Choose--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
Your condition statement has issues. Use document.getElementById('is_offer').value === 'yes' (triple-equals)
function myFunction()
{
if (document.getElementById('is_offer').value === 'yes')
{
document.getElementById('offer').innerHTML = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div></div></div>';
}
}
and change onclick with onChange.
Use .innerHTML to set the div not innerText. innerText assumes all your html data is text and adds it like a text. ,For the yes condition, = is used for assignment but we have to compare so == is used. And call the function on onchange event not on click of the select tag
function myFunction()
{
if( document.getElementById('is_offer').value=='yes')
{
document.getElementById('offer').innerHTML='<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
else
document.getElementById('offer').innerHTML=''
}
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onChange="myFunction()" required>
<option value="" disabled selected >--Choose--</option>
<option value="yes" >Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
You had 3 issues should be changed.
If you want to listen the change of input, you shoule use onchange instead of onclick.
In if condition you use assigning variables instead of comparison (use == or ===).
It seems you would like to change HTML content. So you should use innerHTML instead of innerText.
After fixing all of them we have code like this:
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onchange="myFunction()" required>
<option value="" disabled selected>--Choose--</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
<script>
function myFunction() {
if (document.getElementById('is_offer').value === 'yes') {
document.getElementById('offer').innerHTML = '<div class="form-group m-form__group row"> <label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label> <div class="col-xl-9 col-lg-9"> <div id="asd"></div> </div> </div>';
}
}
</script>
Prefer to use the onchange event on the select tag. Also, you should use === to compare the value with yes or no, not just = whish is an assignment.
By using a template and cloning it, you don't have to mix your JavaScript with HTML code, you just have to fetch the template, clone it and append it to your div.
Do not query the document to find your select in your handler, you have access to it via the event.target object, which you get access to as argument to your handler.
Also, don't forget to erase the discount when you select no.
function onSelect(event) {
const offer = document.getElementById('offer');
offer.innerHTML = '';
if (event.target.value === 'yes') {
const tpl = document.getElementById('discount-tpl');
const clone = document.importNode(tpl.content, true);
offer.appendChild(clone);
}
}
<div class="form-group m-form__group row">
<select class="form-control m-input" name="is_offer" id="is_offer" onchange="onSelect(event)" required>
<option value="" disabled selected >--Choose--</option>
<option value="yes" >Yes</option>
<option value="no">No</option>
</select>
</div>
<div id="offer"></div>
<template id="discount-tpl">
<div class="form-group m-form__group row">
<label class="col-xl-3 col-lg-3 col-form-label">* Discount::</label>
<div class="col-xl-9 col-lg-9">
<div id="asd"></div>
</div>
</div>
</template>

In the multiple select dropdowns a selected dropdown value (option) need to hide in remaining dropdowns

I'm creating a web form with 3 select boxes with multiple questions. If I select 1st Question from 1st select drop-down that question will not appear in the 2nd select drop-down. It will repeat same as 3rd select drop-down.
Note: The main purpose is if user select any questions from select drop-down that question will not appear in another select drop-down.
Demo Code:
.margin-top-10 { margin-top: 1.0em; }
.margin-top-20 { margin-top: 2.0em; }
.margin-top-30 { margin-top: 3.0em; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<div class="row">
<div class="col-md-8 col-md-offset-2 col-xs-12">
<div class="panel panel-default">
<div class="panel-body">
<div class="row margin-top-20">
<div class="form-group">
<label class="control-label col-sm-12 col-xs-12" for="">Question 1</label>
<div class="col-sm-11 col-xs-12">
<select class="form-control" id="sel1">
<option selected="">Choose your question</option>
<option>Select question 1</option>
<option>Select question 2</option>
<option>Select question 3</option>
<option>Select question 4</option>
</select>
</div>
<div class="col-sm-11 col-xs-12 margin-top-10">
<input type="text" class="form-control" placeholder="Type your answer">
</div>
</div>
</div>
<div class="row margin-top-20">
<div class="form-group">
<label class="control-label col-sm-12 col-xs-12" for="">Question 2</label>
<div class="col-sm-11 col-xs-12">
<select class="form-control" id="sel1">
<option selected="">Choose your question</option>
<option>Select question 1</option>
<option>Select question 2</option>
<option>Select question 3</option>
<option>Select question 4</option>
</select>
</div>
<div class="col-sm-11 col-xs-12 margin-top-10">
<input type="text" class="form-control" placeholder="Type your answer">
</div>
</div>
</div>
<div class="row margin-top-20">
<div class="form-group">
<label class="control-label col-sm-12 col-xs-12" for="">Question 3</label>
<div class="col-sm-11 col-xs-12">
<select class="form-control" id="sel1">
<option selected="">Choose your question</option>
<option>Select question 1</option>
<option>Select question 2</option>
<option>Select question 3</option>
<option>Select question 4</option>
</select>
</div>
<div class="col-sm-11 col-xs-12 margin-top-10">
<input type="text" class="form-control" placeholder="Type your answer">
</div>
</div>
</div>
<div class="row margin-top-20">
<div class="col-xs-6 text-right">
<span class="glyphicon glyphicon-arrow-left" aria-hidden="true"></span> Back
</div>
<div class="col-xs-6"><a class="btn btn-primary" role="button" href="Registration-Complete.html" name="btnGlassContactInfo">Register <span class="glyphicon glyphicon-ok"></span></a></div>
</div>
</div>
</div>
</div>
</div>
The first thing you might want to do if change the select elements in your code so that each of them has a unique ID. They are all sel1 at the moment :)
Then you need to bind the onchange event to the select options that will remove the option being selected. Here is an example:
$('select').on('change', function() {
var elem = this;
var option = this.value;
$('.form-control option').each(function() {
if ($(this).html() === option && $(elem).attr('id') !== $(this).parent().attr('id')) {
$(this).remove();
}
});
})
You would probably want to disable the user from using the same selection element, or store the removed options and add them back should the user change his / her mind.
I have disabled them in my example, which you can view here.
https://jsfiddle.net/martiensk/jwfeqrx0/

JS, PHP, MySQL Code errors for mathematical operation

I wrote a small script. I have a form in my page. It takes data from MySQL Database. After that, When user select some options from select panels, I need JS will do math summation and write total in a div/input field.
I wrote the page and got errors. I changed a lot of things after searched similar problems on net and here.
I used parseInt($.. ,10) , document.getElementById("testID").innerHTML , document.getElementById("testID").value , document.getElementById("testID").val() and etc...
So, I'm asking your help to correct my errors.
Thanks
Here is the Jsfiddle page link;
jsfiddle page
My Code (this is the latest version that I have) ;
JS:
<script type="text/javascript">
function updatesum() {
var T = 0;
var d = document;
var A = d.getElementById("araclar").val();
var M = d.getElementById("varis").val();
var K = d.getElementById("kisiler").val();
var B = d.getElementById("bavullar").val();
var C = d.getElementById("cocuklar").val();
var Ck = d.getElementById("cocukKoltuk").val();
T = parseInt('A' ,10) * parseInt('M' ,10);
document.getElementById("toplamm").innerHTML = T;
}
</script>
PHP:
<form action="subscribe.php" id="subscribe" method="post" name="subscribe">
<div class="row">
<div class="col-xs-12 col-sm-10">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3">
<label>NAME<input class="form-control" name="name" placeholder="NAME" type="text"></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>SURNAME<input class="form-control" name="surname" placeholder="SURNAME" type="text"></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>TELEPHONE<input class="form-control" name="date" placeholder="TELEPHONE" type="tel"></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>EMAIL<input class="form-control" name="email" placeholder="EMAIL" type="email"></label>
</div>
<hr />
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3">
<label>FROM:<select class="form-control" name="kalkis" id="kalkis" onchange="bolegler(this.value);sifirla();">
<option value="">Please Select</option>
<?php
$boleg= mysql_query("SELECT * FROM areas WHERE ust LIKE 0");
while($bolges = mysql_fetch_array($boleg)) {
echo '<option value="'.$bolges['id'].'">'.$bolges['isim'].'</option>';
}
?>
</select></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3" id="txtHint">
<!-- This Code will change after #kalkis change by JS start-->
<label>TO:<select name="varis" class="form-control">
<option value="">Please Select</option>
</select></label>
<!-- This Code will change after #kalkis change by JS end-->
</div>
<div id="datetimepicker" class="col-xs-12 col-sm-6 col-md-3 input-append date">
<label>REZERVATION DATE
<input type="text" class="col-xs-8 form-control" name="rezervasyon" style="float:left;"></input>
<span class="add-on col-xs-2" style="float: left; margin: -39px 0; font-size: 23px;"><i class="fa fa-calendar"></i>
</span>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>CAR:
<select name="car" id="car" class="form-control" onchange="updatesum();">
<option value="0">Please Select</option>
<?php
$ara= mysql_query("SELECT * FROM cars");
while($arac = mysql_fetch_array($ara)) {
echo '<option value="'.$arac['price'].'" class="'.$arac['id'].'">'.$arac['isim'].'</option>';
}
?>
</select>
</label>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3">
<label>PERSON QTY
<select name="persons" id="persons" class="form-control" onchange="updatesum();">
<option value="0">Please Select</option>
<?php
$kis= mysql_query("SELECT * FROM person");
while($person = mysql_fetch_array($kis)) {
echo '<option value="'.$person['price'].'" class="'.$person['qty'].'">'.$person['qty'].'</option>';
}
?>
</select>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>bag QTY
<select name="bags" id="bags" class="form-control" onchange="updatesum();">
<option value="0">Please Select</option>
<?php
$bav= mysql_query("SELECT * FROM bag");
while($bag = mysql_fetch_array($bav)) {
echo '<option value="'.$bag['price'].'" class="'.$bag['qty'].'">'.$bag['qty'].'</option>';
}
?>
</select>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>KID QTY
<select name="cocuklar" id="cocuklar" class="form-control" onchange="updatesum();cocukla();">
<option value="0">Please Select</option>
<?php
$coc= mysql_query("SELECT * FROM kidqty");
while($kid = mysql_fetch_array($coc)) {
echo '<option value="'.$kid['price'].'" class="'.$kid['qty'].'">'.$kid['qty'].'</option>';
}
?>
</select>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3" id="koltukalani">
<label>KID CHAIR
<select name='kidchair' id='kidchair' class='form-control' onchange='updatesum();'>
<option value='0'>Please Select</option>
<option value='0'>Do no Want</option>
<option value='<?php echo $genel['kidchair']; ?>'>Need a Kid Chair</option>
</select>
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-2">
<button class="form-control submit-button" id="submit" type="submit">SUBMIT</button>
<br />
TOTAL AMOUNT:
<div id="toplamm" class="toplamm">0</div>
</div>
</div>
</form>
And the Other Codes:
function sifirla:
<script type="text/javascript">
function sifirla() {
document.getElementById("toplamm").innerHTML = "0";
}
</script>
function cocukla:
<script type="text/javascript">
function cocukla() {
var cocuk = parseInt(document.getElementById("cocuklar").value);
if (cocuk < "1") {
document.getElementById("kidchair").innerHTML = " ";
}
else {
document.getElementById("kidchair").innerHTML = "<label>KID CHAIR <select name='kidchair' id='kidchair' class='form-control' onchange='updatesum();'> <option value='0'>Please Select</option> <option value='0'>Do not Want</option> <option value='<?php echo $genel['kidchair']; ?>'>Need a Kid Chair</option> </select> </label>"; }
}
</script>
In this line T = parseInt('A' ,10) * parseInt('M' ,10); you are using trying to get the ASCII code of char A and char M. Whereas you should be parsing variables A and M to integer.
You will need to modify your function as below to get the correct numbers-
T = parseInt(A ,10) * parseInt(M ,10);
Updated as per comment -
Use value instead of val() for getting the values form html id tags.
T = parseInt(A ,10) * parseInt(M ,10) + parseInt(K ,10) + parseInt(B ,10) + parseInt(C ,10) + parseInt(Ck ,10);

The selected option must shown after the function of onchange

I have 2 dropdowns, just like the title.. The selected option must shown after the function of onchange meaning when it automatically refreshes the selected option must stay and show the selected options . The problem is when I select an option from the 2nd dropdown which has onchange function it refreshes and it gets back to the default option.
Here's the code
<div id="page-wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-10">
<h1 class="page-header">
BRANCHES
</h1>
</div>
<div class="col-lg-2">
<a class="btn btn-default bad-marg" href="index.php?act=abr" role="button">Add Branch</a>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div id="form">
<form action="func_vbrs.php" method="POST" class="form-horizontal">
<fieldset>
<div class="row">
<div class="col-lg-4">
<div class="form-group">
<label for="bl" class="control-label col-xs-3"><p class="left">Branch</p></label>
<div class="col-xs-8">
<div class="req">
<select name="bid" class='form-control'>
<option value='' default style='color:gray;'>Branch</option>
<?php
include_once "config.php";
$sql="select branchID, b, bl from branch where b!='HOK'";
$stmt=$con->prepare($sql);
$stmt->execute();
$stmt->bind_result($bid, $b, $bl);
$stmt->store_result();
while($stmt->fetch()){
echo '<option value="'.$bid.'">'.$b.'-'.$bl.'</option>';
}
?>
</select>
</div>
</div>
<div class="col-xs-1">
</div>
</div>
</div>
<div class="col-lg-4">
<div class="form-group">
<label for="cat" class="control-label col-xs-3"><p class="left">Category</p></label>
<div class="col-xs-8">
<div class="req">
<select name="brcat" class="form-control" onchange='this.form.submit()'>
<option value="" default style="color:gray;">Category</option>
<option value="Stock">Stock</option>
<option value="Sales">Sales</option>
<option value="Stock Transfer">Stock Transfer</option>
</select>
</div>
</div>
<div class="col-xs-1">
</div>
</div>
</div>
<div class="col-lg-4">
</div>
</div>
<noscript><input type="submit" value="Submit"></noscript>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
As you can see the 2nd drop down is category, If a user already selects an option after the automatic refresh or onchange function, it gets back to default option.
You need to cross check against post on page load, and add a selected tag appropriately. There are more elegant solutions with less bulky code if you use a loop to create your options, but that's another question.
<?PHP
if (!empty($_POST['brcat'])){
$selected_item = $_POST['brcat'];
} else { $selected_item = Null; }
function selcheck($item1, $item2){
if ($item1 == $item2){
$ret = " selected=\"selected\" ";
} else {
$ret = "";
}
return($ret);
}
?>
<select name="brcat" class="form-control" onchange='this.form.submit()'>
<option value="" default style="color:gray;">Category</option>
<?PHP
$sel = selcheck("Stock",$selected_item);
?>
<option value="Stock"<?=$sel?>>Stock</option>
<?PHP
$sel = selcheck("Sales",$selected_item);
?>
<option value="Sales"<?=$sel?>>Sales</option>
<?PHP
$sel = selcheck("Stock Transfer",$selected_item);
?>
<option value="Stock Transfer"<?=$sel?>>Stock Transfer</option>

Ajax return not show on page source Codeigniter

I have a problem with AJAX return values. The returned data is not showing on my page's source code.
This is my controller code in Codeigniter:
public function get_rooms(){
$rooms_selected = $this->input->get('q', TRUE);
$this->load->model('roomreservation_model');
$room_numbers = $this->roomreservation_model->numberofroom($rooms_selected);
echo '<select class="form-control" name="room_number" id="room_number">';
foreach ($room_numbers as $value) {
echo '<option value="'.$value->room_number.'">'.$value->room_number.'</option>';
}
echo '</select>';
}
HTML code
<div class="col-lg-12">
<h2 class="sub-header">Room Detail</h2>
<div class="col-lg-6 col-xs-12 form-label">
<label for="Room Type">Room Type</label>
<select class="form-control" name="roomtype" id="roomtype" onchange="showUser(this.value)">
<option value="">Select a Room Type</option>
<option value="King Suit">King Suit</option>
<option value="Suit One">Suit One</option>
<option value="Suit Two">Suit Two</option>
<option value="Suit Three">Suit Three</option>
</select>
</div>
<div class="col-lg-6 col-xs-12 form-label">
<label for="Room Type">Room Avaiable</label>
<div id="txtHint">
<b style="color:#6E6E6E">Select Room type then show Avaiable Rooms</b>
</div>
</div>
</div>
When I select a room type (from my select dropdown), an AJAX request is made which returns with all rooms available. Its works fin, but the problem is when I check the browser's source code. It does not show the source of the Available Rooms.

Categories

Resources