2014-04-12 5 views
1

나는 스택 오버 플로우시 새로운 기능을 제공합니다. 정적 드롭 다운을 만든 다음 정적 드롭 다운에서 선택한 값에 따라 동적 드롭 다운을 만들어야합니다. 그냥 coldfusion 및 HTML. 다른 멋진 것들. 첫 번째 드롭 다운에서 사용자는 color, id, officer, school을 선택했습니다. "계속"버튼정적 드롭 다운에서 동적 드롭 다운 Coldfusion

같은 페이지에서 또는 다른 색상에서 데이터베이스를 쿼리하면 다른 색상에 대한 결과를 출력 할 때 id가 선택되면 쿼리의 ID 번호 목록을 제공합니다. 그러한 변수가 선택되면 장교 나 학교에서 똑같이 적용됩니다.

드롭 다운 상자를 사용하여 쿼리를 가져올 수 있지만 프리스트 드롭 다운 상자에서 쿼리 결과를 얻는 데 어려움이 있습니다. 다음은 내 코드입니다 : 당신은 종속 드롭 다운 값에 대한 각각의 선택과 다시 쿼리 후 페이지를 다시 제출하지 않는 한

<cfform method="POST" action=""> 
<select name="dropDownOne" required="yes" onchange="this.form.submit()"> 
<option>Select Report Type</option> 
<option value="color">Color</option> 
<option value="id">ID</option> 
<option value="officier">officier</option> 
<option value="school">school</option> 
</select> 

<input type="Submit" name="Continue" value="Continue"> 
<cfif isDefined('form.selectType')><cfif form.dropDownOne eq "color"> 
    <option>Select Color</option> 
    <cfloop query="colorlist"> 
    <option value="#color_id#" 
<cfif isDefined('form.selectcenter')> 
<cfif form.selectcenter eq "#color_id#">selected</cfif></cfif>>#color#</option> 
    </cfloop> 
+0

cfselect의 바인드 속성이이를 수행하는 가장 쉬운 방법입니다. 이 태그의 문서에는 예제가 있습니다. –

+0

양식 제출을 처리 할 때 드롭 다운 상자에서 선택한 항목의 값을 가져 오는 방법을 묻는 중입니까? 그렇다면 form.dropDownOne이됩니다. –

+0

질문과 관련이 없지만 선택 이벤트가 onchange 인 양식을 제출하면 특히 사용자가 키보드를 사용하는 경우 부주의 한 양식 제출이 발생할 수 있습니다. –

답변

2

, 당신은 클라이언트 측 JS 및/또는 아약스의 어떤 종류를 사용해야합니다.

나는 그것이 당신이하고있는 것처럼 보이기 위해 노력하고있는 것이라고 생각합니다. 당신이하려고하는 것이 너무 분명하지 않습니다; 당신이 선택하고 자동적으로 변화하는 것을 반영하도록 종속 드롭 다운을 원합니까?

그래서 골라서 뽑아 제출 한 내용에 따라 가능한 모든 드롭 다운을 감싸는 경우 커야합니다. 그리고 왜 사용자는 한 번에이 중 하나만 선택할 수 있습니까? 이것은 코드 작성이 매우 번거롭고 성가신 인터페이스처럼 보입니다.

이것은 cfselect을 사용하여 연결하는 방법을 보여줄 것입니다.하지만이 방법을 조금 이상하게 생각하는 것 같습니다. 당신은 각 조각을 제외하고 그것을 보여 주거나 그것을 어딘가에 사용할 것입니까? 아니면 이것은 개념의 증거일까요?

그리고 나는 항상 모든 물건을 항상 표시 할 것입니다. 자동차 선택자 (Year, Make, Model, Trim 레벨)와 같은 것들은 종속 드롭 다운이 더 적합합니다. 각 변수는 이전 값에 고유하게 종속됩니다. 당신이 물어 본 질문에서 당신이 무엇을 구부리고 있는지 확실하지 않습니다.

어쨌든 ColdFusion에는 <cfselect>이 있습니다.이 코드는 자동으로 연결되지만, 개인적으로 jQuery/Ajax를 사용합니다.

태그를 사용하여 수행하는 방법은 다음과 같습니다. 1) 변경시 양식을 제출하지 마십시오. 2) cfselect를 사용하여 드롭 다운을 연결합니다. 3) 바인딩이 작동하도록 원격으로 액세스 할 수있는 쿼리를 호출하는 메서드가 있어야합니다. 여기

<cfif isDefined('Form.DropDownOne')> 
    <!--- Do some action here ---> 
    <cfdump var="#form#"> 
</cfif> 


<cfform> 
    <label>Select A Report</label> 
    <cfselect name="dropDownOne" id="dropDownOne" required="yes" 
     <!--- The display attribute will map the "name" column to the option display text area ---> 
     <!--- The value attribute will map "value" column to the option value (what is submitted)---> 
     display='name ' value='value' 
     <!--- The cfc should send back a query with name and value columns. ---> 
     <!--- The dot path should point to the location of the cfc. ---> 
     bind="cfc:com.app.code.myDropDowns.getCategories()" bindonload="true"> 
     <option>Select Report Type</option> 
    </cfselect> 
    <label>Select A Value</label> 
    <cfselect name="dropDownTwo" id="dropDownTwo" required="yes" 
     display='name' value='value' 
     <!--- This method takes the value from the other drop down. ---> 
     <!--- CF uses {} to denote the binding of the element to pass through. ---> 
     <!--- This binding will occur automatically on any change to the dropDownOne element (including load). ---> 
     bind="cfc:com.app.code.myDropDowns.getDetails({dropDownOne})" > 
     <option>Stuff</option> 
    </cfselect> 
    <input type="Submit" name="Continue" value="Continue"> 
</cfform> 

나는 손으로 내장 쿼리를 반환하는 myDropDowns.cfc (난 당신이 원하는대로, 단지에 쿼리를 반환 데이터를 저장하는 곳 방법/알, 진짜 쿼리 스왑하지 않는했다 요청 : 여기

component output="false" persistent="false" displayname="myDropDowns" { 

    structAppend(variables, Application.Seq.Objects.oCore.injectCoreMethods()); 

    remote function getCategories() { 
     var q = queryNew(''); 
     queryAddColumn(q,'name',['Select Report Type','Color','ID', 'Officer', 'School']); 
     queryAddColumn(q,'value',['Select Report Type','Colors','IDs', 'Officers', 'Schools']); 
     return q; 
    } 

    remote function getDetails(required string Category) { 
     var q = queryNew(''); 
     if(Arguments.Category == 'Colors') { 
      queryAddColumn(q,'name',['Select Value','Red','Green','Blue', 'Yellow', 'Purple']); 
      queryAddColumn(q,'value',['','Red','Green','Blue', 'Yellow', 'Purple']); 
     } else if(Arguments.Category == 'IDs') { 
      queryAddColumn(q,'name',['Select Value','123','456','789', '1011', '978']); 
      queryAddColumn(q,'value',['','123','456','789', '1011', '978']); 
     } else if(Arguments.Category == 'Officers') { 
      queryAddColumn(q,'name',['Select Value','Johnson','Fredricks','Oppenheimer', 'Davis', 'Smith']); 
      queryAddColumn(q,'value',['','Johnson','Fredricks','Oppenheimer', 'Davis', 'Smith']); 
     } else if(Arguments.Category == 'Schools') { 
      queryAddColumn(q,'name',['Select Value','Central','Northridge','Fairview', 'Daring', 'South']); 
      queryAddColumn(q,'value',['','CJH','NRJH','FHS', 'DHS', 'SHS']); 
     } else { 
      queryAddColumn(q,'name',['Select A Report Type First']); 
      queryAddColumn(q,'value',['Yeah, do that']); 
     } 
     return q; 
    } 

} 

당신이 손 코딩 것과 같은 스타일 쿼리를 반환해야합니다 귀하의 테이블을 가리 키도록 수정할 수 고양이/목록 방법에 싸여 쿼리의 커플 당신의 database.tablename과 열을 대체합니다. 물론 이름도 있습니다.

remote function getCats() { 
     var q = queryNew(''); // Create empty query, not really nec. Just to initiate as query type. 
     var oQ = new Query(); // Create query object to execute query against your DB 
     try { // I like to use try-catches, make it easier to figure out what is going on sometimes.... 
      /* You don't have to set the datasource if you set it in the Application for CF9+*/ 
      oQ.setDataSource('myDataSource'); 
      // Query name is only really needed if caching or requerying as it becomes part of your cache signature 
      oQ.setName('qMyQueryCategories'); 
      oQ.setCachedWithin(1); // 1 == 1 day/24 hours, .5 = 12 hours, etc) 
      oQ.setSQL(" 
       SELECT 
        T1.Id, 
        T1.DisplayName AS Name, 
        T1.Category AS Value 
       FROM yourDB.yourCatTableHere T1 
      "); 
      q = oQ.Execute().getResult(); 
      return q; 
     } catch (any err) { 
      /* 
      * Returning the error will allow you to debug in the case you have a bad query. 
      * You can see the result in your F12 debug network tool. 
      * You could optionally call an error handler to log/email the error 
      * but then return the empty query to the UI request so it sort of keeps functioning... 
      * */ 
      return err; 
     } 
    } 

    remote function getList(required string Category) { 
     var q = queryNew(''); 
     var oQ = new Query(); 
     try { 
      oQ.setName('qMyQuery#Arguments.Category#'); 
      oQ.setCachedWithin(.04); // Approximately 1 hour (1/24=.0417) 
      oQ.setSQL(" 
       SELECT 
        T1.Id, 
        T1.Category AS Cat, 
        T1.DisplayName AS Name, 
        T1.ValueKey AS Value 
       FROM [yourDB.yourDetailTableNameHere] T1 
       WHERE T1.Category = ? ; 
      "); 
      // Parameterize your sql variable. CF will take care of quoting it properly, etc. 
      oQ.AddParam(value=Arguments.Category, cfsqltype='CF_SQL_VARCHAR'); 
      q = oQ.Execute().getResult(); 
      return q; 
     } catch (any err) { 
      return err; 
     } 
    } 

바인딩에서 호출하는 메소드 이름이 각 메소드에 사용하는 메소드 이름과 일치하는지 확인하십시오.

+0

첫째, 감사합니다 @ Williambq 데이터는 SQL 서버 데이터베이스에 저장됩니다. 예, 인터페이스가 약간 번거롭다는 것을 이해하지만 그것이 선택되었습니다. 그럼 프리스트는 목록에서 한 번 드롭 다운합니다. 그런 다음 계속 버튼을 누릅니다. 그 후 선택에 따라 데이터베이스에서 쿼리가 실행됩니다. 예를 들어 누군가가 첫 번째 드롭 다운 메뉴에서 색상을 선택하면 "빨강, 파랑, 오렌지 등"을 볼 수 있습니다. 두 번째 드롭 다운 메뉴에 옵션이 표시됩니다. 말이 돼? 또한 거기에 들어가는 쿼리의 예를 몇 가지 알려 주실 수 있습니까? – user3527285

+0

@ user3527285 SQL 쿼리가 어떻게 표시되는지에 대한 대답이 업데이트되었습니다. 본질적으로 세부 쿼리에 범주 값을 전달합니다. – williambq