Sitemap / Advertise

Information



Tags



Share

How to pass HTML element attributes to a function when clicked without the onclick event in jQuery

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will discuss how to glean information from HTML elements when clicked without using the onclick event to pass the required data to a function.

Normally, we can pass information from a clicked HTML element to a function in JavaScript by using the onclick event like this(1):

<p id="demo" onclick='myFunction("information")'>Click me to send the information.</p>

<script>

function myFunction(info) {

document.getElementById("demo").innerHTML = info;

}

</script>

However, in this tutorial, I will show you how to elicit information from the attributes of HTML elements in jQuery. In that regard, you will be able to collect information effortlessly from HTML elements without needing to entering variables in the onclick event manually.

Code

- Create HTML elements with the same class name - data.

- Define the name attribute for each element to pass information to the function in jQuery.

- Select all elements with the data class name and execute the function when one of them is clicked.

- Using the line below, get the name attribute of the recently clicked HTML element - this.

$(this).attr('name');

- Then, display the name attribute.


-------------- HTML --------------

<p class="data" name="BMW">BMW</p>
<p class="data" name="Cadillac">Cadillac</p>
<p class="data" name="Chevrolet">Chevrolet</p>
<p class="data" name="Acura">Acura</p>
<p class="data" name="Bentley">Bentley</p>

-------------- JavaScript --------------

$(".data").on("click", function(){
	alert($(this).attr('name'));
});

Result:

Click one of the elements below to display its name attribute.

BMW

Cadillac

Chevrolet

Acura

Bentley

References

(1) https://www.w3schools.com/jsref/event_onclick.asp