PHP-根据<select> <option>值填充表单字段

时间:2019-11-21 14:16:36

标签: php html forms pdo

我正在尝试根据<select>中选择的选项来填充表格。数据库中的eventTitle字段具有位于代码底部的相应字段。如果选择选项1,我希望在表单中填充与选项1相对应的字段。我不确定执行此操作的最佳方法。提前致谢。 另外,如果您对我应该做的其他事情有其他建议,例如我在编码不良做法,请提出建议。谢谢!

require_once "functions.php";

//this creates a reference to the connection which is in the functions.php file
$connection = getConnection();






//so far this gets all the event titles and echos out a drop down list with them in. yay
$sqlPopulateQuery = "SELECT eventTitle, eventID from NE_events";
$queryResult = $connection->query($sqlPopulateQuery);

echo "Event Title: <select name='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
    echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";

//if a specific event is selected
    //get eventID from database
    //populate textfield with eventID



//echo "Event ID:  <input type='text' ' name='eventID' readonly><br>";
//echo "Venue ID: <input type='text' name='venueID'><br>";
//echo "Category ID: <input type='text' name='categoryID'><br>";
//echo "Start Date: <input type='date' name='eventStartDate'><br>";
//echo "End Date: <input type='date' name='eventEndDate'><br>";
//echo "Price: <input type='text' name='eventPrice'><br>";




?>```


1 个答案:

答案 0 :(得分:0)

您可以使用普通的javascipt或Jquery库满足您的要求,下面列出了每种方法

1。使用javascript解决方案

<?php   
while ($record = $queryResult->fetchObject()) {
    echo "<option value='{$record->eventTitle}' onChange="popuplateData({$record->eventTitle})">{$record->eventTitle}</option>";
}
echo "Event ID:  <input type='text' id='eventID' name='eventID' readonly><br>";
?>

<script>
function popuplateData(option){

    if(option === 'title1'){ // For each option you can modify based on value
        document.getElementById('eventID').value = 'event 1';   
        //More fields goes here
    }

}
</script>

2。使用Jquery解决方案

<?php 
echo "Event Title: <select name='eventTitle' id='eventTitle'>";
while ($record = $queryResult->fetchObject()) {
    echo "<option value='{$record->eventTitle}'>{$record->eventTitle}</option>";
}
echo "</select>";
echo "Event ID:  <input type='text' id='eventID' name='eventID' readonly><br>";
?>

<script>
jQuery(document).ready(function($) {
    $("#eventTitle").change(function(){
        var optionVal = $(this).val();  
        if(optionVal != ''){
            if(optionVal === 'title1'){// For each option you can modify based on value
                $('#eventID').val('event 1');   
                //More fields goes here
            }   
        }
    });
});
</script>