skip to Main Content

In my web application, on change event I pass the data to the javascript function as.

<select onchange="sendInfo(this)" class="form-select js-dropdown" data-id='+counter+' name="Item_Id[' +counter +']" id="ItemId"' + counter + ' required="required" ' +
"</select>"

I want to get the data-id on the javascript variable. How can I pass this?

From the current code, it gets the selected Id. I want to get the data-id as well.

function sendInfo(e)
{
 console.log(e.value);
}

2

Answers


  1. To access the data-id attribute value in your JavaScript function, you can use the getAttribute() method. Here’s how you can modify your code to achieve this:

    <select onchange="sendInfo(this)" class="form-select js-dropdown" data-id='+counter+' name="Item_Id[' +counter +']" id="ItemId' + counter + '" required="required"></select>
    

    In the JavaScript function:

    function sendInfo(e) {
      var dataId = e.getAttribute("data-id");
      console.log(dataId);
      console.log(e.value);
    }
    

    By using e.getAttribute("data-id"), you can retrieve the value of the data-id attribute from the e element (which is the <select> element in this case).

    Now, when the onchange event is triggered, the sendInfo function will log both the selected value (e.value) and the data-id attribute value (dataId) to the console.

    Login or Signup to reply.
  2. You can get your any attribute value with the help of getAttribute and also if you don’t want to use it you can use dataset for data attribute. check below code to get attribute value.

    Let’s say your html looks like this,

    <select onchange="sendInfo(this)" class="form-select js-dropdown" data-id='+counter+' name="Item_Id[' +counter +']" id="ItemId"' + counter + ' required="required" ' +
    "</select>"
    

    Then you can do this in your JavaScript function,

    function sendInfo(e)
    {
      // using getAttribute()
      console.log(e.getAttribute('data-id'));
    
      // using dataset
      console.log(e.taget.dataset.id)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search