2012-12-06 45 views
-1

我想在JavaScript中隱藏並顯示特定條件下的按鈕。在javascript中隱藏/顯示狀態

代碼:

$(function(){ 
    // hide the div initially 
    $("#a").hide(); 

    // Check to see if there is 250 in the url 
    var bal_amount = document.getElementById('balance_amount'); 
    if (bal_amount.value > 0) { 
     $("#a").show(); 
    } 
}); 

HTML

<form> 
<input type="text" id="balance_amount"> 
</form> 

<image src="image.jpg" id="a"> 

但它不工作。

+0

什麼是你的HTML -

您可以進一步通過檢查在文本框中輸入無效提高你的代碼? – Cerbrus

+0

你想在這裏做什麼?當焦點改變時,您是否嘗試在文本字段中驗證'balance_amount',然後顯示您的鏈接? –

+0

看到你的HTML會很有幫助。有可能'bal_amount.value' <0 – aug

回答

1

你需要更改代碼的這一部分 -

// Check to see if there is 250 in the url 
var bal_amount = document.getElementById('balance_amount'); 
if (bal_amount.value > 0) 
{ 
    $("#a").show(); 
} 

您要執行上面這段代碼中document ready事件,這意味着它將被執行當頁面加載時,只有一次。

爲了解決這個問題,你需要放置在事件處理中的代碼 -

​$(document).ready(function() { 
    $("#a").hide(); 

    // See this? This is the event handler for the 
    // change event which will fire whenever the value 
    // of the text box changes. 
    $('#balance_amount').change(function() { 
     // Check to see if there is 250 in the url 
     if ($(this).val() > 0) { 
      $("#a").show(); 
     } 
    }); 
});​ 

這樣,無論何時的balance_amount字段的值發生變化,這一事件將觸發並驗證您的餘額爲你。

Here你會發現一個工作演示。

​$(document).ready(function() { 
    $("#a").hide(); 

    // See this? This is the event handler for the 
    // change event which will fire whenever the value 
    // of the text box changes. 
    $('#balance_amount').change(function() { 

     var balance = parseInt($(this).val(), 10); 
     if (isNaN(balance)) { 
      alert('You have entered an invalid value'); 
      return false; 
     } 

     if (balance > 0){ 
      $("#a").show(); 
     } 

     // There you go, an else block for you 
     else { 
      $("#a").hide(); 
     } 
    }); 
});​ 
+0

它可以工作但是問題在於,當我在文本框中輸入值時,它會起作用,但是textbox的值自動出現,這就是爲什麼當文本框的值自動出現時它不起作用,並且我還希望在此處聲明其他語句。 – user1814328

+0

@ user1814328:You可以很容易地在這裏包含'else'語句!另外,change事件只在焦點從文本框輸出時觸發。替代方法是檢查'keyup/down'事件,這可能是你不想要的。 –

+0

I嘗試else語句也可以,但是其他語句也不行。 – user1814328

0

試試這個:

$(document).ready(function(){ 
     $("#a").hide(); 
    $('#balance_amount').keyup(function() { 
     // Check to see if there is 250 in the url 
     var bal_amount = $('#balance_amount').val(); 
     if (bal_amount.value > 0) { 
      $("#a").show(); 
     } 
    } 
}); 
+0

第3行有錯誤($({selector for input box})。bind('input propertychange',function(){) – user1814328

+0

我真的不喜歡jQuery和文檔選擇器的混合。 – Jivings