Manixman
Manixman

Reputation: 307

How to add data into a text input and select data in a drop down menu?

I have a simple application which yo can see here: application

In the application you will see a drop down menu, simply select a course from the drop down menu and you will see the details displayed in the text inputs below:

Below is the code for the application:

Javascript:

<script type="text/javascript">

$(document).ready( function(){
$('#coursesDrop').change( function(){
if( $(this).val() !== '' ){
var text = $(this).find('option:selected').text();
var split = text.split(' - ');
$('#currentCourseNo').val( split[0] );     
$('#currentCourseName').val( split[1] );       
$('#newCourseNo').val( split[0] );  
$('#newCourseName').val( split[1] ); 
}
else{
$('#currentCourseNo,#currentCourseName,#currentDuration').val('');   
$('#newCourseNo,#newCourseName,#newDuration').val('');                 
}
});
});



</script>   

PHP/HTML:

<?php

// connect to the database
include('connect.php');

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}

?>

<h1>EDIT COURSE</h1>

<?php

$min_year = 1;
$max_year = 10;
$years = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="newDuration">'.PHP_EOL; 
$durationHTML .= '<option value="">Please Select</option>'.PHP_EOL;  

foreach ($years as $year) {
$durationHTML .= "<option>$year</option>".PHP_EOL;  
if ($year != $max_year) {
$nextYear = $year + 1;
$durationHTML .= "<option>$year/$nextYear</option>".PHP_EOL;              
}
}
$durationHTML .= '</select>'; 

$newCourseNo = (isset($_POST['CourseNoNew'])) ? $_POST['CourseNoNew'] : '';

$coursequery = "
SELECT CourseId, CourseNo, CourseName, Duration
FROM Course
ORDER BY CourseNo
";

$courseqrystmt=$mysqli->prepare($coursequery);
// You only need to call bind_param once

$courseqrystmt->execute(); 

$courseqrystmt->bind_result($dbCourseId,$dbCourseNo,$dbCourseName,$dbDuration);

$courseqrystmt->store_result();

$coursenum = $courseqrystmt->num_rows();     

$courseHTML = '';

$courseHTML = '<select name="courses" id="coursesDrop">'.PHP_EOL;
$courseHTML .= '<option value="">Please Select</option>'.PHP_EOL;           

while ( $courseqrystmt->fetch() ) {

$courseHTML .= sprintf("<option value='%s'>%s - %s</option>", $dbCourseId,$dbCourseNo,$dbCourseName) . PHP_EOL; 
}


$courseHTML .= '</select>';


$courseform = "
<form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post' id='courseForm'>
<p><strong>Course:</strong> {$courseHTML} </p>   
</form>";

echo $courseform;



$editsession = "
<form id='updateCourseForm'>

<p><strong>Current Course Details:</strong></p>
<table>
<tr>
<th>Course ID:</th>
<td><input type='text' id='currentCourseNo' name='CourseNocurrent' readonly='readonly' value='' /> </td>
</tr>
<tr>
<th>Course Name:</th>
<td><input type='text' id='currentCourseName' name='CourseNamecurrent' readonly='readonly' value='' /> </td>
</tr>
<tr>
<th>Duration (Years):</th>
<td><input type='text' id='currentDuration' name='Durationcurrent' readonly='readonly' value=''/> </td>
</tr>
</table>
<div id='currentAlert'></div>

<p><strong>New Course Details:</strong></p>
<table>
<tr>
<th>Course ID:</th>
<td><input type='text' id='newCourseNo' name='CourseNoNew' value='' /> </td>
</tr>
<tr>
<th>Course Name:</th> 
<td><input type='text' id='newCourseName' name='CourseNamenew' value='' /> </td>
</tr>
<tr>
<th>Duration (Years):</th> 
<td>{$durationHTML}</td>
</tr>
</table>
<div id='newAlert'></div>

</form>

";

echo $editsession;


?>

</body>
</html>

Now I have 2 small problems which both deal with the Courses's duration:

Problem 1:

In the application when you have selected the course, you can see that under the "Current Course Details" section that the Course ID and Course Name text inputs have been filled in but the Duration text input has not been filled in. Now I can't fill in the Duration text input the same way I have coded to fill in the other two text inputs because I havn't and do not want to include each course's duration in the drop down menu. So my question is what is the correct and best way in order to be able to fill in the Duration Text input for the selected course when the course has been selected from the drop down menu?

Problem 2:

This is similar to problem 1 but this deals with the Duration's Drop Down menu in the "Update Course Details" section. What I want is that when the user selects a course, the selected course's duration should be selected in the Duration drop down menu. At the moment it still states "Please Select" for the duration drop down menu after the user has selected a course

UPDATE:

I have added id='data' to the <td>{$durationHTML}</td>.

Below is the javascript:

var data = document.getElementById('newDuration').value;

$('#coursesDrop').change(function()
{
  var index = this.selectedIndex;

  /* part 1 */
  var data_to_display = data[index];
  $('#data').text(data_to_display);

  /* part 2 */    
  $('#durationDrop')[0].selectedIndex = index;    

}).trigger('change');

The above code is not working as it does not select the duration from the duration drop down menu for the course selected. What am I doing incorrectly?

The details of the course comes from the database below:

Course Table:

CourseId CourseNo CourseName                             Duration
1        INFO101  Information Communication Technology   3/4
2        INFO102  Computing                              2

Now my Course drop down displays the course information from the database as so:

Please Select
INFO101 - Information Communication Technology
INFO102 - Computing

Now below is what the Duration Drop Down menu looks like:

Please Select
1
1/2
2
2/3
3
3/4
4
4/5
5
5/6
6
6/7
7
7/8
8
8/9
9
9/10
10

Now if I select this course below in the course drop down menu:

INFO101 - Information Communication Technology

Then as you can see in the database the duration for this course is 3/4, then the Duration drop down menu should select the 3/4 option once the user has selected course INFO101 - .... in the course drop down menu.

Now if I select this course below in the course drop down menu:

INFO102 - Computing

Then as you can see in the database the duration for this course is 2, then the Duration drop down menu should select the 2 option once the user has selected course INFO102 - .... in the course drop down menu.

Please comment to me if you do not understand :)

UPDATE 2:

<?php

// connect to the database
include('connect.php');


/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
}

?>

<h1>EDIT COURSE</h1>

<?php

$min_year     = 1;
$max_year     = 10;
$years        = range($min_year, $max_year); // returns array with numeric values of 1900 - 2012
$durationHTML = '';
$durationHTML .= '<select name="duration" id="newDuration">' . PHP_EOL;
$durationHTML .= '<option value="">Please Select</option>' . PHP_EOL;

foreach ($years as $year) {
    $durationHTML .= "<option>$year</option>" . PHP_EOL;
    if ($year != $max_year) {
        $nextYear = $year + 1;
        $durationHTML .= "<option>$year/$nextYear</option>" . PHP_EOL;
    }
}
$durationHTML .= '</select>';

$newCourseNo = (isset($_POST['CourseNoNew'])) ? $_POST['CourseNoNew'] : '';

$coursequery = "
SELECT CourseId, CourseNo, CourseName, Duration
FROM Course
ORDER BY CourseNo
";

$courseqrystmt = $mysqli->prepare($coursequery);
// You only need to call bind_param once

$courseqrystmt->execute();

$courseqrystmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName, $dbDuration);

$courseqrystmt->store_result();

$coursenum = $courseqrystmt->num_rows();

$courseHTML = '';

$courseHTML = '<select name="courses" id="coursesDrop">' . PHP_EOL;
$courseHTML .= '<option value="">Please Select</option>' . PHP_EOL;

$courseInfo = array();

while ($courseqrystmt->fetch()) {
    $courseHTML .= sprintf("<option value='%s'>%s - %s</option>", $dbCourseId, $dbCourseNo, $dbCourseName) . PHP_EOL;

    $courseData               = array();
    $courseData["CourseId"]   = $dbCourseId;
    $courseData["CourseNo"]   = $dbCourseNo;
    $courseData["CourseName"] = $dbCourseName;
    $courseData["Duration"]   = $dbDuration;

    array_push($courseInfo, $courseData);
}


$courseHTML .= '</select>';


$courseform = "
<form action='" . htmlentities($_SERVER['PHP_SELF']) . "' method='post' id='courseForm'>
<p><strong>Course:</strong> {$courseHTML} </p>   
</form>";

echo $courseform;



$editcourse = "
<form id='updateCourseForm'>

<p><strong>New Course Details:</strong></p>
<table>
<tr>
<th>Duration (Years):</th> 
<td id='data'>{$durationHTML}</td>
</tr>
</table>

</form>
";

echo $editcourse;

?>

< script type = "text/javascript" > 
$(document).ready(function() {

    var courseinfo = '<?php=json_encode($courseInfo);?>';

    $('#coursesDrop').change(function() {

        var courseId = $(this).val(),
        coursedata;

        for (var i = 0, l = courseinfo.length; i < l; i++) {
            if (courseinfo[i].courseId = courseId) {
                coursedata = courseinfo[i];
            }
        }

        var index = $('#newDuration option[value="' + courseData.Duration + '"]').index('#newDuration option');

        $('#newDuration')[0].selectedIndex = index;

    });
});
 < /script>

Upvotes: 0

Views: 648

Answers (1)

y_nk
y_nk

Reputation: 2275

Problem 1:

You should find a way to "link" durations to items in the dropdown, so... what you don't want to do (put all in the option tag) looks to be the best answer. Anyway you could write a javascript array and use the 's selectedIndex value to point to the good data, with a thing like that :

$('select').change(function()
{
   var index = this.selectedIndex;
   $('input').val(duration_data[index]);
}

Problem 2:

Same as first, as u said. Use the selectIndex property to set your default value by the code.

$('select')[0].selectedIndex = n

Upvotes: 1

Related Questions