$(document).ready(function() {
	$(".alert").click(function() {
		{
			var id = $(this).attr("id");
			alert(id);
			$(id).dialog();
			return false;
		}
	});
});

Ok it's alerting the id AFTER it alerts an undefined.. so it alerts "undefined" and then "5" or whatever the number may be.
What am I doing wrong?

Dani AI

Generated

Two likely causes are running together here. First, the click handler is firing more than once (common when an element with class .alert contains another .alert or when the handler is accidentally bound twice). That explains the two alerts: the first comes from a matched element that has no id (showing undefined), then the outer one shows 5. Second, the selection is wrong: using the raw id string as a selector (e.g. $(id)) is incorrect — an id selector needs a # prefix (and numeric-only ids can be awkward to select).

As suggested, check for multiple .alert elements. For 's situation, a robust fix is to stop propagation and use the element's id property, then select with '#' + id:

$(function(){
  $('.alert').on('click', function(e){
    e.stopPropagation();               // prevent parent .alert from also firing
    var id = this.id || $(this).data('target');
    if (!id) { console.warn('no id on clicked .alert'); return false; }
    $('#' + id).dialog();               // correct id selector
    return false;
  });
});

Debugging & best practices:

  • Use console.log(e.target, e.currentTarget) or console.dir(this) instead of alerts to see which element actually handled the event.
  • Inspect the DOM for nested .alert elements or duplicate handlers (search for multiple script inclusions).
  • Ensure unique IDs (duplicate IDs are invalid). If the element is meant to reference another element, prefer data- attributes (e.g. data-target="#dialog-5") or store a full selector, avoiding numeric-only ids where possible.
  • If elements are added dynamically, delegate with $(document).on('click', '.alert', handler).

do you have multiple classes named .alert?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.