I'm trying to customize a confirmation dialog with a custom message embedded in the hyperlink tag, something like this:
<a class="confirmation" href="whatever.html" data-message="Are you sure?">the text</a>
and the js:
$('.confirm-delete').click(function(){
return confirm('the content of the data-message attribute');
});
So my question is how can I access the data-message attribute? Thanks!
Well you are using jQuery, so use the .data() function to get data-* attributes.
Also using simple JS this.dataset.message will work on most of the new browsers, but going back to primitive browsers, use this.getAttribute('data-message'). But in the case which you are using jQuery, .data() is preferred.
$('.confirmation').click(function(){
return confirm($(this).data('message'));
});
function message(element){
return confirm(element.dataset.message);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<a class="confirmation" href="whatever.html" data-message="Are you sure?">Use jquery</a>
<br/>
<a href="whatever.html" onclick="return message(this);" data-message="Are you sure?">Use simple JS</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With