javascript/jquery updating more than one select boxes options - javascript

I have three select boxes on a page and when someone selects an option from the 1st box, I want to update the options via ajax for the 2nd box. When someone updates the 2nd box then the 3rd box gets new options via ajax.
The problem I'm having seems to be that when the user updates the first box, I check the DB for the options I need and then in php create the new select box and replace the original one. The problem is, even though the code for the select box is the same, and the id's the same the original javascript which was watching for a change on this 2nd box no longer works.
here's the cakephp/html all the cake stuff is doing is creating select boxes.
<table>
<tr>
<td class="threeCol"><?php echo $this->Form->input('industry', array('type'=>'select', 'options'=>$industries, 'empty'=>'Industry', 'id'=>'industry', 'class'=>'formInputSelect'));?></td>
<td class="threeCol" id="cateWrap"><?php echo $this->Form->input('category', array('type'=>'select', 'options'=>$categories, 'empty'=>'Category', 'id'=>'category', 'class'=>'formInputSelect'));?></td>
<td class="threeCol" id="courseWrap"><?php echo $this->Form->input('course', array('type'=>'select', 'options'=>$courses, 'empty'=>'Course', 'id'=>'course', 'class'=>'formInputSelect'));?></td>
</tr>
</table>
And the javascript I use:
<script type="text/javascript">
$(document).ready(function() {
//Update categories dropdown when inustry selected
$("#industry").change(function() {
if( this.value != "Industry" ) {
$.post("<?php echo $this->webroot;?>categories/selectoptionsupdate", {id:this.value})
.done(function (data) {
$("#cateWrap").html(data);
});
}
});
//Update course dropdown when category selected
$("#category").change(function() {
if( this.value != "Category" ) {
$.post("<?php echo $this->webroot;?>courses/selectoptionsupdate", {id:this.value})
.done(function (data) {
$("#courseWrap").html(data);
});
}
});
});
And finally the php which creates the new box.
//UPdate the options for the dropdown on post new job page
function selectoptionsupdate() {
if ($this->request->is('ajax')) {
$this->layout = 'ajax';
$id = $this->request->data['id'];
$options = $this->Course->find('list', array('conditions'=>array('Course.category_id'=>$id)));
$result = '';
$result .= '<select name="data[Job][course]" id="course" class="formInputSelect">';
$result .= '<option value="">Course</option>';
foreach($options as $k=>$v) {
$result .= '<option value="'.$k.'">'.$v.'</option>';
}
$result .= '</select>';
echo 'hey';
}
}
Whats the best way round this problem?

change the lines
$("#industry").change(function() {
$("#category").change(function() {
for:
$(document).on("change", "#industry", function() {
$(document).on("change", "#category", function() {
http://api.jquery.com/on/

Related

function perform on selecting specific dropdown value

i am stuck with strange problem. i have dropdown populate values through db. after populating i append new value. no i want to call function when user select this new value.
if($('#ab option:selected').text() === "Other")
{
$('#txtbox').show();
}
<select class="form-control col-md-7 col-xs-12" id="ab" >
<option select = "selected" value = "" >Select county </option>
<?php
$con=mysqli_connect("localhost","root","","db1");
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "select county from tbl WHERE Code = 'a'";
$res = mysqli_query($con, $sql);
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_object($res)) {
echo "<option value='".$row->id."'>".$row->county."</option>";
}
echo "<option value='".$row->id."'>Other";
}
?>
</select>
i have tried many things but nothing works
Use change event handler and move your code within the callback.
$('#ab').change(function(){
if($(this).text() === "Other"){
$('#txtbox').show();
} else{ // add else part to hide the element
$('#txtbox').hide();
}
});
FYI : You can make your code more simple by using toggle() method.
$('#ab').change(function(){
$('#txtbox').toggle($(this).text() === "Other");
});
You are missing a closing tag for the last option in server-side code.
echo "<option value='".$row->id."'>Other</option>";
// -- here -----------------------------^^^^^^^^^^----
FYI : For running jQuery code correctly after loading all element wrap code within document ready handler.

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 );
});

populate a dropdown from another dropdown database

I am having a trouble with populate a drop-down value from another drop-down with AJAX database. So basically there are Intake and Courses in my form. So, if user choose Intake A, then courses PHP and JQuery will be in Courses option. My problem is now, after i choose Intake A, Courses option doesn't give any value. Can you please help me? Thanks
Here is the AJAX CODE
$(document).ready(function($) {
var list_target_id = 'Courses'; //first select list ID
var list_select_id = 'Iname'; //second select list ID
var initial_target_html = '<option value="">Please select intake...</option>'; //Initial prompt for target select
$('#'+list_target_id).html(initial_target_html); //Give the target select the prompt option
$('#'+list_select_id).change(function(e) {
//Grab the chosen value on first select list change
var selectvalue = $(this).val();
//alert(selectvalue);
//Display 'loading' status in the target select list
$('#'+list_target_id).html('<option value="">Loading...</option>');
if (selectvalue == "") {
//Display initial prompt in target select if blank value selected
$('#'+list_target_id).html(initial_target_html);
} else {
//Make AJAX request, using the selected value as the GET
$.ajax({url: 'CoursesDropdown.php?svalue='+selectvalue,
success: function(output) {
//alert(output);
$('#'+list_target_id).html(output);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status + " "+ thrownError);
}});
}
});
});
Here is the PHP side
<?php
include "connect.php";
$selectvalue = mysqli_real_escape_string($con, $_GET['svalue']);
$checkuser = "Select Coursesname from courses Where CoursesIntake ='$selectvalue'";
$result2 = mysqli_query($con, $checkuser);
echo '<option value="">Please select...</option>';
echo $result2;
while ($row = mysqli_fetch_array($result2)) {
//echo '<option value=" . $row["CoursesName"] . "> . $row["CoursesName"] . "</option>"';
//echo '<option value=' . $row['Coursesname'] . '>' . $row['Coursesname'] . '</option>';
echo '<option value="">Please select...</option>';
echo '<option value="">Please select...</option>';
}
mysqli_close($con);
?>

Ignoring links, checkboxes.. in an editable html field using jquery

Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out

Categories