HTML <button> value Attribute

HTMLWeb DevelopmentFront End Technology

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.

Following is the syntax −

<button value="value">

Above, value is the initial value.

Let us now see an example to implement value attribute in <button> −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<p>Click below to get details about the learning content...</p></br></br>
<button id = "button1" value = "Learning" onclick = "demo1()">Get Tutorials</button>
<button id = "button2" value = "InterviewAnswers" onclick = "demo2()">Get InterviewQA</button>
<p id = "myid"></p>
<script>
   function demo1() {
      var val1 = document.getElementById("button1").value;
      document.getElementById("myid").innerHTML = val1;
   }
   function demo2() {
      var val1 = document.getElementById("button2").value;
      document.getElementById("myid").innerHTML = val1;
   }
</script>
</body>
</html>

This will produce the following output initially −

The output is as follows when “Get Tutorials” button is clicked −

The output is as follows when “Get InterviewQA” button is clicked −

In the above example, we have created JavaScript functions to get the value in a variable. One of them is demo1()

function demo1() {
   var val1 = document.getElementById("button1").value;
   document.getElementById("myid").innerHTML = val1;
}

The result of the above gets displayed on the click of a button. The onclick property is set to call the above function demo1() −

<button id = "button1" value = "Learning" onclick = "demo1()">
   Get Tutorials
</button>
raja
Published on 11-Jun-2019 15:06:39
Advertisements