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
To access the
data-id
attribute value in your JavaScript function, you can use thegetAttribute()
method. Here’s how you can modify your code to achieve this:In the JavaScript function:
By using
e.getAttribute("data-id")
, you can retrieve the value of thedata-id
attribute from thee
element (which is the<select>
element in this case).Now, when the
onchange
event is triggered, thesendInfo
function will log both the selected value (e.value
) and thedata-id
attribute value (dataId
) to the console.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,
Then you can do this in your JavaScript function,