Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add custom attributes to button html. Will it work in all browsers

<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.

like image 623
Manas Saxena Avatar asked Aug 19 '16 11:08

Manas Saxena


People also ask

Can you add custom attributes to HTML?

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.

What is the recommended way to add custom HTML5 attributes?

You can use the setAttribute method to modify the value of existing attributes or to add new attributes.

Can we add value attribute to a button?

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.

Can I add any attributes to HTML elements?

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.


3 Answers

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');
like image 104
brk Avatar answered Sep 30 '22 14:09

brk


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');
like image 34
Jekin Kalariya Avatar answered Sep 30 '22 14:09

Jekin Kalariya


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')

like image 33
Amar Singh Avatar answered Sep 30 '22 15:09

Amar Singh