<button id="save" custom-field="false">
Can I define my own custom attribute for button markup like stated above? Will it work on all browsers?
Basically, the problem I have is that the above save button redirects to an AJAX call, which, if successful, then redirects to some other page. I have added an alert on window.onbeforeunload. I don't want this alert to pop up when the redirect is due to successful ajax call on click of the save button.
So, the above fix is that on successful ajax, I set the custom-field
to true and in my window.onbeforeunload code I alert only if custom-field
false.
If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery. There are some rules to keep in mind before defining your custom attributes.
You can use the setAttribute method to modify the value of existing attributes or to add new attributes.
The value attribute of the <button> element is used to set the initial value of a button. You can set this in a <form>. Here, we will be showing an example without using a form. Above, value is the initial value.
By custom attribute, we mean you can add any type of attribute to any given HTML element. If you are just creating a static web page that has nothing other than HTML and CSS, then adding custom attributes to HTML elements is generally not needed and is not necessary.
Yes you can use jquery .data for adding custom attribute.
It can be used to add any custom arbitrary data
<button id="save" data-myAttribute="myAttribute">
You can retrieve it using
$( "#save" ).data( "myAttribute" ); // myAttribute
or using javascript
document.getElementById('save').setAttribute('mydata','myData');
retrieve it using
document.getElementById('save').getAttribute('mydata');
Yes you can add custom field in any element and access it like below when need
<button id="save" data-field="false">
var custFieldValue=$('#save').attr('data-field');
you can use data-attribute
.
For Eg:
<button id="save" data-field="false">
Read more about data-attribute
You can easily retrieve the data attribute value in jquery using .data()
or .attr('data-field')
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