Reputation: 12957
I come across two following code snippets :
function myFunction() {
var x = document.getElementById("demo");
x.style.fontSize = "25px";
x.style.color = "red";
}
<p id="demo">Click the button to change the layout of this paragraph</p>
<button onclick="myFunction()">Click Me!</button>
<h1>My First JavaScript</h1>
<button type="button" onclick="document.getElementById('demo').innerHTML = Date()"> Click me to display Date and Time.</button>
<p id="demo"></p>
I am not able to understand why the different type="button" attribute has been added in second code snippet?
What's the difference between two buttons?
Upvotes: 0
Views: 703
Reputation: 1779
The <button>
tag defines a clickable button.
Inside a <button>
element you can put content, like text or images. This is the difference between this element and buttons created with the <input>
element.
It has so many Attributes and type
is one of them and this type has 3 values:
button
(Normal button)reset
(to handle reset action, specially for form)submit
(to handle form submit)To know other properties you can read: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button
https://www.w3schools.com/tags/tag_button.asp
Upvotes: 1
Reputation: 207901
In your examples the addition of the type="button"
makes no difference whatsoever (remove it and you'll see).
Typically you would specify the type
of your button if it is being used in a form, as the default type
of <button>
is submit
, and clicking it would cause a <form>
to be submitted, and typically either reload the current page or load a new page.
By specifying the type as button
instead of the default submit
, you prevent that behavior.
Upvotes: 1
Reputation: 1
There are three types of buttons:
Button attribute is not that big deal, because it changes nothing in your code. The only difference in your two code versions are writing the whole code after the "onclick" attribute (code2) and writing the function name after the "onlick" attribute (code1). You can read about the button attributes and differences between input and button with the same attributes on this site http://html.com/attributes/button-type/ I hope it will help you a lot.
Upvotes: 0
Reputation: 1
The attribute type
decide the style of <Button>
. It's default value is button
in Internet Explorer.However, in other browser,it's default value is submit
even in standard of W3C
.
So you need to define the type
of button
always.
Upvotes: 0
Reputation: 1
Writing <button type="button">
defines the button as a clickable button.
There is no big difference with <button>
, but it is more safe to put a type attribute to the button element because some browsers may use different default types for the <button>
element, which could lead to bugs.
Upvotes: -1