2011-06-15 27 views
0
<div class='divver'> 
     Quantity:&nbsp; 
     <select class='box' name='qty' id='quantity'> 
     <option value='1'>1</option> 
     <option value='2'>2</option> 
     <option value='3'>3</option> 
     <option value='4'>4</option> 
      </select> 
    </div> 

<script type="text/javascript"> 
    var s = document.getElementById("quantity"); 
    var quant = s.options[s.selectedIndex].text; 
    function checkIt(){ 
    alert (quant); 
    } 
</script> 

提交成功後,我運行checkIt。爲什麼不抓住選定的選項?

function submitQuickview() 
    { 
     if(productForm.validate()){ 

      //submit the form with ajax 
      new Ajax.Request($('product_addtocart_form').action, { 
       parameters: $('product_addtocart_form').serialize(true), 
       onSuccess: checkIt 
      }); 
     } 

     return false; 
    } 

出了什麼問題?無論提交的選項的值如何,它總是提示1作爲quant var。任何想法爲什麼?請注意,我沒有使用jQuery並在Vanilla或Prototype框架中工作。

+0

「我不使用jquery」是什麼意思? – Jason 2011-06-15 21:28:41

+0

這意味着大部分時間我試圖找到一個解決方案使用JavaScript有人會給我一個jQuery的方法,這不是我在這裏的選項 – Zac 2011-06-15 22:01:54

+0

我在逗弄;)大多數人來這裏要求一切jquery的答案。 – Jason 2011-06-15 23:07:48

回答

3

這是因爲您正在加載頁面時正在給quant變量賦值。

爲了得到當前值
1)你必須閱讀功能中選擇的值 更改您的代碼如下:

var s = document.getElementById("quantity");  
function checkIt(){  
var quant = s.options[s.selectedIndex].text;  
alert (quant); 
} 

或者

2)當觸發select的onchange事件時更改該值。 喜歡的東西:

var s = document.getElementById("quantity");  
var quant = s.options[s.selectedIndex].text;  
s.onchange = function(){ 
    quant = s.options[s.selectedIndex].text;  
} 

function checkIt(){  
alert (quant); 
} 
+0

啊..我是個笨蛋。準備好開始過週末了!謝謝你的幫助。 – Zac 2011-06-15 22:00:52

0

這種方法避免創建循環引用(或關閉,使循環引用),並避免全局變量。

function submitQuickview() { 

    var s = document.getElementById("quantity"); 

     if(productForm.validate()){ 

      //submit the form with ajax 
      new Ajax.Request($('product_addtocart_form').action, { 
       parameters: $('product_addtocart_form').serialize(true), 
       onSuccess: checkIt 
      }); 
     } 

     return false; 
    } 

function checkIt() { 
    var s = document.getElementById("quantity"); 
    // grab your value 
    var quant = s.options[s.selectedIndex].text; 
    alert(quant); 
} 
相關問題