Error refererirme to the value of an element in jquery

1

I am modifying a tab of bootstrap to have marked the one that I need when loading the page and I am not able to do it dynamically.

On the one hand I use this function (taken from this website)

function activaTab(tab){
    $('.nav-tabs a[href="' + tab + '"]').tab('show');};

With what I just need to pass the value of the link to show. The problem is that if I write directly the text works:

activaTab('anchor-1');

But if I take the value of an element of the page that contains the value #anchor-1 does not work. The last thing I have is a input hidden with the value.

activaTab($('#enlace-1').val());

I'm pretty new to the js so it's probably a basic error;)

Update (Feb 3, 2016)

Thank you very much for answering, I expand the code because I have not explained myself as clearly as I supposed.

Effectively I have removed the # from the function but because all the values that happened to it already go with the # .

The code of tab is this:

<ul class="nav nav-tabs" id="tab1">
  <li  {% if tab_anchor == '#pr-val' %} class="active" {% endif %}><a data-toggle="tab" href="#pr-val">Valoración</a></li>
  <li  {% if tab_anchor == '#pr-sel' %} class="active" {% endif %}><a data-toggle="tab" href="#pr-sel">Selección </a></li>
  <li  {% if tab_anchor == '#pr-des' %} class="active" {% endif %}><a data-toggle="tab" href="#pr-des">Descarte</a></li>
</ul>

The ifs are from the Twig template manager to have the default tab that was previously loaded (when making an insert that returns to the one marked).

<div id="pr-val" class="tab-pane fade active in">
<div id="pr-sel" class="tab-pane fade">
<div id="pr-des" class="tab-pane fade">

With this I have the tab that I want marked but the lower div does not correspond. So what I do is look up the value of the active href and show the panel. When not working and to ensure that the failure did not come from there, provisionally I have included a hidden input with the value of the selected anchor that I have in the session to have the direct value through the anchor id.

 <input id="anchor" type="hidden" name="anchor" value="{{ tab_anchor }}"/>

And the javascript code would be this:

$('#tab1 a').click(function (e) {
  e.preventDefault()
  $(this).tab('show')});


function activaTab(tab){
   $('.nav-tabs a[href="' + tab + '"]').tab('show');
};

This is when I make the call through:

activaTab('#pr-des');

works, but if I do it through:

activaTab($('#anchor').val());

does not work, the variable anchor having the value "# pr-des".

As putting the id of the value "by hand" worked it occurred to me to do a switch since that way I could call him directly.

$(document).ready(function(){

    switch($('#anchor').val()) {

       case '#pr-val':
         activaTab('#pr-val');
         break;

       case '#pr-sel':
         activaTab('#pr-sel');
         break;

       case '#pr-des':
         activaTab('#pr-des');
         break;
    }

    //activaTab('#pr-des');

 });

And that's not how it works either. On the other hand, if after switch , within that function, I will comment on:

activaTab('#pr-des');

and it works ... I have tested the cases of the switch and enter the one that corresponds.

I have tried to do alert of what the activaTab function shows and in both cases it prints:

.nav-tabs a[href="#pr-des"]

Thanks for taking a look. I'm about to send the tabs to the other neighborhood and make another type of "menu" ...

    
asked by PLTY 03.02.2016 в 02:36
source

1 answer

1

I have replicated the code according to what you mention and I did not give any problem (below you can see the functional example), instead I only managed to have a behavior similar to yours when my code was not in the closing of JQuery, it may be that when your code is executed, the HTML has not finished loading, which is why when executing manually it takes the expected behavior. I would like to know if your code is inside a JQuery closure for loading the DOM.

Even so, I leave the code to replicate so you can take it as a reference.

In the following code you can notice the functionality by means of a <input> in which you enter the #tab to activate and when you press «Send» it takes the value to activate the tab by means of of the functions that Bootstrap offers in its documentation: JavaScript · Bootstrap :

Note: Lines that start with the code: $log.logger(); can be deleted, they are only used for debugging purposes.

$(function(){
  /**
   * Sólo para fines de depuración.
   */
  $.fn.logger = function (val) {
    var $this = $(this);
    $this.stop().animate({
    	scrollTop: $this.prop('scrollHeight')
    }, 1000);
    $this.append($('<p>', {text: val}));
  }
  
  var $log = $('#log');
  $('form').on('submit', function(e) {
    $log.logger('===== '+ new Date());
    
    var nameTab = $('#tab-name').val();
    $log.logger('Se registra: '+nameTab);
    
    /**
     * Si no se añade el gato (#) o símbolo numérico,
     * lo añado al principio de la cadena.
     */
    if (!/^#/.test(nameTab)) {
      nameTab = '#'+nameTab;
      $log.logger('Añadido el símbolo numérico (#): '+nameTab);
    }
    
    console.log($(nameTab).data());
    
    $('a[href="'+nameTab+'"]').tab('show');
    $log.logger('Activado: $(\'a[href="'+nameTab+'"]\').tab(\'show\')');
    
    e.preventDefault();
    e.stopPropagation();
  });
});
#log {
  height: 100px;
  overflow-y: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

<div class="row">

  <form class="col-xs-6 col-sm-6">
    <label for="tab-name">Nombre de la pestaña</label>
    <input type="text" id="tab-name" placeholder="#ejemplo" required />
    <button type="submit">Activar</button>
  </form>
  
  <div class="col-xs-6 col-sm-6">
    <h3>Log</h3>
    <div class="row" id="log"></div>
  </div>
  
</div>

<hr />

<div>

  <!-- Lista de pestañas -->
  <ul class="nav nav-tabs" role="tablist">
    <li role="presentation" class="active">
      <a href="#primera" aria-controls="primera" role="tab" data-toggle="tab">Tab: #primera</a>
    </li>
    <li role="presentation">
      <a href="#segunda" aria-controls="segunda" role="tab" data-toggle="tab">Tab: #segunda</a>
    </li>
    <li role="presentation">
      <a href="#tercera" aria-controls="tercera" role="tab" data-toggle="tab">Tab: #tercera</a>
    </li>
  </ul>

  <!-- Pestañas -->
  <div class="tab-content">
    <div role="tabpanel" class="tab-pane active" id="primera">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus rutrum justo vitae urna condimentum aliquet. Nam accumsan ultrices posuere. Maecenas a orci viverra libero dictum efficitur. Proin suscipit nibh lectus, nec elementum est vehicula quis. Praesent euismod, enim ut viverra convallis, nunc nibh accumsan enim, ac mattis eros velit at erat. Integer pretium libero nec rhoncus elementum. Nulla tristique sodales urna nec semper. Morbi sapien turpis, lobortis eu convallis sed, fringilla quis ex. Donec nec placerat enim.</p>
    </div>
    <div role="tabpanel" class="tab-pane" id="segunda">
      <p>Quisque pharetra lorem vel enim iaculis, a pharetra nunc sagittis. Sed at dapibus ante. Duis viverra imperdiet aliquam. Praesent nulla est, venenatis vitae luctus quis, finibus et leo. Nulla dapibus lobortis tempus. Aliquam efficitur vestibulum libero, facilisis finibus augue finibus congue. Sed laoreet vestibulum nisi vitae sodales.</p>
    </div>
    <div role="tabpanel" class="tab-pane" id="tercera">
      <p>Vivamus in sapien ultrices risus imperdiet varius vel in metus. Sed in nisl tincidunt, vehicula augue eu, laoreet elit. Nulla quis nisl augue. Duis at molestie neque. Praesent cursus dui vitae elit mattis, eu pellentesque urna convallis. Praesent lobortis purus eu massa vehicula, sed consequat dolor tempor. Donec at imperdiet lectus, id hendrerit odio. Morbi iaculis est eget nibh imperdiet, nec porttitor turpis condimentum.</p>
    </div>
  </div>

</div>
    
answered by 14.03.2016 в 23:27