-1

I have spent hours trying to resolve this problem and reviewing other similar StackOverflow questions (1) (2), but none seem to have an answer to my problem..

I can't get past this error: ReferenceError: id is not defined. Alert does not show too.

  $("button.btn-tag-cat").click(function(e){
    e.preventDefault();
    var id = $(this).prop('id');
    alert(id);
    id.find('span').show();
    }, function(){
    id.find('span').hide();
  });

I have tried the following ways to using the id variable but none work.

$(id).find('span').show();
$("#" + id).find('span').show();

However, when i remove the chunk of code below the alert, the alert pops up with the correct id belonging to the button.

  $("button.btn-tag-cat").click(function(e){
    e.preventDefault();
    var id = $(this).prop('id');
    alert(id);
  });

View partial: Button id references a ruby local variable id="<%= name %>"

  <% q.categories_name_in.each do |name|  %>
    <button type="button" class="btn btn-outline-primary btn-lg btn-tag-cat" id="<%= name %>"><%= name %><span class='glyphicon glyphicon-remove'></span></button>
  <% end %>
doyz
  • 887
  • 2
  • 18
  • 43

2 Answers2

2

As you've noted, the error is chaining functions in the click listener.

In order to get the id attribute, you can use the jQuery attr function, like:

$("button.btn-tag-cat").click(function(e) {
  e.preventDefault();
  var id = $(this).attr('id');
  alert(id);
  $('#' + id).find('span').show();
});

$("button.btn-tag-cat").click(function(e) {
  e.preventDefault();
  var id = $(this).attr('id');
  alert(id);
  $('#' + id).find('span').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn-tag-cat" id="hallo">Press</button>
Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
1

Here, in your code I will beautify it to see your mistake:

$("button.btn-tag-cat").click(
  function(e) {
    e.preventDefault();
    var id = $(this).prop('id');
    alert(id);
    id.find('span').show();
  },

  function() {
    id.find('span').hide();
  }
);

notice the second function has

  function() {
    id.find('span').hide(); // right here
  }

but the id is not defined yet

try

  function() {
    var id = $(this).prop('id'); // this first
    id.find('span').hide();
  }
notrota
  • 1,048
  • 10
  • 21