2013-10-03 54 views
1

我寫了一個jQuery腳本,可以自動檢測用戶輸入的號碼。如果用戶輸入了2,4,6,8,10 - 他們會自動彈出一個確認框,指出有報價。Onfocus和離焦文本框

如果他們點擊是,他們會被重定向。但是,如果他們單擊取消,它會將焦點重新放回文本框,並再次出現確認框。

是否有反正我可以做到這一點,如果用戶點擊取消,焦點關閉文本框,所以沒有確認框的循環發生。

HTML

<input type="text" class="Quantity" id="Quantity9438851" name="Quantity" value="1" style="width:30px"> 

JQUERY

$("#Quantity9438851").bind("change paste keyup", function() { 
    if($(this).val() == 2){ 
    var didConfirm = confirm("There is currently an offer for 2 polo shirt for £25. Click YES to recieve discount."); 
     if (didConfirm == true) { 
     window.location.href = "http://blahblah.com/&Quantity=10"; 
     } 
    }else if($(this).val() == 4){ 
    var didConfirm = confirm("There is currently an offer for 4 polo shirt for £50. Click YES to recieve discount."); 
     if (didConfirm == true) { 
     window.location.href = "http://google.com/Registration/blah"; 
     }   
    }else if($(this).val() == 6){ 
    var didConfirm = confirm("There is currently an offer for 6 polo shirt for £75. Click YES to recieve discount."); 
     if (didConfirm == true) { 
     window.location.href = "http://google.com/Registration/blah"; 
     }     
    }else if($(this).val() == 8){ 
    var didConfirm = confirm("There is currently an offer for 8 polo shirt for £100. Click YES to recieve discount."); 
     if (didConfirm == true) { 
     window.location.href = "http://google.com/Registration/blah"; 
     }     
    }else if($(this).val() == 10){ 
    var didConfirm = confirm("There is currently an offer for 10 polo shirt for £100. Click YES to recieve discount."); 
     if (didConfirm == true) { 
     window.location.href = "http://google.com/Registration/blah"; 
     }     
    } 
}); 

http://jsfiddle.net/NUJrL/3/

+2

代碼改進建議:如果'($(本).VAL()%2 === 0){... 「目前的報價」 + $(本) .val()+「polo ...」}' – Johan

+0

如果(didConfirm == true){...} else {...關注另一個項目},您可以關注另一個項目。你可以使代碼更小,但這是另一個答案。 –

+1

非常感謝你@Johan – jagmitg

回答

1

爲什麼不乾脆用blur事件?

$("#Quantity9438851").bind("blur", function() { 

    var val = $(this).val(); 

    if(!(val % 2) && val <= 10){ 

     var conf = confirm("There is currently an offer for " 
     + val +" polo shirt for £25. Click YES to recieve discount."); 

     if (conf) 
     window.location.href = "http://google.com/&Quantity=10"; 


    } 
}); 

http://jsfiddle.net/NUJrL/6/

+0

或者更進一步,只需綁定到'模糊'。這樣,如果用戶想要輸入22,那麼在完成之前不會彈出提供2的交易對話框! – danielpsc

+0

去看看那個綁定函數。但就目前而言。這完美的作品! – jagmitg

+0

@danielpsc好點,更新! – Johan