2012-06-01 41 views
0

嘿,我想在用戶填寫輸入時顯示錶格。當輸入填充時,javascript顯示隱藏的元素

我所擁有的是:

<head>部分:

<script type="text/javascript"> 

//hide initially  
$("table#mytable").hide(); 

// show function 
function showit() { 
$("table#mytable").show(); 
} 
</script> 

和表:

<table id="mytable"><tr><td>FOO</td><td>BAR</td></tr></table> 

及以下(也許是很重要的)表形式:

<form action="foobar.php"> 
<input name="example" onselect="showit()" /> 
<input type="submit" value="Send" /> 
</form> 

我認爲onselect並不完美,但它應該在我的情況下做到這一點。

上面的代碼根本不隱藏表格。我不知道我做錯了什麼。希望some1能找到一個錯誤 - 謝謝。

編輯

這裏是解決方案:

head

<script type="text/javascript"> 
function show(id) { 
    document.getElementById(id).style.display = 'block'; 
} 
</script> 

,並在每個元素隱藏只需添加style="display: none;"和編輯輸入 - 增加onkeyup="show('id')其中id是元素隱藏的ID例如#mytable

+0

嘗試和沒有工作 – andrewpo

+0

請參閱更新 –

回答

2

它不工作的原因是因爲您在呈現表元素之前調用了javascript。有三種方法這樣做的:

// Use CSS (best): 
<table style="display:none;" id="mytable">...</table> 

// Using DOM Load event (wait for all of the elements to render) (second best) 
$(function() { $("table#mytable").hide(); }); 

// Put your javascript at the bottom of the page instead of the head. (not preferred) 
+0

爲什麼_not preferred_在頁面底部的腳本? [加速您的網站的最佳實踐](http://developer.yahoo.com/performance/rules.html#js_bottom) – Andreas

+0

嘗試了1和2 - 沒有工作。我不知道爲什麼。 'display:none'我無法顯示它,但它被正確隱藏 – andrewpo

+0

我使用了1. - 並找到了另一種方法來改變它 - 我猜hide()並顯示沒有工作在我的情況 - 檢查編輯 – andrewpo

0

你也可以使用的onkeyup和記錄隨時可能有助於

$(document).ready(function() { 
$("#mytable").hide(); 
    $("#example").keyup(function (e) { 
$("#mytable").show(); 
}) 
});​ 

jfidle http://jsfiddle.net/dznej/

+0

onkey up似乎是個好主意 - 謝謝 – andrewpo

+0

我已經完全複製了yout jsfidle並檢查了歌劇和ff - 沒有工作我不知道爲什麼 - 它可能是由我的服務器設置引起的? js是客戶端語言,但也許在那裏是錯誤的 – andrewpo

0

退房我已經爲您創建的小提琴 - http://jsfiddle.net/ggJSg/

基本上有兩個問題:

  • 你需要調用$("#mytable").hide();只有當DOM就緒
  • 使用適當的事件(如我的例子中的焦點)來觸發表格顯示
+0

我也想到了焦點,但它似乎並不是OP所要求的。該表應在「用戶填寫輸入」時顯示。即當在文本框中輸入字符時。 –

-1

當DOM完成加載時,您需要使用.ready()函數來執行代碼。然後,你應該使用.change()函數來顯示它:

$(document).ready(function() { 

    // Hide initially  
    $('#mytable').hide(); 

    // When something changes in the input named `example` then show the table. 
    $("[name='example']").change(function() { 
    $('#mytable').show(); 
    }); 
});