2015-01-27 2 views
0

책의 이름을 가져 와서 데이터베이스에서 가격을 가져 와서 그 결과를 테이블에 넣는 입력 필드가 있습니다.JavaScript로 숫자를 늘리는 문제

이제 책이 두 번 이상 선택되면 수량을 늘리고 그 책의 가격을 표시하고 싶습니다.

<div> 
    <input type="text" id="book_item" value="<?php echo $books['book_name']; ?>"/> 
    <input type="button" id="addbook" value="Apply" onclick="addBookToTable()" />   
</div> 

<table id="booktable"> 
    <thead> 
     <tr> 
     <th>Book Name</th> 
     <th id="quantity">Quantity</th> 
     <th>Price</th> 
     <th>Remove Book</th> 
     </tr> 
    </thead> 

    <tfoot> 
     <tr> 
     <td>Total</td> 
     <td></td> 
     <td id="price"></td> 
     <td></td> 
     </tr> 
    </tfoot> 
</table> 

<script> 
    var quantity = $("#quantity").children('td').eq(1).text(); 

    // not sure how to check if the book is already in the table or not 
    // if it is, then it should just show the name of the book 
    // only one time and increase the quantity number. 
<script> 

나는이 문제를 해결할 수있는 코드 샘플이나 의견을 주셔서 감사합니다 : 여기

는 코드입니다.

+0

'$ ("quantity")'를 선택하면''요소를 얻을 수 있으므로'td' chiildren을 찾을 수 없습니다. 먼저 parent (예 :'$ ("# quantity"). parent ('table')'를 찾아서 tbody와 tr 또는 td를 찾으십시오. – szapio

답변

0

데이터베이스 결과 만 표시하면 자바 스크립트 클라이언트 측을 사용할 필요가 없으므로 원래 배열을 검사 한 다음 클라이언트 측에서 표시 할 테이블을 생성해야합니다.

대신에 즉석에서 책을 추가하는 경우 (상단의 입력 내용이 제안 된 것처럼 보임)이 작업을 수행하는 가장 좋은 방법은 "addBookToTable"절차를 수정하여 전체 표를 확인하도록하는 것입니다 그 이름을 가진 책이 이미 있고 결국에는 새로운 줄을 추가하는 대신 수량을 올립니다.

편집 :

음, 책을 특정 순서대로하지 않는 한 전체 목록의 선형 검색 돌아가는 없다 :

$('#booktable tr').each(function() { 
    var children = $(this).children('td'); 
    if(children.length > 1) { 
    if(children.first().text() == MyNewBookTitle) { 
     var quantityChild = $(children[1]); 
     quantityChild.text(parseInt(quantityChild.text()) + 1); 
    } 
    } 
}); 

참고가 ID를 "사용하지 말아야 ID는 고유해야하기 때문에 td에서 '가격' 또한

, 당신이 필터를 사용할 수 위의 코드에서 그래서 당신이 당신의 TDS 클래스 이름을 제공해야합니다 first() 또는 children[1] 사용의 어색함을 피하기 위해 :

children.filter('.title') 

children.filter('.quantity') 
+0

사실 당신은 맞습니다. 테이블 하나씩 addBookToTable 함수. 이제 나는 책 이름이 존재하는지 확인하기 위해 테이블을 확인하는 방법을 모른다. JavaScript 코드 제안이나 도움이되는 페이지가 있습니까? 고맙습니다. – Irfana

+0

내 프로그램에 제안 된 코드를 적용했지만 불행히도 아직 작동하지 않는 것 같습니다. – Irfana

+0

문제를 자세히 설명하고 문제를 재현하는 jsFiddle을 제공하십시오. –

0

을 이 선택기를 사용할 수 있습니다.

var bookName="any bookName " ; 
    var theBookTD = $("#booktable tr td:nth-child(1):contains('"+ bookName+"')"); 

if (theBookTD.length>0) { 
//the book already exists in table 
    var theBookQuantity = theBookTD.next().first().text(); 
}else { 
// the book doesn't exist in table; 
} 

여기를보십시오 http://jsfiddle.net/buuk2zjf/3/

+0

코드에서 ('Book Name')은 무엇입니까? 데이터베이스에서 오는 책 이름의 거대한 목록이 있기 때문에 책 이름이 동적이어야합니다! – Irfana

+0

var bookName = "모든 bookName"; $ ("booktable tr td : nth-child (1) : contains ('"+ bookName + "')"); –

+0

내가 제안한 샘플 코드를 시도했지만 내 테이블에서 작동하지 않는 것 같습니다. – Irfana

관련 문제