To create an onclick
JavaScript function for the given HTML label element, you can follow these steps:
Step 1: Add an id
attribute to the label element so that we can easily select it in JavaScript. Step 2: Define the onclick
function that will be called when the label is clicked. Step 3: Add an event listener to the label to trigger the onclick
function when it’s clicked.
Here’s the JavaScript code:
<label id="itemTitleLabel" for="@itemTitelId" class="fontweight-normal radio-label">@Model.ListItems[i].Title</label>
<script>
// Step 2: Define the onclick function
function onLabelClick() {
// Your code here...
// This function will be executed when the label is clicked.
// You can add any JavaScript logic or actions you want to perform here.
// For example, you can access the label's text content using `innerText`:
var labelText = document.getElementById('itemTitleLabel').innerText;
console.log('Label clicked! Text content:', labelText);
}
// Step 3: Add an event listener to the label
var labelElement = document.getElementById('itemTitleLabel');
labelElement.addEventListener('click', onLabelClick);
</script>
Replace // Your code here...
with the actions you want to perform when the label is clicked. In the provided example, it simply logs the label’s text content to the console. You can customize the onLabelClick
function to perform any desired tasks or actions.