gek
gek

Reputation: 125

Show hidden div based of any value contained in the input field

I have the following mark up of a div that contains a form. The form has a basic search div and an advanced div.

 <div class="form">
     <form>
         <input type="text" name="first_name">
         <input type="text" name="last_name">

       <div class="Basic" class="slide">
         <input type="text" name="location"> 
       </div>

       <a class="toggle-link" onclick="ShowDiv('Adv');">+ show advanced fields</a>

      <div id="Adv" class="slide hidden">
         <input type="text" name="first_name2">
         <input type="text" name="last_name2">
         <input type="text" name="street">
         <input type="text" name="town">
         <input type="text" name="country">
       </div>
     </form>

     <a onclick="ShowDiv('Basic');">- hide advanced fields</a> 
    </div>

The hide/show is functioning based on the following script:

 function HideDiv() {
          $('.slide').hide();
      }
      function ShowDiv(ctrl) {
         HideDiv();
     $('#' + ctrl).show();
      }
       ShowDiv('Basic'); 

My problem (and this is a follow up ticket based on an existing question that I never managed to get to work) is that I want a user when he returns to this search form to be presented with the advanced div open if he used the advanced search form in the first place. So if any of the input fields contain any data values the div should be open when the user returns to the page.

I have this code so far but it doesn't work.

   $(document).ready(function () {

     $(function(){
       $("div#Adv input").each(function(){
           if($(this).val()!='')
              $(this).parent().parent().show();
              return;                       
  });
 });

Upvotes: 1

Views: 2250

Answers (3)

gdoron
gdoron

Reputation: 150313

$(function(){
    if($("#Adv input[value!='']").length){
        $('#Adv').show();
        $('a.toggle-link').hide();
    }
});

Upvotes: 1

slash197
slash197

Reputation: 9034

I believe you are missing some brackets there

$(document).ready(function(){
     $(function(){
       $("div#Adv input").each(function(){
           if($(this).val()!='')
           {
              $(this).parent().parent().show();
              return;
           }
     });
});

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

You should do

   $("div#Adv input").each(function(){
       if(this.value !== ''){
          //get the first ancestor with class=slide and show it
          $(this).closest('.slide').show();
          return;
        }
    });

Upvotes: 0

Related Questions