2012-06-01 42 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(); 
    }); 
});