Board index   FAQ   Search  
Register  Login
Board index php forum :: php coding PHP coding => General

Repopulate selectbox depending on choice made in other.

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Repopulate selectbox depending on choice made in other.

Postby hinkeltje » Tue Sep 11, 2012 5:29 am

I am trying to find out how to repopulate a selectbox depending on the value chosen in the previous selectbox.

To be specific:
I have a table customer (customerid, customername) and a table contact (contactid, customerid, contactname).
Depending on the customer that is chosen in the first selectbox I want to repopulate the second selectbox with only the appropriate contact persons belonging to the specific customer.

But since PHP is a server sided language, I probably can't fix this with PHP.

I hope there is someone who can help me with this.
User avatar
hinkeltje
New php-forum User
New php-forum User
 
Posts: 15
Joined: Thu Aug 25, 2011 10:51 pm

Re: Repopulate selectbox depending on choice made in other.

Postby kyle04 » Wed Sep 12, 2012 6:32 am

You will need an ajax type function, triggered by the onchange event in the first select list.
The function should call a php script which can sort the data needed from the select list value, then return the values to the second select list :


<script type="text/javascript">
function getHTTPObject() { // set up the remote call
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}

function call_your_script() { //call your php script to get second select box values
http = getHTTPObject();
var sel = document.getElementById("selectname"); // id of 1st select list
var sel_value = sel.options[sel.selectedIndex].value; // value of selected value
var arr_url = "myscript.php?select_value="+sel_value; // php script address based on select value

http.open("GET", arr_url, false);
http.send(null);
var results = http.responseText;

// second list generated here, you can display it on the page using javascript

}
</script>

So
<select id="selectname" onchange="call_your_script();"> // will trigger above script to call the php script

<?php

$select_value = $_REQUEST['select_value'];

...do some database stuff here to generate a second select list of contacts based on the $select_value

use echo to generate the second list


?>
kyle04
New php-forum User
New php-forum User
 
Posts: 94
Joined: Sat Jul 07, 2012 1:36 pm

Re: Repopulate selectbox depending on choice made in other.

Postby hinkeltje » Thu Sep 13, 2012 3:34 am

Hi Kyle,

Thank you for your help. Thanks to your example I am now almost there.

Just one question left:

var results containes the correct data.
But how do I get this data on the right place in my HTML / PHP document?

Hope you are willing to help me one more time.
User avatar
hinkeltje
New php-forum User
New php-forum User
 
Posts: 15
Joined: Thu Aug 25, 2011 10:51 pm

Re: Repopulate selectbox depending on choice made in other.

Postby kyle04 » Fri Sep 14, 2012 6:01 am

You have do display the data generated by the php script, something like :


...............

http.open("GET", arr_url, false);
http.send(null);
var results = http.responseText; // the php generated select list

document.getElementById('my_select_box_container_div').innerHTML=results;
document.getElementById('my_select_box_container_div').style.display="block";
</script>

You second select list box will be in an initially hidden div :

<div id="my_select_box_container_div" style="display:none;"></div>

When the ajax call is made the results (ie the second generated select list) should appear on the page in the div container. The above javascript fills the div container with the select list (the innerHTML part), then switches the display property to "block". The second part is optional, the initial div display can be set to block, it depends how you want the results to appear on the page. Take care with correct syntax as javascript gives no error warnings if it dosen't work.
The beauty of this type of function is that the user dosen't leave the page being viewed - the work is done behind the scenes and the specific data is displayed as if by magic !
Good luck !

AndyP
kyle04
New php-forum User
New php-forum User
 
Posts: 94
Joined: Sat Jul 07, 2012 1:36 pm

Re: Repopulate selectbox depending on choice made in other.

Postby prabatgp » Wed Feb 20, 2013 5:41 am

<script type="text/javascript" src="<?php echo public_path('../../scripts/jquery/jquery.validate.js');?>"></script>

<?php echo stylesheet_tag('performance/performanceReviewSuccess'); ?>


<div id="content">
<div id="performanceReviewcontentContainer">
<?php echo isset($templateMessage) ? templateMessage($templateMessage) : ''; ?>
<div class="outerbox">
<div id="formHeading" class="mainHeading"><h2><?php echo __("Performance Review")?></h2></div>

<form action="#" id="frmSave" class="content_inner" method="post">

<?php echo $form['_csrf_token']; ?>

<input type="hidden" name="id" id="id" value="<?php echo $performanceReview->getId()?>"/>
<input type="hidden" name="saveMode" id="saveMode" value="" />

<div id="formWrapper">
<label class="detailHearder"><?php echo __("Employee")?></label>
<label class="detail"><?php echo $performanceReview->getEmployee()->getFirstName()?> <?php echo $performanceReview->getEmployee()->getLastName()?></label>
<br class="clear"/>
<label class="detailHearder"><?php echo __("Job Title")?></label>
<label class="detail"><?php echo htmlspecialchars_decode($performanceReview->getJobTitle()->getJobTitleName())?> </label>
<br class="clear"/>
<label class="detailHearder"><?php echo __("Reviewer")?></label>
<label class="detail"><?php echo $performanceReview->getReviewer()->getFirstName()?> <?php echo $performanceReview->getReviewer()->getLastName()?></label>
<br class="clear"/>
<label class="detailHearder"><?php echo __("Review Period")?></label>
<label class="detail"><?php echo set_datepicker_date_format($performanceReview->getPeriodFrom())?>-<?php echo set_datepicker_date_format($performanceReview->getPeriodTo())?></label>
<br class="clear"/>
<label class="detailHearder"><?php echo __("Status")?></label>
<label class="detail"><?php echo __($performanceReview->getTextStatus())?> </label>
<br class="clear"/>
<?php if( count($performanceReview->getPerformanceReviewComment()) > 0){?>
<label class="detailHearder"><?php echo __("Notes")?></label>
<label class="detail">

<table width="600px">
<th>
<tr>
<td width="100px"><b><?php echo __("Date")?></b></td>
<td width="150px"><b><?php echo __("Employee")?></b></td>
<td width="350px"><b><?php echo __("Comment")?></b></td>
</tr>
</th>
<?php foreach( $performanceReview->getPerformanceReviewComment() as $comment){?>
<tr>
<td ><?php echo set_datepicker_date_format($comment->getCreateDate())?></td>
<td ><?php echo ($comment->getEmployee()->getFullName() != '')? $comment->getEmployee()->getFullName():__('Admin')?></td>
<td ><?php echo $comment->getComment()?></td>
</tr>

<?php }?>
</table>

</label>
<br class="clear"/>
<?php }?>

<div id="tableWrapper">
<input type="hidden" name="validRate" id="validRate" value="1" />
<div id="performanceError" class="hide">
<div id='messageBalloon_failure' class='messageBalloon_failure' ><ul></ul></div>
</div>
<table cellpadding="0" cellspacing="0" class="data-table prData" align="left" width="100%">
<thead>
<tr>

<td width="10px" scope="col">

</td>
<td scope="col" width="100">
<?php echo __("Goal")?>
</td>
<td width="490px" scope="col">
<?php echo __("Key Performance Indicator")?>
</td>

<td scope="col" width="100">
<?php echo __("Min Rate")?>
</td>
<td scope="col" width="100">
<?php echo __("Max Rate")?>
</td>
<td scope="col" width="100">
<?php echo __("weightage")?>
</td>
<td scope="col" width="100">
<?php echo __("Rating")?>
</td>
<td scope="col" width="100">
<?php echo __("Points")?>
</td>
<td scope="col" width="200">
<?php echo __("Reviewer Comments")?>
</td>
</tr>
</thead>
<tbody>
<?php foreach( $kpiList as $kpi){?>
<tr class="odd">
<td class="">

</td>
<td >
<?php echo ($kpi->getId()!= '')?$kpi->getId():'-'?>
</td>
<td >
<?php echo $kpi->getKpi()?>
</td>

<td >
<?php echo ($kpi->getMinRate()!= '')?$kpi->getMinRate():'-'?>
</td>
<td >
<?php echo ($kpi->getMaxRate() !='')?$kpi->getMaxRate():'-'?>
</td>

<td>
<input type="hidden" name="max<?php echo $kpi->getId()?>" id="max<?php echo $kpi->getId()?>" value="<?php echo $kpi->getMaxRate()?>" />
<input type="hidden" name="min<?php echo $kpi->getId()?>" id="min<?php echo $kpi->getId()?>" value="<?php echo $kpi->getMinRate()?>" />
<input id="txtWeight<?php echo $kpi->getId()?>" name="txtWeight[<?php echo $kpi->getId()?>]" type="text" class="smallInput" value="<?php echo trim($kpi->getWeight())?>" maxscale="<?php echo $kpi->getMaxRate()?>" minscale="<?php echo $kpi->getMinRate()?>" valiadate="1" />
</td>

<td>
<input type="hidden" name="max<?php echo $kpi->getId()?>" id="max<?php echo $kpi->getId()?>" value="<?php echo $kpi->getMaxRate()?>" />
<input type="hidden" name="min<?php echo $kpi->getId()?>" id="min<?php echo $kpi->getId()?>" value="<?php echo $kpi->getMinRate()?>" />
<input id="txtRate<?php echo $kpi->getId()?>" name="txtRate[<?php echo $kpi->getId()?>]" type="text" class="smallInput" value="<?php echo trim($kpi->getRate())?>" maxscale="<?php echo $kpi->getMaxRate()?>" minscale="<?php echo $kpi->getMinRate()?>" valiadate="1" />
</td>

<td>
<input type="hidden" name="txtgetRate" id="txtgetRate" value="<?php echo trim($kpi->getRate())?>" />
<input type="hidden" name="txtgetWeight" id="txtgetWeight" value="<?php echo trim($kpi->getWeight())?>" />
<input id="txtPoint" name="txtPoint" type="text" class="smallInput" value="<?php echo $_GET['point'];?>" valiadate="1" />
</td>


<td class="">
<textarea id='txtComments' class="reviwerComment" name='txtComments[<?php echo $kpi->getId()?>]'
rows="4" cols="76" ><?php echo htmlspecialchars_decode(trim($kpi->getComment()))?></textarea>
</td>

</tr>

<?php } ?>

</tbody>

</table>
</div>
<?php if(($isHrAdmin || $isReviwer) && ($performanceReview->getState() != PerformanceReview::PERFORMANCE_REVIEW_STATUS_APPROVED)){?>
<label class="detailHearder"><?php echo __("Note")?></label>
<textarea id='txtMainComment' name='txtMainComment' class="formTextArea"
rows="4" cols="60" ></textarea>
<br class="clear"/>
<?php }?>
</div>
</form>
<div id="buttonWrapper" class="formbuttons">&nbsp;
<?php if(($isReviwer && ($performanceReview->getState() <= PerformanceReview::PERFORMANCE_REVIEW_STATUS_BEING_REVIWED || $performanceReview->getState()==PerformanceReview::PERFORMANCE_REVIEW_STATUS_REJECTED)) || ( $isHrAdmin && $performanceReview->getState() != PerformanceReview::PERFORMANCE_REVIEW_STATUS_APPROVED)){?>
<input type="button" class="savebutton" id="saveBtn"
value="<?php echo __("Edit")?>" />
<?php }?>

<?php if( $isReviwer && ( $performanceReview->getState() == PerformanceReview::PERFORMANCE_REVIEW_STATUS_SCHDULED || $performanceReview->getState() == PerformanceReview::PERFORMANCE_REVIEW_STATUS_BEING_REVIWED || $performanceReview->getState() == PerformanceReview::PERFORMANCE_REVIEW_STATUS_REJECTED)){?>
<input type="button" class="savebutton" id="submitBtn"
value="<?php echo __("Submit")?>" />
<?php } ?>

<?php if( $isHrAdmin && $performanceReview->getState() == PerformanceReview::PERFORMANCE_REVIEW_STATUS_SUBMITTED){?>
<input type="button" class="savebutton" id="rejectBtn"
value="<?php echo __("Reject")?>" />
<?php } ?>

<?php if( $isHrAdmin && ( $performanceReview->getState() == PerformanceReview::PERFORMANCE_REVIEW_STATUS_SUBMITTED )){?>
<input type="button" class="savebutton" id="approveBtn"
value="<?php echo __("Approve")?>" />
<?php }?>

<input type="button" class="savebutton" id="backBtn" value="<?php echo __("Back");?>" />

</div>



</div>
</div>


</div>
<script type="text/javascript">




//points value
var point;
function getPoint(){
getWeight="<?php echo trim($kpi->getRate())?>";
getRate="<?php echo trim($kpi->getWeight())?>";
point=((getWeight/100)*getRate);
document.calculator.total.value=point;
}


//Check autosave
function autosave()
{
var t = setTimeout("autosave()", 20000);

var title = $("#txt_title").val();
var content = $("#txt_content").val();

if (title.length > 0 || content.length > 0)
{
$.ajax(
{
type: "POST",
url: "autosave.php",
data: "article_id=" + <?php echo $article_id ?>
+ "&title=" + title + "&content=" + content,
cache: false,
success: function(message)
{
$("#timestamp").empty().append(message);
}
});
}
}

//Check submit
function checkSubmit(){
var valid = true ;
var msg = '';
$("input.smallInput").each(function() {
max = parseFloat($(this).attr('maxscale'));
min = parseFloat($(this).attr('minscale'));
rate = parseFloat(this.value) ;
weight = parseFloat(this.value) ;
if( !isNaN(max) || !isNaN(min)){
if( isNaN(rate))
if( isNaN(weight)){
valid = false;
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
}else{
if( (rate > max) || (rate <min) )
if( (weight > max) || (weight <min) ){
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
valid = false;

}else{
$(this).css('background-color', '#ffffff');
$(this).css('border', 'solid 1px #000000');
}
}

}
});
if( !valid ){
msg = '<?php echo __('KPI Should Be a Number Within Minimum and Maximum Value');?>';
$("#messageBalloon_failure ul").html('<li>'+msg+'</li>');
$("#performanceError").show();
}
return valid ;
}


//Check save
function checkSave(){
var valid = true ;
var msg = '';
$("input.smallInput").each(function() {
max = parseFloat($(this).attr('maxscale'));
min = parseFloat($(this).attr('minscale'));
rate = parseFloat(this.value) ;
weight = parseFloat(this.value) ;
if(!isNaN(this.value)){
if( isNaN(rate))
if( isNaN(weight)){
valid = false;
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
}else{
if( (rate > max) || (rate <min) )
if( (weight > max) || (weight <min) ){
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
valid = false;

}else{
$(this).css('background-color', '#ffffff');
$(this).css('border', 'solid 1px #000000');
}
}

}
});
if( !valid ){
msg = '<?php echo __('KPI Should Be a Number Within Minimum and Maximum Value');?>';
$("#messageBalloon_failure ul").html('<li>'+msg+'</li>');
$("#performanceError").show();
}
return valid ;
}

$(document).ready(function(){
var mode = 'edit';





//Disable all fields
$('#frmSave :input').attr('readonly', true);
$('#saveBtn').removeAttr('readonly');

//When click edit button
$("#saveBtn").click(function() {
if( mode == 'edit')
{
$('#saveBtn').attr('value', "<?php echo __("Save")?>");
$('#frmSave :input').removeAttr('readonly');
mode = 'save';
}else
{
if(checkSubmit()){
$('#saveMode').val('save');
$('#frmSave').submit();
}
}
});

//When Submit button click
$("#submitBtn").click(function() {
$('#frmSave :input').removeAttr('readonly');
if(checkSubmit()){
$('#saveMode').val('submit');
$('#frmSave').submit();
}
});

//When Submit button click
$("#rejectBtn").click(function() {
$('#frmSave :input').removeAttr('readonly');
$('#saveMode').val('reject');
$('#frmSave').submit();
});

//When Submit button click
$("#approveBtn").click(function() {
$('#frmSave :input').removeAttr('readonly');
$('#saveMode').val('approve');
$('#frmSave').submit();
});

// Back button
$("#backBtn").click(function() {
location.href = "<?php echo url_for('performance/viewReview');?>";
});

//Validate search form
$("#frmSave").validate({

rules: {
txtMainComment: {maxlength: 250},
validRate: {minmax:true }

},
messages: {
txtMainComment: "<?php echo __(ValidationMessages::TEXT_LENGTH_EXCEEDS, array('%amount%' => 250))?>",
validRate: ""
}
});


$.validator.addMethod("minmax", function(value, element) {

if($('#validRate').val() == '1' )
return true;
else
return false;
});

// check keyup on scale inputs
$("#frmSave").delegate("keyup", "input.smallInput", function(event) {
var id ;
var max ;
var min ;
var rate ;
var weight;
var msg ;
var error = false;
$("input.smallInput").each(function() {

id = $(this).attr('id');
max = parseFloat($(this).attr('maxscale'));
min = parseFloat($(this).attr('minscale'));
rate = parseFloat(this.value) ;
weight = parseFloat(this.value) ;
if(!isNaN(this.value)){

if( (rate > max) || (rate <min) )
if( (weight > max) || (weight <min) ){
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
msg = '<?php echo __('KPI Should Be a Number Within Minimum and Maximum Value')?>';
error = true;

}else{
$(this).css('background-color', '#ffffff');
$(this).css('border', 'solid 1px #000000');
}
}else{
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
msg = '<?php echo __('KPI Should Be a Number Within Minimum and Maximum Value')?>';
error = true;
}
});

if(error){
$("#messageBalloon_failure ul").html('<li>'+msg+'</li>');
$("#performanceError").show();
$('#validRate').val('0');
}else
{
$("#performanceError").hide();
$('#validRate').val('1');
}

return false;
});

//Check Reviwer comment
$("#frmSave").delegate("keyup", "textarea.reviwerComment", function(event) {
validateReviewerComment();
});

function validateReviewerComment() {
var error = false;
var msg ;
var flag = false;

$("textarea.reviwerComment").each(function() {
if(this.value.length >= 2000 ){
$(this).css('background-color', '#ffeeee');
$(this).css('border', 'solid 1px #ffdddd');
error = true;
}else{
$(this).css('background-color', '#ffffff');
$(this).css('border', 'solid 1px #000000');
flag = true;
}
});

if(error){
$("#messageBalloon_failure ul").html('<li><?php echo __('Comment Should Be Less Than %amount% Characters', array('%amount%' => 2000));?></li>');
$("#performanceError").show();
$('#validRate').val('0');
}else{
$("#performanceError").hide();
$('#validRate').val('1');
}
return flag;
}




//make sure all validations are performed before submit
$("#frmSave").submit(function() {
flag = validateReviewerComment();
return flag;
});
});
</script>




hi i mentioned the red color in value just i want know how to call the javascript function variable in php
prabatgp
New php-forum User
New php-forum User
 
Posts: 1
Joined: Wed Feb 20, 2013 5:29 am

Re: Repopulate selectbox depending on choice made in other.

Postby seandisanti » Thu Feb 28, 2013 3:40 pm

calling a javascript function from php:
Code: Select all

<!DOCTYPE html>
<html>
<?php echo '<script>alert("blah");</script>'?>
</html> 
seandisanti
php-forum Fan User
php-forum Fan User
 
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm


Return to PHP coding => General

Who is online

Users browsing this forum: Baidu [Spider] and 2 guests

Sponsored by Sitebuilder Web hosting and Traduzioni Italiano Rumeno and antispam for cPanel.