2017-03-30 1 views
0

사용자가 숫자가 아닌 값을 입력하면 vticketqty를 0으로 설정하는 함수를 추가하고 싶습니다. 난 몇 가지 시도했지만 내 코드가 제대로 작동하지 않을 경우 나는 분명히 뭔가 잘못하고있어 기능을 추가합니다. Javascript - 함수를 삽입하는 데 문제가 있습니다.

내가 사용하던 기능입니다 :

function NaN(){ 
    if (isNaN(TicketQty)) TicketQty = 0; 
    } else { 
    return TicketQty 
} 

그러나 올바른 경우 잘 모르겠어요, 난 함수가 코드 내에 배치 할 위치를 완전히 확실하지 않다. 이것은 내 자바 스크립트 코드입니다. 어떤 도움을 주시면 감사하겠습니다. 대신이의

var vTicketType; 
var vTicketQty; 
var vTicketPrice; 
function calcTotal() { 
    vTicketType = prompt("Enter Ticket Type").toUpperCase(); 
    document.write("<br>"); 
    vTicketQty = prompt("Enter No. of Tickets"); 
    calcPrice(); 
    vTicketQty = parseInt(vTicketQty); 
    document.write("<br>"); 
    document.write("Type of Ticket:" + vTicketType); 
    document.write("<br>"); 
    document.write("Number of Tickets:" + vTicketQty); 
    document.write("<br>"); 
    var vTotalPayment =(vTicketPrice) * (vTicketQty); 
    if (vTotalPayment >0) { 
     document.write("Total Payment is: $" + vTotalPayment); 
     vTicketPrice = parseInt(vTicketPrice); 
    } else { 
     document.write("INVALID") 
    } 
} 



function calcPrice(){ 
    if (vTicketType == 'A') { 
     vTicketPrice = 50; 
    } else if (vTicketType == 'B') { 
     vTicketPrice = 30; 
    } else if (vTicketType == 'C'){ 
     vTicketPrice = 10; 
    } 
    else { 
     vTicketPrice = -1; 
    } 
} 
+0

'document.write를 사용하지 마십시오()' 코드에서 페이지가로드 된 후 실행됩니다. 그것은 당신의 페이지를 쓸어 버릴 것입니다. – Barmar

+0

전역 변수를 사용하지 말고, 함수 인수와 반환 값을 사용하십시오. – Barmar

답변

0

는 :

document.write("<br>"); 
vTicketQty = prompt("Enter No. of Tickets"); 
calcPrice(); 
vTicketQty = parseInt(vTicketQty); 
document.write("<br>"); 

이보십시오.

document.write("<br>"); 
while (isNaN(vTicketQty)) { 
    vTicketQty = prompt("Enter No. of Tickets"); 
    calcPrice(); 
    vTicketQty = parseInt(vTicketQty); 
    if (isNaN(vTicketQty)) { 
     alert("Quantity must be a number"); 
    } 
} 
document.write("<br>"); 

편집 - 요청으로.

document.write("<br>"); 
vTicketQty = prompt("Enter No. of Tickets"); 
calcPrice(); 
vTicketQty = parseInt(vTicketQty); 
if (isNaN(vTicketQty)) { 
    vTicketQty = 0; 
} 
document.write("<br>"); 

편집을 할 -

1 같은 더 기능)

document.write("<br>"); 
calcPrice(); 
vTicketQty = getQty(); 
document.write("<br>"); 

function getQty() { 
    qty = parseInt(prompt("Enter No. of Tickets")); 
    if (isNaN(qty)) { 
     return 0; 
    } 
    return qty; 
} 

2)

document.write("<br>"); 
vTicketQty = prompt("Enter No. of Tickets"); 
calcPrice(); 
vTicketQty = checkNaN(parseInt(vTicketQty)); 
document.write("<br>"); 


function checkNaN(qty) { 
    if (isNaN(qty)) { 
     return 0; 
    } 
    return qty; 
} 
+0

고마워,이 작품을하지만, 내가 promptqty 루프에 설정된 프롬프트보다는 0으로 설정하고 싶습니다. 이 작업을 수행하는 간단한 방법이 있습니까? – Mithrandir

+0

내 게시글을 편집했습니다. 그래서 두 가지 해결책이 있습니다. 당신이 필요로하는 해결책과 다른 사람이 비슷한 문제가있을 때 선호하는 원래의 것. – noyanc

+0

감사합니다. 기능을 만드는 방법이 있습니까? – Mithrandir

관련 문제