2017-11-11 1 views
0

select optionselect option을 기반으로합니다.다른 선택 기준으로 선택 PHP

의미 만약 옵션 : 은 다음 두 번째 옵션은 옵션이 있어야합니다 첫 번째 옵션에서 선택 : S1, F1.

옵션 경우 가 첫 번째 옵션에서 선택되는 다음 두 번째 옵션이 있어야 옵션 : S2, F2.

등등 ..하지만 내 select option는 데 모든 옵션.

참고 : select의 옵션은 데이터베이스를 기반으로합니다.

내가 시도 :

<td><select class="country" name="item1"> 
    <option value="Select Item">Item</option> 
    <?php 
    $stmt = $user_home->runQuery('SELECT * FROM item ORDER BY Sr ASC '); 
    $stmt->execute(); 

    if($stmt->rowCount() > 0) 
    { 

     while($row=$stmt->fetch(PDO::FETCH_ASSOC)) 
     { 
      extract($row); 
      ?> 
    <option value="<?php echo $IRN ?>"><?php echo $Name; ?></option> 
    <?php 
     } 
    } 

     ?> 
</select></td> 

     <td><select class="country" name="service1"> 
    <option value="Select Service">Service</option> 
    <?php 
    $stmt = $user_home->runQuery('SELECT * FROM service WHERE IRN = :irn ORDER BY Sr ASC '); 
    $stmt->bindParam(':irn',$IRN); 
    $stmt->execute(); 

    if($stmt->rowCount() > 0) 
    { 

     while($row=$stmt->fetch(PDO::FETCH_ASSOC)) 
     { 
      extract($row); 
      ?> 
    <option value="<?php echo $SRN ?>"><?php echo $Name; ?></option> 
    <?php 
     } 
    } 

     ?> 
</select></td> 

집중 코드 : 나는 (안 데이터베이스를 & codding 모든 옵션을 사용하여) 고정 값으로이 작업을 수행하는 방법을 알고 있지만, 제가 드릴 수 없습니다

$stmt = $user_home->runQuery('SELECT * FROM service WHERE IRN = :irn ORDER BY Sr ASC '); 
    $stmt->bindParam(':irn',$IRN); 
    $stmt->execute(); 

동적 값으로 수행 (옵션을 위해 데이터베이스 사용).

+0

나는 당신의 필요를 이해한다면, 당신은 완전히 다른 방법을 사용해야합니다. 가능한 해결책 : 1) 첫 번째 Items 쿼리는 해당 ''을 리턴합니다. – cFreed

+0

@cFreed Ok, 그렇게하는 법? 내 코드를 추가/편집하여 설명해 주시겠습니까? – BTC

답변

0

간단한 체인으로 연결된 선택 메뉴의 다음 예는 목표를 달성하는 방법에 대한 아이디어를 제공해야합니다.이를 연구하고 데이터베이스 호출을 구현해야하지만 전체 코드를 복사하고 당신이 당신의 자신의 데이터베이스 코드와 AJAX 위의 솔루션을 구현하려고 시도 할 수 없거나 꺼려하는 이유

<?php 
    /* 
     Include other PHP files/libraries, 
     set the session etc etc 

     ..... 
    */ 


    if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['action'], $_POST['id']) && $_POST['action']=='get_dependant_menu'){ 
     ob_clean(); 

     $action=filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING); 
     $id=filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT); 

     if($action && $id && !is_nan($id)){ 
      /* 

       In production you would use the supplied POST values to query the database 
       and process the recordset - sending back the results as formatted HTML to 
       the AJAX callback function. 

       For the sake of demonstration though the script simply sends back data from a 
       simple loop... 

       sql=select * from table where id=? etc 

      */ 



      for($i=1; $i <= 10; $i++)echo "<option value='Service-$id-$i'>Service-$id-$i"; 
     } 
     exit(); 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <title>Dependent/Chained SELECT menus</title> 
     <script type='text/javascript' charset='utf-8'> 
      /* Basic Ajax function */ 
      function ajax(m,u,p,c,o){ 
       /* 
        m=Method, 
        u=Url, 
        p=Params, 
        c=Callback, 
        o=Options 
       */ 
       var xhr=new XMLHttpRequest(); 
       xhr.onreadystatechange=function(){ 
        if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders()); 
       }; 

       var params=[]; 
       for(var n in p)params.push(n+'='+p[n]); 

       switch(m.toLowerCase()){ 
        case 'post': p=params.join('&'); break; 
        case 'get': u+='?'+params.join('&'); p=null; break; 
       } 

       xhr.open(m.toUpperCase(), u, true); 
       xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
       xhr.send(p); 
      } 


      /* Callback function to populate second menu */ 
      function createmenu(r,o,h){ 
       /* 
        r=response 
        o=options (sent by ajax function) 
        h=response headers 
       */ 
       o.menu.innerHTML=r; 
      } 



      function bindEvents(){ 
       /* Get references to the two dropdown menus */ 
       var oSelItem=document.querySelector('select[name="item1"]'); 
       var oSelService=document.querySelector('select[name="service1"]'); 


       /* Assign an `onchange` event listener */ 
       oSelItem.onchange=function(e){ 

        var method='post'; 
        var url=location.href; 

        /* the parameters to send to the PHP script */ 
        var params={ 
         'action':'get_dependant_menu', 
         'id':this.options[ this.options.selectedIndex ].value 
        }; 

        /* Options to pass to the ajax callback */ 
        var opts={ 
         menu:oSelService 
        }; 

        /* make the ajax request */ 
        ajax.call(this, method, url, params, createmenu, opts); 

       }.bind(oSelItem); 
      } 

      document.addEventListener('DOMContentLoaded', bindEvents,false); 
     </script> 

     <style type='text/css' charset='utf-8'> 
      select {padding:1rem;width:300px;} 
     </style> 
    </head> 
    <body> 
     <h1>Chained select menus using basic ajax</h1> 
     <form method='post'> 

      <select name='item1' class='country'> 
       <?php 
        /* 
         In production your code would use a database call 
         to populate the menu but for example purposes it 
         simply uses a loop 
        */ 

        for($i=1; $i <= 10; $i++)echo "<option value=$i>Item $i"; 

       ?> 
      </select> 

      <select name='service1' class='country'> 
      </select> 
     </form> 
    </body> 
</html> 

는 모르겠지만 당신들이 지속적인 아마도 탄원 후 다음은 당신에게 더 나은 아이디어를 줄 것이다. 이것은 테스트되지 않았습니다! 새로운 행이 새로 추가 된 메뉴를 선택 클로닝되지 onchange를 이벤트 핸들러가 함수 bindEvents 상기 registed Add Row 버튼을 사용하여 추가

<?php 


    if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['action'], $_POST['id']) && $_POST['action']=='get_dependant_menu'){ 
     ob_clean(); 

     $action=filter_input(INPUT_POST, 'action', FILTER_SANITIZE_STRING); 
     $id=filter_input(INPUT_POST, 'id', FILTER_SANITIZE_STRING); 

     if($action && $id && !empty($id)){ 

      $sql='select * from service where irn = :irn order by sr asc'; 
      $stmt->bindParam(':irn',$id); 
      $stmt->execute(); 

      if($stmt->rowCount() > 0){ 
       while($row=$stmt->fetch(PDO::FETCH_ASSOC)){ 
        echo "<option value='{$row['IRN']}'>{$row['Name']}"; 
       } 
      } 
     } 
     exit(); 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <title>Dependent/Chained SELECT menus</title> 
     <script type='text/javascript' charset='utf-8'> 
      function ajax(m,u,p,c,o){ 
       var xhr=new XMLHttpRequest(); 
       xhr.onreadystatechange=function(){ 
        if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders()); 
       }; 

       var params=[]; 
       for(var n in p)params.push(n+'='+p[n]); 

       switch(m.toLowerCase()){ 
        case 'post': p=params.join('&'); break; 
        case 'get': u+='?'+params.join('&'); p=null; break; 
       } 

       xhr.open(m.toUpperCase(), u, true); 
       xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
       xhr.send(p); 
      } 
      function createmenu(r,o,h){ 
       o.menu.innerHTML=r; 
      } 



      function bindEvents(){ 
       var oSelItem=document.querySelector('select[name="item1"]'); 
       var oSelService=document.querySelector('select[name="service1"]'); 
       oSelItem.onchange=function(e){ 

        var method='post'; 
        var url=location.href; 
        var params={ 
         'action':'get_dependant_menu', 
         'id':this.options[ this.options.selectedIndex ].value 
        }; 
        var opts={ 
         menu:oSelService 
        }; 
        ajax.call(this, method, url, params, createmenu, opts); 
       }.bind(oSelItem); 
      } 
      document.addEventListener('DOMContentLoaded', bindEvents,false); 
     </script> 
     <style type='text/css' charset='utf-8'> 
      select {padding:1rem;width:300px;} 
     </style> 
    </head> 
    <body> 
     <h1>Chained select menus using basic ajax</h1> 
     <form method='post'> 

      <select name='item1' class='country'> 
      <?php 

       $sql='select * from `item` order by `sr` asc;'; 
       $stmt=$user_home->runQuery($sql); 
       $stmt->execute(); 

       if($stmt->rowCount() > 0){ 
        while($row=$stmt->fetch(PDO::FETCH_ASSOC)){ 
         echo "<option value='{$row['IRN']}'>{$row['Name']}"; 
        } 
       } 

      ?> 
      </select> 
      <select name='service1' class='country'> 
      </select> 
     </form> 
    </body> 
</html> 

. & 새로 추가 된 모든 선택 메뉴가 동일한 메커니즘 (예 : 아약스)을 사용하려면 가장 쉬운 방법은 inline event handlersitem 드롭 다운 메뉴에 지정하는 것입니다. 자바 스크립트는 위의 (안 BTW 테스트)

<script type='text/javascript' charset='utf-8'> 
    /* AJAX FUNCTION */ 
    function ajax(m,u,p,c,o){ 
     var xhr=new XMLHttpRequest(); 
     xhr.onreadystatechange=function(){ 
      if(xhr.readyState==4 && xhr.status==200)c.call(this, xhr.response, o, xhr.getAllResponseHeaders()); 
     }; 

     var params=[]; 
     for(var n in p)params.push(n+'='+p[n]); 

     switch(m.toLowerCase()){ 
      case 'post': p=params.join('&'); break; 
      case 'get': u+='?'+params.join('&'); p=null; break; 
     } 

     xhr.open(m.toUpperCase(), u, true); 
     xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
     xhr.send(p); 
    } 


    /* AJAX CALLBACK */ 
    function createmenu(r,o,h){ 
     o.menu.innerHTML=r; 
    } 

    /* INLINE EVENT HANDLER */ 
    function evtselect(e){ 
     try{ 
      var el=e.target; 
      /* it is NOT necessary to have the `action` parameter... that was for testing for me initially */ 
      var params={ 
       'action':'get_dependant_menu', 
       'id':el.value 
      }; 

      /* 

       newly added nodes (add row) should have their names changed*/ 
       so the following line needs attention! Basically you need to find, in the DOM, 
       the next select menu on the same row (think parentNode, nextSibling etc etc) 

       The following is NOT tested......!!!!! 
      */ 
      var td=el.parentNode.nextSibling; 

      var opts={ 
       menu:td.querySelector('select') 
      }; 
      ajax.call(this, method, url, params, createmenu, opts); 
     }catch(err){ 
      console.log(err); 
     } 
    } 
</script> 

사용하려면 변경 될 수 inline event handler 당신이 일반적으로 할 것 :

<select name='item' onchange='evtselect(event)'>/* options */</select> 
+0

자,이 코드를 사용해야합니다. 제 코드에 따라 코드를 편집 할 수 있습니까? – BTC

+0

업데이트가 있습니까? – BTC

+0

위 코드를 실행 해 보셨습니까? 이 메커니즘은 첫 번째 드롭 다운에서 선택 기준으로 보조 드롭 다운을 채우는 장소에 있지만 정적 루프를 데이터베이스 코드로 대체해야합니다. 충분히 간단해야합니다. – RamRaider

관련 문제