显示或隐藏表单元素

时间:2012-07-16 11:36:07

标签: javascript jquery ruby-on-rails

我有一个html表单 - 在那个文本字段中,如

<input type = "text" name = "age" value = "" id = "txt_age">

关于年龄的价值,我必须将此元素显示为 -

<select name = "married">
  <option value = "Yes">Yes</option>
  <option value ="No">No</option>
</select>

如果年龄≥18岁,那么已婚领域将被显示形成否则隐藏它。此年龄> 18条件存储在数据库中。随着年龄的变化,已婚领域切换(显示/隐藏)。 我怎么能用javascript / jquery做。请指教。

有关更多信息,所有这些字段都是动态生成的。所以我想添加onchange =&#34; somefuction(condition);&#34;当条件满足时,在创建然后查找字段时显示年龄,也在DB中。

OR

我认为有一种解决方案 -
在这种情况下结婚的领域将寻找年龄变化的价值。然后结婚将隐藏/展示自己。但问题是,如何结婚观​​察年龄领域或调用javascript功能。
很抱歉没有解释完整的问题。

3 个答案:

答案 0 :(得分:1)

将select =“married”添加到select中并使用类似的内容。

$("#txt_age").blur(function() {
    if(parseInt($(this).val() > 18) {
        $("#married").show();
    } else {
        $("#married").hide();
    }
});

答案 1 :(得分:0)

更新:我从未在ruby rails上工作过。但我认为您可以从数据库中获取值并在隐藏字段中设置该值。

设置hiddenfield值后,将jQuery更改为,

$(document).ready(function(){
$("#txt_age").focusout(function()
{
if(parseInt($("#txt_age").val())>parseInt($("#hiddenfield_id").val()))
{
$("#married").show();
}
else
{
$("#married").hide();
}
});
});

不要忘记修改<select name = "married"> to <select name = "married" id = "married">

答案 2 :(得分:0)

试试这个&amp;注意

  • 避免id =“txt_age”
  • 之间的空格

休息这应该有所帮助:

var $foo = $('select[name="married"]');
$foo.hide(); // in start always hide

$('#txt_age').on('blur', function() {
   if(parseInt(this.value)>18){
       $foo.hide();
   } else {
       $foo.show();
   }

});
相关问题