How do I dynamically select a specific link with JQuery?

I am trying to select a specific link and open a dialog.

  $('#edit').click(function(e) {
    var url = $(this).attr('href');
    var dialog_form = $('<div id="dialog-form">Loading form...</div>').dialog({
      autoOpen: false,
      width: 520,
      modal: true,
      open: function() {
        return $(this).load(url + ' #content');
      },
      close: function() {
        $('#dialog-form').remove();
      }
    });
    dialog_form.dialog('open');
    e.preventDefault();
  });

      

On a page with multiple edit links

<a href="articles/edit/1" id="edit">edit</a>
<a href="articles/edit/2" id="edit">edit</a>

      

but the code only works when there is only one link to edit.

How can I dynamically select the exact link I click on?

+3


source to share


3 answers


ID

attributes must be unique, which is invalid HTML. Browsers always return the first occurrence.

You can use the class name instead.

<a href="articles/edit/1" class="edit">edit</a>

      



And you will need to change your selector to .edit

to find elements by class name.

$('.edit').click(function(e) {
  ... 
});

      

With HTML5, you can use attributes as well data-*

.

+3


source


First of all, don't use duplicate identifier attributes - they must be unique for every element in the DOM. If you want a selector, use the class names instead:

<a href="articles/edit/1" class="edit">edit</a>
<a href="articles/edit/2" class="edit">edit</a>

      



Second, use on()

instead click()

:

$('.edit').on('click', function(e) {
    var url = $(this).attr('href');
    var dialog_form = $('<div id="dialog-form">Loading form...</div>').dialog({
      autoOpen: false,
      width: 520,
      modal: true,
      open: function() {
        return $(this).load(url + ' #content');
      },
      close: function() {
        $('#dialog-form').remove();
      }
    });
    dialog_form.dialog('open');
    e.preventDefault();
  });

      

+2


source


Two elements with the same ID are not valid HTML. Use the class instead.

0


source







All Articles