dtbonklcs575884485
2011-02-19 14:34
浏览 251
已采纳

默认情况下隐藏元素取决于下拉列表

I have a form element, that is hidden or show depending on a dropdown element in my form. I've been able to change the visibility when the dropdown changes.

Here's my code right now:

$("select[name=post_category]").change(function(){
var id = $("select[name=post_category]").val();
if(id != 3){
    $("dt#post_url-label").hide();
    $("dd#post_url-element").hide();
}
else{
    $("dt#post_url-label").show();
    $("dd#post_url-element").show();
}
});

What I want is the fields to be hidden, unless the page loads with id=3 (so i can't just hide them with CSS), in that case the field has to be visible from the start. Right now, the field is always visible on pageload.

Any suggestions how I should go about this?

图片转代码服务由CSDN问答提供 功能建议

我有一个表单元素,根据表单中的下拉元素隐藏或显示。 我已经能够在下拉列表更改时更改可见性。

这是我现在的代码:

  $(“select [  name = post_category]“)。change(function(){
var id = $(”select [name = post_category]“)。val(); 
if(id!= 3){
 $(”dt#post_url  -label“)。hide(); 
 $(”dd#post_url-element“)。hide(); 
} 
else {
 $(”dt#post_url-label“)。show(); \  n $(“dd#post_url-element”)。show(); 
} 
}); 
   
 
 

我想要的是要隐藏的字段 ,除非页面加载id = 3(所以我不能用CSS隐藏它们),在这种情况下,字段必须从一开始就可见。 现在,该字段始终在页面加载中可见。

有任何建议我应该怎么做?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongya3627 2011-02-19 14:40
    已采纳

    Try this:

    $('select[name="post_category"]').change(function() {
        $('dt#post_url-label, dd#post_url-element').toggle( +this.value === 3 );
    }).change();
    

    The idea is to trigger the change event immediately. You should be able to achieve that by using either triggerHandler('change') or just change().

    Live demo 1: http://jsfiddle.net/XE78E/
    Live demo 2: http://jsfiddle.net/XE78E/1/

    The 2. demo shows that the element is visible if the 3-rd option is preselected.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doupin5408 2011-02-19 14:39

    so why dont u check on page load if the id = 3 or not and use same logic to hide or show the element.

    评论
    解决 无用
    打赏 举报
  • duanjuan1103 2011-02-19 14:42

    That code is javascript, right?
    Call $("select[name=post_category]").change() on page load.

    window.onload = function() { $("select[name=post_category]").change() }
    

    or add it to your existing onload function.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题