-1

How should I structure a function named countryUrl() taking the parameter id from the <li> tag in:

<ul>
  <li onclick="countryUrl(this.id)" id="20" value="Benin">
    <a href="#">Benin</a>
  </li>
</ul>

and concatenating it to /frame/theme/ in an ajax call:

$.ajax({
        type:"GET",
        url :"/frame/theme1/"+myUrl,
        dataType: 'json',
        success:  function(data) { ...

Would it be something like :

function countryUrl(id){
   return "/frame/theme/"+this.id; 
}

Then how do I pass it to the url: field ?

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
road
  • 479
  • 3
  • 20
  • You have a link there, which is a perfect place to store a URL for jQuery to access. Also, don't use an inline `onclick` handler because JavaScript belongs in `.js` files not `.html` files. – zzzzBov Aug 07 '17 at 19:20
  • So where is the function at that you are calling? – epascarello Aug 07 '17 at 19:21

2 Answers2

0

You can you data("id") instead of id. Then you will just use counrtyUrl(this.data('id'). In the $.ajax call use the argument from the function.

SashaSemanyuk
  • 357
  • 6
  • 20
0

First, don't use inline HTML event attributes, such as onclick. There are a variety of reasons why. Instead, separate your JavaScript from your HTML and follow modern standards as shown below.

Next, although it is legal for an id to be a number, it's not a good idea (especially for backwards compatibility).

Additionally, li elements don't have a value attribute. Use data-* attributes to store custom values in HTML elements instead.

Lastly, you don't need hyperlinks in your lists to make the list items clickable.

All you need to do is set up your li element(s) to have a click event callback and that callback extracts the data from the clicked li and uses it as you need.

// Get reference to the bullet:
var li = document.getElementById("lstBenin");

// Set up bullet to be clickable:
li.addEventListener("click", countryURL);

// function that is called when bullet is clicked
function countryURL(){

  // Create new URL based on the "data-value2" attribute
  // of the element that was clicked:
  var newURL = "/frame/theme1/" + this.dataset.value2;
  console.log(newURL);  // Test

  // Make AJAX call using new URL
  $.ajax({
          type:"GET",
          url :newURL,
          dataType: 'json',
          success:  function(data) { 
          }
        });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li id="lstBenin" data-value1="Benin" data-value2="20">Benin</li>
</ul>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71