Selecting sections with JQuery/Javascript - Best Practices

I am building a web application using PHP. It lists each salesperson and below it, the clients assigned to them. There are only about 5 or 6 salespeople. There could be any number of clients for a salesperson.

Each salesperson is given their own div and client information (name, email, phone) is grouped with an unordered list:


<div id="salesperson-1">[INDENT]
<h1>Salesperson 1</h1>
<ul>[INDENT]
<li>Steve Smith</li>
<li>steve@company-a.com</li>
<li>555-5555</li>
<li><a href="#">Delete Client</a></li>
[/INDENT]
</ul>
[/INDENT]
<a href="#">Delete Salesperson</a>
</div>

I would like to be able to delete (actually hide) either a salesperson or client depending on which link the user clicked.

I have been using JQuery throughout my site so far and I can accomplish the task for the salespeople by creating individual events for 6 salespeople. If there are only 5 people, the 6th event will never be triggered. If there are 6, everyone is covered.

The tricky part are the clients since I can’t guarantee a specific number of them.

I would like to fit best practices as much as possible and reduce the complexity of my code if I can. Keeping that in mind…

  • Is there a better way to handle the salespeople rather than rewriting the function 6 times?
  • Can I pass a variable to a JQuery function using the onClick binder on the <a> tag –> <a href=“#” onClick=deleteClient(10)> and use the variable to determine which client to delete?
  • Would using a function in plain javascript and ignoring JQuery for this entirely be better?

Thanks!

If you want the same behavior for all six salespeople, you should only have one function to handle that, which then takes a parameter to determine which salesperson to hide, much like what you suggested for clients in your second question.

Yes, you can use such a variable to tell jQuery which client (or salesperson) should be deleted. The selectors passed to jQuery are just strings, so if the variable passed in by clicking on the link is 10 and corresponds to a div representing a client that has an id of “client-10”, the following code will select that div:


function deleteClient(id) {
  client = $("#client-" + id);
  // Do what you need to do to delete the client
}

Look for the accordian functionality in JQUERY or as a JS example. This may be what you want.