복붙노트

[JQUERY] 다운 상자 동적 드롭?

JQUERY

다운 상자 동적 드롭?

해결법


  1. 1.여기 당신이 원하는 것을 할 것입니다 예입니다. 기본적으로, 당신은이를 위해 jQuery를 / AJAX를 사용할 수 있습니다.

    여기 당신이 원하는 것을 할 것입니다 예입니다. 기본적으로, 당신은이를 위해 jQuery를 / AJAX를 사용할 수 있습니다.

    난 당신이 다음 놀 완벽하게 동작하는 예제를 가져야한다 (이를 tester.php 전화 another_php_file.php) 파일로이 두 가지 예를 복사 / 붙여 넣기 그렇다면, 서버 로그인 / 테이블 / 필드 이름에 맞게 내 예제 코드를 업데이트했습니다.

    나는 두 번째 드롭 다운 상자를 만들려면 아래 내 변형 예,의 값으로는 발견했다. 당신은 라인별로 논리 라인을 따르는 경우에, 당신은 실제로 매우 간단 볼 수 있습니다. 나는 주석 (한 번에 한) 스크립트가 각 단계에서 무엇을하고 있는지를 보여줍니다 경우, 여러 가지 주석 처리 된 줄에 남아.

    FILE 1 - TESTER.PHP

    <html>
        <head>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script type="text/javascript">
                $(function() {
    //alert('Document is ready');
    
                    $('#stSelect').change(function() {
                        var sel_stud = $(this).val();
    //alert('You picked: ' + sel_stud);
    
                        $.ajax({
                            type: "POST",
                            url: "another_php_file.php",
                            data: 'theOption=' + sel_stud,
                            success: function(whatigot) {
    //alert('Server-side response: ' + whatigot);
                                $('#LaDIV').html(whatigot);
                                $('#theButton').click(function() {
                                    alert('You clicked the button');
                                });
                            } //END success fn
                        }); //END $.ajax
                    }); //END dropdown change event
                }); //END document.ready
            </script>
        </head>
    <body>
    
        <select name="students" id="stSelect">
            <option value="">Please Select</option>
            <option value="John">John Doe</option>
            <option value="Mike">Mike Williams</option>
            <option value="Chris">Chris Edwards</option>
        </select>
        <div id="LaDIV"></div>
    
    </body>
    </html>
    

    FILE 2 - another_php_file.php

    <?php
    
    //Login to database (usually this is stored in a separate php file and included in each file where required)
        $server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
        $login = 'root';
        $pword = '';
        $dbname = 'test';
        mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
        mysql_select_db($dbname) or die($connect_error);
    
    //Get value posted in by ajax
        $selStudent = $_POST['theOption'];
        //die('You sent: ' . $selStudent);
    
    //Run DB query
        $query = "SELECT * FROM `category` WHERE `master` = 0";
        $result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
        $num_rows_returned = mysql_num_rows($result);
        //die('Query returned ' . $num_rows_returned . ' rows.');
    
    //Prepare response html markup
        $r = '  
                <h1>Found in Database:</h1>
                <select>
        ';
    
    //Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
        if ($num_rows_returned > 0) {
            while ($row = mysql_fetch_assoc($result)) {
                $r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
            }
        } else {
            $r = '<p>No student by that name on staff</p>';
        }
    
    //Add this extra button for fun
        $r = $r . '</select><button id="theButton">Click Me</button>';
    
    //The response echoed below will be inserted into the 
        echo $r;
    

    코멘트에서 귀하의 질문에 대답하려면 : "당신이 다운 상자 1 드롭에서 선택한 옵션 만 관련이있는 상자 채우기 필드 아래 2 방울을 어떻게해야합니까?"

    첫 번째 드롭에 대한 .change 이벤트 내부 A., 당신은 첫 번째 드롭 다운 상자의 값을 읽을 수 :

    $ ( '#은 dropdown_id'). 변화 (함수 () { VAR DD1 = $ ( '#은 dropdown_id') 발 ().; }

    위의 .change () 이벤트에 대한 AJAX 코드에서 B., 당신은 (우리의 경우, "another_php_file.php")는 2 .PHP 파일로 보내는 데이터에서 그 변수를 포함

    전달 된 변수 MySQL의 쿼리하여 결과를 제한 C. 당신의 사용. 이러한 결과는 다음 AJAX 기능에 다시 전달하고 당신은 성공에 액세스 할 수 있습니다 : AJAX와 기능의 일부를

    D.에서 그 성공의 기능, 당신 개정 된 SELECT 값으로 DOM에 코드를 주사한다.

    즉, 예를 들어 위에서 게시에 내가 뭐하는 거지입니다 :

    그리고 짜잔, 당신은 이제 첫 번째 드롭 다운 컨트롤에서 선택에 값 특정 주문을 받아서 두 번째 드롭 다운 컨트롤을 참조하십시오.

    타사 브라우저처럼 작동합니다.

  2. from https://stackoverflow.com/questions/16924082/dynamic-drop-down-box by cc-by-sa and MIT license