简体   繁体   中英

How to pass parameter to an onclick function

I have a li item that I am passing through to my server to retrieve data from the database, but I am unable to do so:

<li name="Physics" value="Physics" id="physics" onclick="drawChart(id)">Physics</li>

This drawChart function use google chart API .

function drawChart(value) {
      var jsonData = $.ajax({
          url: "getData.php?subject=value",
          dataType: "json",
          async: false
          }).responseText;
...

The getData.php is working fine but I am unable to pass parameter and use it.

Stop using inline javascript, and the issue solves it self

 $('#physics').on('click', function() { drawChart(this.id); }); function drawChart(value) { var jsonData = $.ajax({ url : "getData.php", data : {subject : value}, dataType : "json", }).done(function(response) { // use response here }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li name="Physics" value="Physics" id="physics" >Physics</li> 

Assuming $.ajax in your code is jQuery, why not use more of it ...

You could pass in this as an argument to the onclick function.

 function clickHandler(el) { console.log(el.id); } 
 <button id="clickMe" onclick="clickHandler(this)">Click me</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM