使用onclick在jquery自动完成中获取所选值

时间:2015-03-04 13:39:33

标签: jquery

这是我的链接:http://vkacademy.in/medvanndemo/test/类型。我想使用onclick在jQuery中获取选定的下拉列表值。我也尝试了onkeyupkeypresschangebind。这是我的代码

<html>
    <script type="text/jscript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="jquery/js/jquery-ui-1.8.2.custom.min.js"></script> 
    <script type="text/javascript"> 
        jQuery(document).ready(function() {
            $('#categoryfield').autocomplete({
                source: 'suggest_cate.php', 
                minLength: 2
            });
        });
    </script> 
    <script>
    $(document).ready(function() {
        //alert('ok');
        $("#categoryfield").change(function() {
            var catid1 = this.value;
            //alert(catid1);
            var url = "sample.php?cateid1=" + catid1;
            //alert(url);
            $.post(url, function(data) {
                //alert(data);
                $("#option1").html(data);
            });
        });
        $("#option2").click(function() {
            $("#option2_error").html("Sorry! Please select the product.");
        });
    });
</script>

<body>
    <form name="frm1" action="" method="post">
        <input type="text" name="category" id="categoryfield" value='' class="buttonlength" placeholder="E.g. Tuition, Music, Dance" />
        <span id="option1">
            <select name="pname" id="option2">
                <option value="">Select the field</option>
            </select>
        </span>
        <span id="option2_error" style="color:red; font-size:15px;"></span><br>
        <input type="submit" name="sub" />
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

当您执行html()时,您正在重写option2 div,因此事件不再处于活动状态。尝试在ajax调用中执行事件处理:

 $(document).ready(function() {
    //alert('ok');
    $("#categoryfield").change(function() {
        var catid1 = this.value;
        //alert(catid1);
        var url = "sample.php?cateid1=" + catid1;
        //alert(url);
        $.post(url, function(data) {
            //alert(data);
            $("#option1").html(data);
            $("#option2").click(function() {
               $("#option2_error").html("Sorry! Please select the product.");
            });
        });
    });

});