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

早过忘川 提交于 2021-02-10 14:49:05

问题


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

回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/9837704/show-hidden-div-based-of-any-value-contained-in-the-input-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!