dragon_9000 2012-11-23 17:32
浏览 54
已采纳

使用JQuery自动完成强制选择

I know this question has been asked before, but I wasn't able to find any answers that are up to date or functional (at least for my application).

My JQuery autocomplete box is using a mysql database as its source. I want the user to be able to type to get recommendations, but then is forced to select from the dropdown choices before they can submit the form.

My Javascript:

    <script type="text/javascript">
    $.widget( 'ui.autocomplete', $.ui.autocomplete, {
        _renderMenu: function( ul, items ) {
            var that = this;
            $.ui.autocomplete.currentItems = items;
            $.each( items, function( index, item ) {
                that._renderItemData( ul, item );
            });
        }        
    });
    $.ui.autocomplete.currentItems = [];

    $(function() {

        $("#college").autocomplete({
            source: "search.php",
            minLength: 5
        });
    });

    var inputs = {college: false};

    $('#college').change(function(){
        var id = this.id;
        inputs[id] = false;

        var length = $.ui.autocomplete.currentItems.length;
        for(var i=0; i<length; i++){
            if($(this).val() == $.ui.autocomplete.currentItems[i].value){
                inputs[id] = true;
            }
        }
    });

    $('#submit').click(function(){
        for(input in inputs){
            if(inputs.hasOwnProperty(input) && inputs[input] == false){
                alert('incorrect');
                return false;
            }
        }
        alert('correct');
        $('#college_select_form').submit();
    });
    </script>

My form:

<form action="choose.php"  method="post" id="college_select_form" name="college_select_form">
                                        <input type="text" id="college"  name="college" class="entry_field" value="Type your school" onclick="this.value='';" onfocus="this.select()" onblur="this.value=!this.value?'Type your school':this.value;" /><input type="submit" id="submit" name="submit" class="submitButton" value="Go" title="Click to select school" />
                                    </form>

Search.php:

<?php

try {
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
    echo $e->getMessage();
}

$return_arr = array();

if ($conn)
{
    $ac_term = "%".$_GET['term']."%";
    $query = "SELECT * FROM college_list where name like :term";
    $result = $conn->prepare($query);
    $result->bindValue(":term",$ac_term);
    $result->execute();

    /* Retrieve and store in array the results of the query.*/
    while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
        array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
    }


}
/* Free connection resources. */
//$conn = null; 
/* Toss back results as json encoded array. */
echo json_encode($return_arr);

?>

So what would be the best approach to doing this? The only solution I can think of is using PHP to verify that the textbox's value matches a value in the database, but I'm not sure how to implement that with my current code.

  • 写回答

6条回答 默认 最新

  • douzhi1972 2012-11-28 23:21
    关注

    You should always check it in "choose.php" (server-side) since the user can disable the JavaScript and post whatever they want in the inputs of your form

    $college = mysql_real_escape_string($_GET['college']);
    if ($college != "" || $college != null || $college != -1)
    {
        //DO STUFF
    }
    

    NOTE: YOU SHOULD ALWAYS USE "mysql_real_escape_string" to prevent SQL Injection! more info: http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php

    So accordingly in search.php change the

    $ac_term = "%".$_GET['term']."%";
    

    to

    $ac_term = "%". mysql_real_escape_string($_GET['term']) ."%";
    

    You can also check the form before the user submit to just make it more user friendly (users don't want to wait couple of seconds for the page to gets refreshed with errors on it!)

    so maybe something like this would help: Submit Event Listener for a form

    function evtSubmit(e) {
      // code
      e.preventDefault();
     // CHECK IT HERE!
    };
    
    var myform = document.myForm;
    myform.setAttribute('action', 'javascript:evtSubmit();');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了