2012-07-20 2 views
1

나는 잃어 버렸습니다. 여기에 몇 시간 동안 뇌를 부숴 버린 후, 여기에 질문을 던져야 할 때입니다.Javascript로 확인란을 사용하여 양식 요소를 사용/사용 중지하는 방법은 무엇입니까?

확인란을 선택하면 일부 양식 요소가 활성화되고 체크하지 않으면 해당 요소가 다시 비활성화되는 일부 자바 스크립트 코드가 실행됩니다.

<form id="orderform" style="margin-left: 6cm"> 
<input type="checkbox" name="cleaning" value="yes" onclick="houseclean()"/> Home cleaning <br /> 
Service: <select name="rooms" id="rooms" disabled > 
    <option value="1bedroom">One Bedroom Apt</option> 
    <option value="2bedroom">Two Bedroom Apt</option> 
    <option value="3bedroom">Three Bedroom Townhome or SF Home</option> 
    <option value="4bedroom">Four Bedroom Home</option> 
    <option value="5bedroom">Five Bedroom Home</option> 
    <option value="6bedroom">Six Bedroom Home</option> 
</select> <br /> 
Date/Time: <input type="text" name="datetime" disabled /><br /> 
How often would you like a cleaning?: <select name="howoften" disabled> 
    <option value="once">One Time Only</option> 
    <option value="2bedroom">Every Week</option> 
    <option value="3bedroom">Every Other Week</option> 
    <option value="4bedroom">Once a Month</option> 
</select> <br /> 
</form> 
+1

무엇이 잘못 되었나요? –

+0

오류가 무엇인지 자세히 설명해주십시오. 이걸로 나는 document.orderform.blah를 추측 할 수 있습니다.disabled는 실제로 당신이 원하는 것이 아니며 아마도 jQuery를 사용할 것인가? 아니면 onclientclicked하고 싶습니까? –

답변

2

이 코드는 트릭을 할 것입니다 : 내 HTML 코드는 여기

function houseclean() 
{ 
if (document.orderform.cleaning.checked == true) 
    { 
    document.orderform.rooms.disabled = false; 
    document.orderform.datetime.disabled = false; 
    document.orderform.howoften.disabled = false; 
    } 
else 
    { 
    document.orderform.rooms.disabled = true; 
    document.orderform.datetime.disabled = true; 
    document.orderform.howoften.disabled = true; 
    } 
} 

을 그리고 :

여기에 내가 가지고있는 자바 스크립트입니다. 가능한 경우 요소 ID 및 getElementById를 명시 적으로 사용해야합니다.

html로 :

<form id="orderform" style="margin-left: 6cm;"> 
<input type="checkbox" id="cleaning" name="cleaning" value="yes" onclick="javascript:houseclean();"/> Home cleaning <br /> 
Service: <select name="rooms" id="rooms" disabled > 
    <option value="1bedroom">One Bedroom Apt</option> 
    <option value="2bedroom">Two Bedroom Apt</option> 
    <option value="3bedroom">Three Bedroom Townhome or SF Home</option> 
    <option value="4bedroom">Four Bedroom Home</option> 
    <option value="5bedroom">Five Bedroom Home</option> 
    <option value="6bedroom">Six Bedroom Home</option> 
</select> <br /> 
Date/Time: <input type="text" id="datetime" name="datetime" disabled /><br /> 
How often would you like a cleaning?: <select id="howoften" name="howoften" disabled> 
    <option value="once">One Time Only</option> 
    <option value="2bedroom">Every Week</option> 
    <option value="3bedroom">Every Other Week</option> 
    <option value="4bedroom">Once a Month</option> 
</select> <br /> 
</form>​ 

그리고 자바 스크립트 :

function houseclean() 
{ 
if (document.getElementById('cleaning').checked == true) 
    { 
    document.getElementById('rooms').removeAttribute('disabled'); 
    document.getElementById('datetime').removeAttribute('disabled'); 
    document.getElementById('howoften').removeAttribute('disabled'); 
    } 
else 
    { 
    document.getElementById('rooms').setAttribute('disabled','disabled'); 
    document.getElementById('datetime').setAttribute('disabled','disabled'); 
    document.getElementById('howoften').setAttribute('disabled','disabled'); 
    } 
} 

JSFiddle 예 : http://jsfiddle.net/HQQ4n/10/

+0

왜이 downvoted했다?! – Adi

+0

@RabNawaz, 당신은'document.ElementId.AnotherId'로 선택할 수 없다는 것을 알고 있습니까? – Adi

+0

여기서 중요한 것은 내 코드가 작동하며 OP 코드가 아닙니다. 대신'getElementById'를 사용하는 것은 항상 작동한다는 것입니다. – gcochard

1

나는 작동하도록 코드를 얻었다. 양식 요소에 id 속성을 추가하고 document.getElementById을 안전한쪽에 사용했습니다.

JFiddle 예 : http://jsfiddle.net/vxRjw/1/

-1

매우 강력하지만 동적 JQuery와 용액 없음 ...

$("#mycheckbox").click(function() { 
    enableFormElements("#myform", $(this).attr('checked')); 
}); 

function enableFormElements(form, enable) { 
     var fields = ["checkbox","textarea","select"]; 
     var selector = form+" input"; 
     $.each(fields, function(i,e) { selector += ","+form+" "+e; }); 
     $(selector).each(function(idx) { 
      if (enable) { 
       $(this).removeAttr("disabled"); 
       $(this).removeAttr("readonly"); 
      } else { 
       $(this).attr("disabled","disabled"); 
       $(this).attr("readonly","readonly"); 
      } 
      if ($(this).is("select") || $(this).is("textarea")) { 
       var id = $(this).attr("id"); 
       var txt_equiv = id+"_text"; 
       var val = $(this).find("option[value='"+$(this).val()+"']").text(); 
       // dynamically add the span to this element...so you can switch back and forth... 
       if ($(this).parent().find("span").length == 0) { 
        $(this).parent().append("<span class='record_display_text' id='"+txt_equiv+"'>"+val+"</span>"); 
       } 
      } 
      if ($("#"+txt_equiv).length != 0) { 
       if (enable) { 
        $("#"+id).show(); 
        $("#"+txt_equiv).hide(); 
       } else { 
        $("#"+txt_equiv).show(); 
        $("#"+id).hide(); 
       } 
      } 
     }); 
} 

함수는 기본적으로 모든 입력을 찾는다

, 선택은 텍스트 영역을 제공하는 요소와 비활성화 또는 내부에 발견 각각을 가능하게합니다. JQuery 1.9를 사용하는 경우, 설정을 소품으로 변경하려고 할 수 있습니다. 그러나 모든 브라우저가 아직 일관되게 작동하지는 않습니다. (bleh). 텍스트 영역이나 선택의 경우 실제로는 입력 뒤에 "_text"를 제외하고 입력과 일치하는 ID가있는 관련 범위를 만듭니다. 페이지에 충돌 할 수있는 다른 ID가있는 경우 해당 ID를 편집하고 싶을 수 있지만 그 자리에두면 텍스트 또는 실제 select/textarea를 숨기거나 표시 할 수 있습니다. 또는 장애인. 다시 말하지만 모든 상황에서 테스트하지는 않지만 자유롭게 복사 및 편집 할 수 있습니다.

아, 모든 선택 사항이나 텍스트 영역이 부모에게 유일한 자식인지 확인하십시오. if span 당신은 동적으로 같은 부모 내에서 관련된 스팬을 추가하기 때문에 ... 그래서 선택이나 텍스트 영역이 스팬, div 또는 td 또는 무언가와 같은 부모에 래핑되지 않는다면, 생성 된 텍스트는 어딘가에 무작위로 분포합니다. : P

을 그리고 당신은

input[readonly], 
    select[readonly], 
    textarea[readonly] { 
     cursor: default; 
    } 

    input[disabled] { 
     background-color:#F0F0F0; 
     border:none; 
     -moz-box-shadow: none; 
     -webkit-box-shadow:none; 
     box-shadow:none; 
     padding: 0; 
    } 

당신은 아마 일치하는 배경 색상을 변경할 것입니다 ... 폼 요소가 더 정상적인 페이지 또는 표준 범위 요소처럼 보이게하기 위해 일부 CSS를 추가 할 수 있습니다 페이지 색상 ... 그리고 "커서 : 기본"하나는 부트 스트랩 트위터가 성가신 "제한된"커서를 추가했거나 사용할 수없는 요소를 넘어서는 것입니다.하지만 어쨌든 이것은 오늘 저녁에 생각해 낸 해결책입니다. 나를 위해 일해. :)

+0

OP가 jQuery를 사용하지 않는다면 당신의 대답은 거의 쓸모 없게됩니다. 바로 JavaScript 솔루션을 제공해야합니다. – Pavlo

관련 문제