0

所以我一直试图弄清楚这几天,但无济于事。我正在尝试使用 php 使用从 mysql 查询的值填充 html 表单。我使用heredoc 将带有填充值的表单推送到网页,但我无法填充下拉列表。如果有人愿意提供帮助,如果您也可以包含有关如何填充单选按钮的方法,因为这是我在下拉列表>_< 之后的下一个任务。

我尝试过的最近的事情,在下面的代码中来自这篇文章: 如何使用 javascript 以编程方式设置选择框元素的值?

但它仍然无法执行。

我用谷歌搜索了很多,查看了多个 stackoverflow 帖子,甚至试图找到一个关于如何做到这一点的 youtube 教程。我现在很沮丧,想弄清楚这个虫子。

这是我的html:

<!DOCTYPE html>

<html>
    <head>
        <Script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        <script language="javascript" type="text/javascript">

        function searchDB(){
            //alert ("running searchDB")
            var $request;
            // abort any pending request
            if ($request) {
                $request.abort();
            }
            // setup some local variables
            var $form = $("#searchForm");
            // let's select and cache all the fields
            var $inputs = $form.find("uniqueID");
            // serialize the data in the form
            var serializedData = $form.serialize();

            if (alphaNumericCheck()) {
                //disable the inputs for the duration of the ajax request
                $inputs.prop("disabled", true);

                // fire off the request to /form.php
                $request = $.ajax({
                    url: "SearchandUpdateIsaiah.php",
                    type: "POST",
                    data: serializedData
                });

                // callback handler that will be called on success
                $request.success(function (response, textStatus, jqXHR){
                    // log a message to the console
                    $("#display").html(response);

                });
                // callback handler that will be called on failure
                $request.fail(function (jqXHR, textStatus, errorThrown){
                    // log the error to the console
                    console.error(
                        "The following error occured: "+
                        textStatus, errorThrown
                    );
                });

                // callback handler that will be called regardless
                // if the request failed or succeeded
                $request.always(function () {
                    // reenable the inputs
                    $inputs.prop("disabled", false);
                });

                }
        };
        //makes sure all values submitted in form only contain a-z, A-Z, or 0-9 and no spaces.
        function alphaNumericCheck() {
            var regex = /^[a-zA-Z0-9]+$/;
            if (!regex.test($("#uniqueID").val())) 
            {
                alert("Please fix search term");
                return false;
            }
            /*else if (!regex.test($("#lName").val()))
            {
                alert("Please fix last name");
                return false;
            }*/
            else
            {
                return true;
            }
        };


        </script>
    </head>
    <body>
        <br>
        Search form
        <form id="searchForm">
            Insert a uniqueID: <input type="text" id="uniqueID" name="uniqueID">
        </form>
        <input type="button" id="search" name="search" value="Search">
        <script> $("#search").click(function(){searchDB();});</script>

        <div id="display"> </div>


</body>

这是我的php:

<?php
//Search the database function
SearchDB();
Function SearchDB(){

    $search=$_POST['uniqueID'];


    //------------------------------------------------------------------------
    //----------------------connect to database-------------------------------
    //------------------------------------------------------------------------
    $dbhost = '**********';
    $dbuser = '**********';
    $dbpass = '**********';
    //connection to database, stored as $conn
    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' .     mysql_error());
    //------------------------------------------------------------------------
    //----------------------connect to database-------------------------------
    //------------------------------------------------------------------------

    mysql_select_db("test_db",$conn);
    $likeSearch = $search.'%';
    $sql = "SELECT * FROM alumni WHERE uniqueID = '$search' OR last_name LIKE '$likeSearch'"; 
    $result = mysql_query($sql,$conn);
    $resultsArray = array();
    if (!$result) {
        echo "worked";
        $resultCount=0;
    }else {
        while ($row = mysql_fetch_assoc($result)) {
            $resultsArray[] = array(
                'uniqueID' => $row['uniqueID'],
                'fName' => $row['first_name'],
                'lName' => $row['last_name'],
                'salary' => $row['salary'],
                'company' => $row['company']
            );
        }
        $resultCount = Count($resultsArray);
    }

    if ($resultCount>1) {
    //return list of names
        //echo $resultCount. "\n";
        foreach ($resultsArray as $value){
                $string = "First name: {$value[fName]}    Last name: {$value[lName]}    Unique ID: {$value[uniqueID]} \n";  
                $textReturn = $textReturn.$string;
        };
        $textReturn = $textReturn."Copy and paste the UniqueID of the student whose data you wish to retrieve.";
$c = <<<TEXT
    </br> <textarea rows="{4*$resultCount}" cols="75">{$textReturn}</textarea>
TEXT;
        echo $c;
    }elseif ($resultCount===1) {
    //return form of data
        foreach ($resultsArray as $value){
            $formFirstName = $value[fName];
            $formLastName = $value[lName];
            $formSalary = $value[salary];
            $formCompany = $value[company];
        };
$c = <<<TEXT
<!DOCTYPE html>
    <html>
        <head>
            <Script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

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

            function submit(){
                var $request;
                // abort any pending request
                if ($request) {
                    $request.abort();
                }
                // setup some local variables
                var $form = $("#alumniForm");
                // let's select and cache all the fields
                var $inputs = $form.find("fName, lName, company, salary, submit");
                // serialize the data in the form
                var serializedData = $form.serialize();

                if (alphaNumericCheck())
                {
                    //disable the inputs for the duration of the ajax request
                    $inputs.prop("disabled", true);

                    // fire off the request to /form.php
                    $request = $.ajax({
                        url: "main2.php",
                        type: "POST",
                        data: serializedData
                    });

                    // callback handler that will be called on success
                    $request.done(function (response, textStatus, jqXHR){
                        // log a message to the console
                        $("#ajaxInfo").html(response).show();
                    });

                    // callback handler that will be called on failure
                    $request.fail(function (jqXHR, textStatus, errorThrown){
                        // log the error to the console
                        console.error(
                            "The following error occured: "+
                            textStatus, errorThrown
                        );
                    });

                    // callback handler that will be called regardless
                    // if the request failed or succeeded
                    $request.always(function () {
                        // reenable the inputs
                        $inputs.prop("disabled", false);
                    });

                    }
                    else
                    {
                    }
            };
            //makes sure all values submitted in form only contain a-z or A-Z and no spaces.
            function alphaNumericCheck() {
                var $regex = /^[a-zA-Zs]+$/;
                if (!$regex.test($("#fName").val())) 
                {
                    alert("Please fix first name");
                    return false;
                }
                else if (!regex.test($("#lName").val()))
                {
                    alert("Please fix last name");
                    return false;
                }
                else
                {
                    return true;
                }
            }

            </script>

        </head>
        <body>
                <form id="alumniForm">
                    <h3>Alumni Form</h3>
                    <br/>
                    <input type='hidden' name='submitted' id='submitted' value='alumni'/>
                    Input name <br/>
                        First Name: <input type="text" name="fName" id="fName" value="{$formFirstName}">
                        Last Name: <input type="text" name="lName" id="lName" value="{$formLastName}">

                     <br>
                     Select user company name from a dropdown list <br/>
                        <script>
                            var element = document.getElementById('company');
                            element.value = {$formCompany};
                            $('#company').selectmenu('refresh');
                        </script>
                        <select name="company" id="company">
                            <option value=""></option>
                            <option value="Proctor & Gamble">Proctor & Gamble</option>
                            <option value="General Electric">General Electric</option>
                            <option value="PwC">PwC</option>
                            <option value="McDonalds">McDonalds</option>
                        </select>

                     <br>
                     Select user salary range using radio buttons
                     <br>
                        <input type="radio" id="salary" name="salary" value="LT30000">Less than $30,000<br>
                        <input type="radio" id="salary" name="salary" value="30000">$30,000-$40,000<br>
                        <input type="radio" id="salary" name="salary" value="40000">$40,000-$50,000<br>
                        <input type="radio" id="salary" name="salary" value="50000">$50,000-$60,000<br>
                        <input type="radio" id="salary" name="salary" value="60000">$60,000-$70,000<br>
                        <input type="radio" id="salary" name="salary" value="70000">$70,000-$80,000<br>
                        <input type="radio" id="salary" name="salary" value="80000">$80,000-$90,000<br>
                        <input type="radio" id="salary" name="salary" value="90000">$90,000-$100,000<br>
                        <input type="radio" id="salary" name="salary" value="GT100000">Greater than $100,000
                    </form>
                    <br/>
                    <input type="submit" id="submit" name="submit" value="ADD/UPDATE" onclick="javascript:submit()"/> <br/>
                    <br><textarea id="ajaxInfo" rows="4" cols="75"> display php return </textarea><br/>

        </body>
    </html>
TEXT;
            echo $c;
    }else {
        echo "No results found \n";
    };  

    mysql_close($conn);
}
?>

非常感谢!!

4

1 回答 1

0

“自动填充下拉选择不会更新/显示”

您永远不会使用 PHP 来更新选择器,javascript 也不会做任何事情。

你创造

select name="company"

但你永远不会更新它。这就是为什么什么都没有发生。

还:

$('#company').selectmenu('refresh');

不应该做任何事情,因为您还没有声明#company 的存在。

于 2013-04-17T15:12:01.303 回答