简体   繁体   中英

Show or hide form element

I have one html form - On that one text field like

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

On the value of age i have to show this element like -

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

If age>18 then married field will be shown to form otherwise hide it.This age>18 condition is stored in database.As value of age changes married field toggle(show/hide). How can i do it with javascript/jquery.Please suggest.

For more information, all these fields are genereated dynamically.So i was thinking to add onchange = "somefuction(condition);" with age while creating then look for field are to be shown when condition is satisfied, is also in DB.

OR

One solution may i think that -
The field in this case married will look for value of age changes.Then accordingly married will hide/show itself.But problem is that how married observe age field or call javascript function.
Sorry for not explaining full problem.

add id="married" to the select and use something like this.

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

UPDATE: I never worked on ruby rails. But I think you can fetch value from database and set that value in a hidden field.

Once hiddenfield value is set change jQuery to,

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

Don't forget to modify <select name = "married"> to <select name = "married" id = "married">

Try this & note

  • avoid the space between id = "txt_age"

rest this should help:

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();
   }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM