Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid inline javascript

My code is essentially this:

<a href="javascript:void(0);" onClick="viewServices(1)">Services</a>
<a href="javascript:void(0);" onClick="viewServices(43)">Services</a>
<a href="javascript:void(0);" onClick="viewServices(16)">Services</a>
...

Where viewServices:

function viewServices(stylistID){
    alert(stylistID);
}

Only, there are two problems:

  1. I am using inline Javascript, and that is discouraged.
  2. When I click a link, the function isn't called.

It should also be mentioned that I am importing JQuery and Bootstraps .js files, and that each link (as well as associated ID) is loaded dynamically.

Is there an established method that will allow me to remove my inline javascript, but also make it so that I can call functions that pass the dynamically loaded link's "ID" to the function?

** EDIT

Each link is generated during a mysqli_fetch_row that repeats until each row's information has been run through. The number in viewServices(#) is actually

<?php echo $row[0]; ?>
like image 904
Daniel Brown Avatar asked Jul 10 '26 07:07

Daniel Brown


1 Answers

A solution is to utilize data attribute and class to refactor html like this

<a href="#" data-service="16" class="service-link">Services</a>

Then, jQuery

$('.service-link').on('click', function(e){
  e.preventDefault(); // Stop default behavior of clicking link
  alert(this.data('service')); // Retrieve the service id and use it
});
like image 180
Billy Chan Avatar answered Jul 15 '26 19:07

Billy Chan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!