如何将数据添加到文本输入并在下拉菜单中选择数据? [英] How to add data into a text input and select data in a drop down menu?

查看:108
本文介绍了如何将数据添加到文本输入并在下拉菜单中选择数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的应用程序,您可以在这里看到:应用程序



在应用程序中,您将看到一个下拉菜单,只需从下拉菜单中选择一个课程,您将在下面的文本输入中看到详细信息:



以下是应用程序的代码:

Javascript:

 < script type =text / javascript> ($(this)).val($($))

$(document).ready(function(){
$('#coursesDrop' )!==''){
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 

//连接数据库
include('connect.php');如果(mysqli_connect_errno()){
printf(连接失败:%s\\\
,mysqli_connect_error());
$ b $ / *检查连接* /

die();
}

?>

< h1>编辑课程< / h1>

<?php

$ min_year = 1;
$ max_year = 10;
$年=范围($ min_year,$ max_year); //返回数值为1900 - 2012的数组
$ durationHTML ='';
$ durationHTML。='< select name =durationid =newDuration>'。PHP_EOL;
$ durationHTML。='< option value =>请选择< / option>'。PHP_EOL;

foreach($ year 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);
//你只需要调用bind_param一次

$ courseqrystmt-> execute();

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

$ courseqrystmt-> store_result();

$ coursenum = $ courseqrystmt-> num_rows();

$ courseHTML ='';

$ courseHTML ='< select name =coursesid =coursesDrop>'。PHP_EOL;
$ courseHTML。='< option value =>请选择< / option>'。PHP_EOL;

while($ courseqrystmt-> fetch()){

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


$ courseHTML。='< / select>';


$ courseform =
< p>< strong>课程:< / strong>课程:< / strong> {$ courseHTML}< / p>
< / form>;

echo $ courseform;



$ editsession =
< form id ='updateCourseForm'>

< p>< strong>当前课程详情:< / strong>>< / p>
<表>
< tr>
课程ID:< / th>
< td>< / td>
< / tr> $ b< td>< input type ='text'id ='currentCourseNo'name ='CourseNocurrent'readonly ='readonly'value ='' $ b< tr>
课程名称:< th>
< td>< input type ='text'id ='currentCourseName'name ='CourseNamecurrent'readonly = 'readonly'value =''/>< / td>
< / tr>
< tr>
持续时间(年):< / th>
< td>< input type ='text'id ='currentDuration'name ='Durationcurrent'readonly ='readonly'value =''/>< / td>
< / tr>
< / table>
< div>< div>< / gt>< / div>

< p> < /强>< / p> ;
< table>
< tr>
< th>课程编号:< / th>
< td>< input type ='text'id ='newCourseNo'name ='CourseNoNew'value =''/> < / TD>
< / tr>
< tr>
课程名称:< / th>
< td>< input type ='text'id ='newCourseName'name ='CourseNamenew'value =''/> < / TD>
< / tr>
< tr>
持续时间(年):< / th>
< td> {$ durationHTML}< / td>
< / tr>
< / table>
< div id ='newAlert'>< / div>

< / form>

;

echo $ editsession;


?>

< / body>
< / $ gt;

现在我有两个小问题,持续时间:

问题1: 在应用程序中选择了当然,您可以在当前课程详细信息部分看到课程ID和课程名称文本输入已填写,但持续时间文本输入尚未填写。现在我无法填写持续时间文本输入同样的方式,我已经编码填写其他两个文本输入,因为我不想也不想将每个课程的持续时间包括在下拉菜单中。所以我的问题是什么才是正确和最好的方式才能够问题2:

>

这与问题类似1但是这涉及更新课程详情部分中的持续时间下拉菜单。我想要的是,当用户选择一门课程时,应该在持续时间下拉菜单中选择所选课程的持续时间。目前,在用户选择了课程后,它仍然会在持续时间下拉菜单中显示请选择。

更新:



我已将id ='data'添加到< td> {$ durationHTML}< / td> / p>

下面是javascript:

  var data = document.getElementById 'newDuration')值。 

$('#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');

以上代码不起作用,因为它不会从持续时间下拉菜单中选择持续时间当然选择。我在做什么不正确?



课程详情来自以下数据库:



课程表:

 课程编号课程编号课程名称课程时长
1 INFO101信息通讯技术3/4
2 INFO102计算2

现在我的课程下拉菜单显示数据库中的课程信息,如下所示:

 请选择
INFO101 - 信息通讯技术
INFO102 - 计算

下面是持续时间下拉菜单的样子:

 请选择
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

现在,如果我选择以下课程在课程下拉菜单中:

  INFO101  - 信息通讯技术

然后,您可以在数据库中看到本课程的持续时间是 3/4 ,那么一旦用户选择了课程,持续时间下拉菜单应该选择 3/4 选项 INFO101 - .... 在课程下拉菜单中。



现在,如果我在下面的课程下拉菜单:

  INFO102  - 计算

然后你可以在数据库中看到这门课的持续时间是 2 ,那么持续时间下拉菜单应该选择 2 选项,一旦用户在课程下拉菜单中选择课程 INFO102 - ....



如果您不明白,请给我评论:)



更新2:

 <?php 

//连接到数据库
include('connect.php' ); (mysqli_connect_errno()){
printf(连接失败:%s\\\
,mysqli_connect_error())检查连接* /



) ;
die();
}

?>

< h1>编辑课程< / h1>

<?php

$ min_year = 1;
$ max_year = 10;
$年=范围($ min_year,$ max_year); //返回数值为1900 - 2012的数组
$ durationHTML ='';
$ durationHTML。='< select name =durationid =newDuration>'。 PHP_EOL;
$ durationHTML。='< option value =>请选择< / option>'。 PHP_EOL;

foreach($ year 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);
//你只需要调用bind_param一次

$ courseqrystmt-> execute();

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

$ courseqrystmt-> store_result();

$ coursenum = $ courseqrystmt-> num_rows();

$ courseHTML ='';

$ courseHTML ='< select name =coursesid =coursesDrop>'。 PHP_EOL;
$ courseHTML。='< option value =>请选择< / 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 =
< p>< strong>课程:< / strong> {$ courseHTML}< / p>
< / form> ;;

echo $ courseform;



$ editcourse =
< form id ='updateCourseForm'>

< p>< strong>新课程详情:< / strong>< / p>
< table>
< tr>
持续时间(年):< / th>
< td id ='data'> {$ durationHTML}< / td>
< / tr>
< / table>

< /形式>
;

echo $ editcourse;

?>

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

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

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

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

如果(courseinfo [i] .courseId = courseId){
coursedata = courseinfo [i]; $ b $($ i = 0,l = courseinfo.length; i <1; i ++) b}
}

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

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

});
});
< /脚本>


解决方案

问题1:

您应该找到一种方法将持续时间链接到下拉菜单中的项目,所以...您不想执行的操作(将全部内容放在选项标签中)看起来是最好的答案。无论如何,你可以写一个javascript数组,并使用selectedIndex值指向正确的数据,就像这样:

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

$ / code>

问题2:

  $('select')同第一个例子一样,使用selectIndex属性来设置默认值。 )[0] .selectedIndex = n 


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>

解决方案

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

这篇关于如何将数据添加到文本输入并在下拉菜单中选择数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆