Get selected value of a 2 dropdown items using jQuery - javascript

I am using the sql to retrieve the values for dropdown. I am only able to get only the 1st dropdownbox item. how do i get the second dropdown value. I am fetching the data from sql.
<label for="category">Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label for="city">city</label>
<select name="city" id="city">
<?php while($row = mysql_fetch_array($query_parent1)): ?>
<option value="<?php echo $row['city']; ?>"><?php echo $row['city']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
and my jquery looks like below
$(document).ready(function(){
$("#parent_cat").change(function(){
var selectedCountry = $("option:selected").val();
alert("You have selected the Country - " + selectedCountry);
});
});
I am able to get the 1st dropdown value how can i also get the second dropdown value
$(document).ready(function(){
$("#city").change(function(){
var selectedCountry1 = $("option:selected").val();
alert("You have selected the city- " + selectedCountry1);
});
});
Can i know where i went wrong

Looks like you are trying to get the value of the selected city in the change event handler.
In the event handler this refers to the changed element, so you can just read the its value
$(document).ready(function () {
$("#city").change(function () {
var selectedCountry1 = this.value; //or $(this).val()
//if you want to get the text of the selected option
var text = $(this).find('option:selected').text(); //find the selected option inside the current select
alert("You have selected the city- " + selectedCountry1);
});
});
$(document).ready(function () {
$("#parent_cat").change(function () {
var selectedCountry = this.value; //or $(this).val()
alert("You have selected the Country - " + selectedCountry);
});
});
The problem with your code is $("option:selected") returns all the option elements which are selected, but when you use the getter .val() it will return only the value of the first selected option element's value, so you will be getting the same value everywhere.

you need to use
$(this).val();
instead of
$("option:selected").val();

Related

getting select box to display selected value in different select box

I have two select boxes in which I want to select a value for one and the second select box should get same value.
Currently I am passing id and want my designation also to pass to ajax. Can I know how this can be implemented via ajax. Any help will be highly appreciated.
<select name="designation" class="form-control" id="desig" >
<option value="">Select a Designation/Role</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl where status =1 and designationtype_id = 1 ");
while ($rows = mysql_fetch_assoc($sql)){
echo "<option value=" . $rows['id'] . ">" . $rows['designation'] . "</option>";
}
?> <select name="dd" id="dd" class="form-control" disabled>
<option value=""></option>
</select>
My AJAX,
<script type="text/javascript">
$(document).ready(function() {
$("#desig").change(function() {
var id = $(this).val();
var dataString1 = 'id=' + id;
var des = $(this).val();
var dataString2 = 'designationname=' + des;
$.ajax({
type: "POST",
url: "escalation_ajax.php",
data: dataString,
cache: false,
success: function(html) {
var data = html.split(",");
$('#rephead').val(data[0]);
}
});
});
});
</script>
escalation_ajax.php
<?php
if ($_POST['id'])
{
if ($_POST['des'])
{
$des_id = $_POST['id'];
$designation = $_POST['des'];
$sql = mysql_query("SELECT designation_id, reporting_head FROM aafmindia_in_sbi.tbl_reporting_head WHERE status=1 and reporting_head_for='$des_id'");
if ($sql === FALSE)
{
trigger_error('Query failed returning error: ' . mysql_error() , E_USER_ERROR);
}
else
{
while ($row = mysql_fetch_array($sql))
{
$id = $row['designation_id'];
$reporting_head = $row['reporting_head'];
echo '<option value="' . $id . '">' . $reporting_head . '</option>' . ',' . '<option value="' . $des_id . '">' . $designation . '</option>';
}
}
}
}
?>
What you could do, is have the second select (the one that needs the same value as the first) in a seperate file that you load via AJAX.
AJAX function:
function selection()
{
var selectValue=$("select#dd option:selected").val();
$.ajax({
type : "POST",
url : "escalation_ajax.php",
data : { id : selectValue },
success: function (html) {
$("#secondSelectorDiv").html(html);
}
})
}
What this does, is that when the selection() function is called, it will post the selected value of the first select to "escalation_ajax.php". It will then load that page into an element (div element in my example) with the id "secondSelectorDiv".
The html for the select with the function (which I will call onchange in this example), can look like this:
<select id="dd" onchange="selection();">
<option value=""></option>
</select>
<div id="secondSelectorDiv"></div>
Now in escalation_ajax.php you can retrieve the post variable and use it to look for the id in question for the second select.
<?php
$id=$_POST['id'];
/*
If you're using the id to fetch something in your database,
which it looks like you're doing, then use the post variable
to fetch your rows and build the select from that.
*/
$sql="SELECT * FROM table_name WHERE id='$id'";
$result_set=mysql_query($sql);
$row=mysql_fetch_array($result_set);
$count=mysql_num_rows(result_set);
$counter=0;
//this is the id you will check for in order to see what's to be selected
$idToCheck=$row['id'];
?>
<select id="dd2">
while($count > $counter)
{
counter++;
echo '<option value=""'; if($idToCheck == $id){ echo 'selected="selected"'; } echo '></option>';
}
?>
If you want the second select to be displayed before the first select has a value, you can simply just call an AJAX function that loads in the second select on page load.
IMPORTANT!: You should really switch to mysqli_* or PDO instead of using the deprecated mysql_*. You should at the very least look into sanitizing your inputs.

having issues while trying to populate second drop down-list dynamically using AJAX

i am trying to populate second dropdown based on the selected option of 1st dropdown but i am unable to do so i dont know what i am doing wrong but something is wrong all my endeavors to achieve my desired results are dashed to the ground cuz its not working kindly help me
so far i have done this....
<select name="ddl_company" size="1" class="form-control" id="ddl_company" onchange="getId(this.value);">
<option value="">Select Company</option>
<?php
//Getting Company name from mysql and displaying it in the 1st dropdown having id ddl_company
$query = mysql_query("select * from company where company_status='Active'order by company_name asc");
while ($r = mysql_fetch_array($query)) {
if ($r['company_id'] == $ddl_company) {
echo "<option selected value=$r[company_id]>$r[company_name]</option>" . "<BR>";
} else {
echo "<option value=$r[company_id]>$r[company_name]</option>";
}
// second drop down list which is going to fetch data from mysql db based on the selected option of 1st dropdown
?>
<select name="ddl_dept" size="1" class="form-control" id="ddl_dept">
<option value=""></option>
</select>
//ajax implementation of 2nd dropdown
<script type="text/javascript">
function getId(val)
{
$.ajax({
type:"POST",
url:"getdata.php",
data:"company_id="+val,
success:function(data)
{
$('#ddl_dept').html(data);
}
});
}
</script>
finally get_data.php file
<?php
include("../newconfig.php");
if (!empty($_POST['company_id'])) {
$company_id = $_POST['company_id'];
$query = "select * from department where department_status='Active'LIMIT 1 AND company_id='$company_id'LIMIT 1";
$sqlquery = mysql_query($query);
while ($r = mysql_fetch_array($sqlquery)) {
# code...
if ($r['company_id'] == $company_id) {
echo "<option selected value=$r[department_id]>$r[department_name]</option>" . "<BR>";
} else {
echo "<option value=$r[department_id]>$r[department_name]</option>";
}
}
}
}
?>
I have done all this yet its not working kindly help me i shall be very thankful. btw thats my output
click this to show the result
Try something like this : jquery
$("select#ddl_dept").on('change',function(){
var selected = $('#ddl_company option:selected').text();
getId(selected );
});

How to get the parent div id in javaScript?

I want to get the parent div id (the div class is called "col-sm-2") when selecting each option in HTML "select" tag in each div. But it always gives only the div id of latest added product at "id" alert. For example if the id of my last added product is "7", it always gives "7" as the alert.
Here is my PHP code for getting the product id.
$jsql_ae7 = mysql_query("select request_list.product_id from request_list where request_list.product_id='{$jrowa2['id']}' and request_list.email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsql_ae7);
Here is my HTML code.
<div class="col-sm-2" id="<?php echo $jfeta7['product_id']; ?>">
<select id="formats_id" name="aformats" onchange="showFormat(this);">
<option value="<?php echo $jrowa2['formats']; ?>"><?php echo $jrowa2['formats']; ?></option>
<?php foreach($formats3 as $v3){ ?>
<?php if($v3 !== $jrowa2['formats']) { ?>
<option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
Here is my javaScript code.
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var id = scriptTags[scriptTags.length - 1].parentNode.id;
alert(id);
};
Try to use each:
$('select').each(function() {
alert($(this).parent().attr('id'));
});
You coild get the id property of the immediate container div using closest() :
$('select').on('change',function() {
alert($(this).closest('div').prop('id'));
});
use this code
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var parent = scriptTags[scriptTags.length - 1].parentNode;
alert(parent.getAttribute('id'));
};
Try this:
Fiddle
$('#formats_id').change(function(){
alert($(this).parent().attr('id'));
});
First we will start with making the selection:
$('select').each(function() {
var selectField = $(this); // this will point to select element
});
There are two ways:
This will take direct parent of select
selectField.parent().attr('id');
This will select first ancestor that is a div with class 'my-class':
selectField.closest('div.my-class').attr('id');
Both work, but differ in deep of search:)

repopulating multiple select form with a drop down form through ajax

i want to repopulate a multiple select form from the database with ajax by just selecting a drop down value.
here is the code for the drop down menu:
<?php
$sql2 = "select _id, title from sub_category order by title;";
$sel2 = mysqli_query($connect,$sql2);
$array2 = array();
while($row2 = mysqli_fetch_assoc($sel2)){
$array2[] = $row2;
}
?>
<div class="span2">
<select name="des_pos" id="des_pos">
<?php
foreach($array2 as $value2){ ?>
<option value ="<?php echo $value2['_id']; ?>" <?php if($value2["title"] == $desired_position){ echo 'selected="selected"';} ?>><?php echo $value2['title']; ?> </option>
<?php
}
?>
</select>
</div>
and here is the code for the multiple select form:
$sql4 = "SELECT _id, score_type from test_category where sub_code='$des_pos_id'";
$sel4 = mysqli_query($connect,$sql4);
$array4 = array();
while($row4 = mysqli_fetch_assoc($sel4)){
$array4[] = $row4;
}
<select name = 'test_tags[]' multiple>
<?php
foreach($array4 as $value4){ ?>
<option value ="<?php echo $value4['_id']; ?>" <?php echo in_array($value4['_id'], $test_tag) ? 'selected="true"' : null; ?>><?php echo $value4['score_type']; ?></option>
<?php
}
?>
</select>
so the the output that i want is, the values of the multiple select form should change depending on the choice on the dropdown menu...
i need a jquery.ajax code for this but i don't know where to begin... i am getting the value through a $_POST.. but i want to do it without going through another page and redirecting.
some helpful stuff:
AJAX Tutorial: W3schools ajax tutorial
then you need to learn about HTML DOM
and then you need to learn about Select DOM Object
mixing those will teach you how to figure out your question.
In the first dropdown #des_pos select event send the ajax post to the php page as follow.
$("#des_pos").select(function(e){
$.ajax({
url:"getdropdata.php",
dataType:"json",
success: function(data){
$.each(data,function(index,value){
$("#multiselect").append("<option value="+value+">"+value+"</option>"));
});
}
})
});

How to give selected value in dropdown list inside while loop

When I select a value in this dropdown, a javascript function will work and it will give a GET value to URL. Now I want to give that selected value as selected in this dropdown list. How to do that?
<?php while ($row = mysql_fetch_array($res)) { echo '<option value='.$row["id"].'>'.$row["name"].'</option>';}?>
Compare GET value with current loop value
<?php while ($row = mysql_fetch_array($res)) {echo '<option '.(($row['id'] == $_GET['id']) ? 'selected' : '').' value='.$row["id"].'>'.$row["name"].'</option>';}?>
Fetch selected value from GET request to compare with each id and put selected attribute in option tag to make it selected by default.
e.g.
<select name="id">
<?php
while ($row = mysql_fetch_array($res)) {
if ($_GET['id']==$row["id"]) {
echo '<option selected="selected" value='.$row["id"].'>'.$row["name"].'</option>';
} else {
echo '<option value='.$row["id"].'>'.$row["name"].'</option>';
}
}
?>
</select>

Categories