Fill the src attribute of an iframe and make it visible via jQuery when user click item

Asked

Viewed 157 times

1

I have a web page with a navbar at the top and an iframe that loads another page below.

The idea is that when the user clicks on the menu item via jQuery I fill the src attribute of iframe with the page and it loads. But it’s not working.

The code of the button:

(....)
<li class="nav-item  dropdown active mx-3">
  <a class="nav-link dropdown-toggle" href="#" id="menuCadastros" role=button data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Cadastros
    <span class="sr-only">(Página Atual)</span>
  </a>
  <div class="dropdown-menu" aria-labelledby="menuCadastros">
      <a class="dropdown-item" href="cadastrarmorador.php">Morador</a>
    <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="" id="cadUser">Usuário</a>           
  </div>
</li>
(....)

The jQuery is this:

<script type="text/javascript">
$(document).ready(function(){               
   $('#areaCentral').hide();
   $('#cadUser').click(function(){
      $('iframe').attr('src','cadastrarusuarios.php');
      alert($('iframe').attr('src'));
      $('#areaCentral').show(); 
   });
});
</script>

1 answer

0


You need to add one event.preventDefault() click event to prevent the link redirect or reload the page. The rest of the code seems normal to me:

$(document).ready(function(){				
   $('#areaCentral').hide();
   $('#cadUser').click(function(event){
      event.preventDefault();
      $('iframe').attr('src','cadastrarusuarios.php');
      alert($('iframe').attr('src'));
      $('#areaCentral').show();	
   });
});
#areaCentral{
   display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
   <li class="nav-item  dropdown active mx-3">
     <a class="nav-link dropdown-toggle" href="#" id="menuCadastros" role=button data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Cadastros
       <span class="sr-only">(Página Atual)</span>
     </a>
     <div class="dropdown-menu" aria-labelledby="menuCadastros">
        <a class="dropdown-item" href="cadastrarmorador.php">Morador</a>
       <div class="dropdown-divider"></div>
         <a class="dropdown-item" href="" id="cadUser">Usuário</a>			
     </div>
   </li>
</ul>
<div id="areaCentral">
   iframe aqui
   <iframe></iframe>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.