2017-01-03 1 views
3

두 개의 테이블 행에는 각각 <td>에있는 3 개의 확인란이 있습니다.여러 테이블 행의 여러 확인란에서 값 가져 오기

체크 박스가 선택된 특정 규칙에 따라 해당 행에 네 번째 <td>을 표시하려고합니다. 각 행은 다음과 같이이다 :

HTML

<tr class="tableRow"> 
    <td> 
     <input class="select" class="select" type="checkbox" value="select"/> 
    </td> 
    <td> 
     <input class="voice" class="voice" type="checkbox" value="voice"> 
    </td> 
    <td> 
     <input class="mail" class="mail" type="checkbox" value="mail"/> 
    </td> 

    <!--The <td>'s i want the results of the checkboxes to show --> 
    <td class="initial-cost">Initial cost</td> 

    <td class="voicemail-and-initial-cost">VoiceMail and Initial Cost</td> 

    <td class="email-and-initial-cost">Email and Initial Cost</td> 

    <td class="all-services-cost">All Services Cost</td> 
</tr> 

내가 좀 일이 jQuery를 가지고 있지만 모든 테이블 행을 '이다'... 비용 '의 오히려 각 행보다 개별적으로 jQuery를

$(document).ready(function() {     //on page load.... 
$(".voicemail-and-initial-cost").hide(); //hide all cost elements 
$(".email-and-initial-cost").hide();  //hide all cost elements 
$(".all-services-cost").hide();    //hide all cost elements 


$(".select").change(function(event) {    //when #select is clicked... 
    if ($(this).is(":checked")) {     //if this checkbox has been checked... 
     $(".initial-cost").show();     //show .initial-cost element 
    } else {          //otherwise... 
     $(".voicemail-and-initial-cost").hide(); //hide all cost elements 
     $(".email-and-initial-cost").hide();  //hide all cost elements 
     $(".all-services-cost").hide();    //hide all cost elements 
    } 
}); 

$(".voice").change(function(event) {     //when #voice is clicked... 
    if ($(this).is(":checked")) {      //if this checkbox has been checked... 
     if ($('.mail').is(":checked")) {    //check to see if #mail is checked too and if it is... 
      $(".initial-cost").hide();     //hide .initial-cost 
      $(".voicemail-and-initial-cost").hide(); //hide .voicemail-and-initial-cost 
      $(".email-and-initial-cost").hide(); 
      $(".all-services-cost").show();   //show .all-services-cost 
     } else {          //but if #mail is not checked.... 
      $(".initial-cost").hide();     //hide .initial-cost 
      $(".voicemail-and-initial-cost").show(); //show .voicemail-and-initial-cost instead 
     } 
    } else {                   //otherwise if this checkbox is not checked... 
     if(($('.select').is(":checked")) && ($('#mail').is(":checked"))){    //and .select AND .mail is checked however... 
      $(".initial-cost").hide();             //hide .initial-cost 
      $(".all-services-cost").hide();            // hide .all-services-cost 
      $(".email-and-initial-cost").show();          //show .email-and-initial-cost instead 
     } else if (($('.select').is(":checked")) && (!$('.mail').is(":checked"))){  //otherwise if #select is checked AND #mail is NOT checked.... 
      $(".voicemail-and-initial-cost").hide(); 
      $(".initial-cost").show(); 
     } 
    } 
}); 

$(".mail").change(function(event) {      //when #mail is clicked... 
    if ($(this).is(":checked")) {      //if this checkbox has been checked... 
     if ($('.voice').is(":checked")) {    //check to see if #voice is checked too and if it is... 
      $(".initial-cost").hide();     //hide .initial-cost 
      $(".voicemail-and-initial-cost").hide(); //hide .voicemail-and-initial-cost 
      $(".email-and-initial-cost").hide();  //hide .email-and-initial-cost 
      $(".all-services-cost").show();   //show .all-services-cost 
     } else {          //but if #voice is not checked.... 
      $(".initial-cost").hide();     //hide .initial-cost 
      $(".email-and-initial-cost").show();  //show .email-and-initial-cost instead 
     } 
    } else {                   //otherwise if this checkbox is not checked... 
     if(($('.select').is(":checked")) && ($('.voice').is(":checked"))){    //and #select and #voice is checked however... 
      $(".all-services-cost").hide();            // hide .all-services-cost 
      $(".voicemail-and-initial-cost").show();         //show .voicemail-and-initial-cost 
     } else if (($('.select').is(":checked")) && (!$('.voice').is(":checked"))){  //if this checkbox is not checked AND #voice is NOT checked... 
      $(".all-services-cost").hide();            // hide .all-services-cost 
      $(".voicemail-and-initial-cost").hide(); 
      $(".email-and-initial-cost").hide(); 
      $(".initial-cost").show();          //show .initial-cost instead 
     } 

    } 
}); 
}); //end of ready 

은 지금은 단지 요소를 대상으로 생각

$(".initial-cost").hide(); 

같은으로 : -에서조차 오류 메시지를

$('td').next(':has(.initial-cost):first').hide(); 

하지만 지금은 모든 일이 아무것도 얻을 여기에 무슨 문제 행, 나는에서 JQuery와 선택기를 변경해야 콘솔.

규칙 자체가 문제가 아니라 사실 그 규칙이 표 행당 적용되는 것이지 모든 항목을 한꺼번에 적용하지 않기를 바랍니다. 나는 이것이 의미가 있고 누군가가 저를 올바른 방향으로 향하게하기를 바랍니다. 여기 나는 그것이 도움이 될 것입니다 무슨의 JSfiddle입니다 :이 같은 https://jsfiddle.net/monkeyroboninja/5n0v0eL5/

+0

ID는 문서에 고유해야합니다. 해당 테이블 행이 실제로 반복되는 경우 유효하지 않은 HTML이 있으며 실행중인 코드가 작동하지 않습니다. 대신 클래스 및 이벤트 위임을 사용하십시오. –

+0

아하, ID에 대해 지금 수정 중입니다. – Liam

답변

3

변화 라인 :

$(".initial-cost").show(); 

$(this).parents('.tableRow').find(".initial-cost").show(); 

으로 올바르게과 같은 행에 다른 요소를 대상으로 변경된 체크 박스 요소.

1

이것이 내가하는 일입니다. 나는 단지 필수적인 것을 게시한다.

데이터 속성을 사용하여 데이터를 읽습니다. 많은 다른 트릭이 있지만, 나는 이것을 좋아합니다.

(주의 사항, Jamiec는 동일한 원리를 사용하여 부모를 찾아, ...)

<style> 
    td.apples, td.pears, td.lemons { 
    visibility: hidden; 
    } 
</style> 
<table> 
    <tr> 
    <td> 
     <input class="check" data-fruit="apples" type="checkbox"> apples 
    </td> 
    <td> 
     <input class="check" data-fruit="pears" type="checkbox"> pears 
    </td> 
    <td> 
     <input class="check" data-fruit="lemons" type="checkbox"> lemons 
    </td> 
    <td class="apples"> 
     I like apples 
    </td> 
    <td class="pears"> 
     I like pears 
    </td> 
    <td class="lemons"> 
     I like lemons 
    </td> 
    </tr> 
    <tr> 
    <td> 
     <input class="check" data-fruit="apples" type="checkbox"> apples 
    </td> 
    <td> 
     <input class="check" data-fruit="pears" type="checkbox"> pears 
    </td> 
    <td> 
     <input class="check" data-fruit="lemons" type="checkbox"> lemons 
    </td> 
    <td class="apples"> 
     I like apples (2) 
    </td> 
    <td class="pears"> 
     I like pears (2) 
    </td> 
    <td class="lemons"> 
     I like lemons (2) 
    </td> 
    </tr> 
</table> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script> 
    $(document).ready(function() { 
    // event. click on one of the checkboxes 
    $('.check').change(function(e) { 
     // on or off? 
     var on_off = $(this).is(":checked") ? true : false; // heredoc notation 
     // we read the data-fruit attribute 
     var fruit = $(this).data('fruit'); 
     // now we want to know which row this is, so we find the parent 
     var parent_row = $(this).parents('tr'); 
     // we have the parent, so we can look for children that have the same class as the data-fruit 
     var cel = parent_row.find('.' + fruit).css('visibility', on_off ? 'visible' : 'hidden'); 
    }) 
    }) 
</script> 
2

당신은 과감하게 체크 박스 상태의 '규칙'을 인코딩하여 코드를 단순화 할 수 있습니다. 당신은 8 (2^3) 가능성을 제공하는 3 개의 체크 박스를 가지고 있습니다. 이 모든 것들을 객체 리터럴에서 캡처하고 이벤트 핸들러에서 참조 할 수 있습니다.

이벤트 핸들러는 상태 변경 만 확인하면됩니다. 국가를 재 계산하라. 개체를 확인하여 표시 할 내용을 확인하십시오.

개별 행에서 작업하려면 변경된 <input>에 가장 가까운 <tr>이 있어야합니다.

그래서 코드는 다음과 같이 단순화 할 수 있습니다

var userOptionState = { 
 
    0: 'No cost', 
 
    1: 'Initial cost', 
 
    2: 'Voice cost', 
 
    3: 'Initial and voice cost', 
 
    4: 'Mail cost', 
 
    5: 'Initial and mail cost', 
 
    6: 'Voice and mail cost', 
 
    7: 'Initial and voice and mail cost' 
 
}; 
 

 
$(document).ready(function() { 
 
    $(".select, .voice, .mail").change(function(event) { 
 
    var sum = 0; 
 
    var row = $(this).closest('tr'); 
 
    if(row.find('td input.select').is(':checked')) {sum += 1} 
 
    if(row.find('td input.voice').is(':checked')) {sum += 2} 
 
    if(row.find('td input.mail').is(':checked')) {sum += 4} 
 
    row.find('td.out').html(userOptionState[sum]); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table> 
 
    <tbody> 
 
    <tr class="tableRow"> 
 
     <td> 
 
     <input class="select" type="checkbox" value="select" /> 
 
     </td> 
 
     <td> 
 
     <input class="voice" type="checkbox" value="voice"> 
 
     </td> 
 
     <td> 
 
     <input class="mail" type="checkbox" value="mail" /> 
 
     </td> 
 
     <!--output td --> 
 
     <td class="out">No cost</td> 
 
    </tr> 
 
    <tr class="tableRow"> 
 
     <td> 
 
     <input class="select" type="checkbox" value="select" /> 
 
     </td> 
 
     <td> 
 
     <input class="voice" type="checkbox" value="voice"> 
 
     </td> 
 
     <td> 
 
     <input class="mail" type="checkbox" value="mail" /> 
 
     </td> 
 
     <!--output td --> 
 
     <td class="out">No cost</td> 
 
    </tr> 
 
    </tbody> 
 
</table>

+0

이것은 달성 할 수있는 확실한 방법입니다 - 나는 범위 지정 부분 만 제공하는 게으름이었습니다. 이것은 훌륭한 대답입니다. – Jamiec

+0

이것은 정말 멋지지만 나중에 출력 내에서 PHP 쿼리 결과를 넣으려고합니다 . 나는 당신의 방법을 시도하고 PHP 쿼리는 예상대로 @ Jamiec의 응답과 같이 작동하지 않을 것이다. 왜 이렇게되는지 나는 잘 모르겠다. PHP는 'userOptionState'변수에 PHP를 넣어야하는 기존 방식으로 사전로드되어 있기 때문에 생각합니다. 그러나 나는 당신의 대답에서 무언가를 배웠다. 나는 미래에 내가 비슷한 일을 할 것이라고 생각한다. 나는 분명히 더 유선형이고 단순해진이 방법으로 그렇게하려고 노력할 것이다. – Liam