Signup/Sign In

How to add buttons within the input field using Bootstrap 5?

The input field is used to collect data from the user in the form of text. What if we want to collect any document, audio, video, and images from the user. In that case, we can use the input buttons with the help of which users can upload the data from their local system. We can also save this data to the server using the input submit button. We can add the buttons within the input field using the input-group class.

Adding buttons within the input field using bootstrap 5

The add buttons to the input field wrap the <input> and <button> within the .input-group class. The buttons can be placed on either side of the input field.

To add buttons, just replace the <label> with the <button> element.

  • Add .btn class within the <button> along with type="button" attribute and some unique id name.
  • The aria-describedby will point to id of <button> .
  • aria-label="upload" attribute is added along with the previous attributes in the <input> element.
  • For placing the button before input field, add <button> first and then <input>.
  • For placing input field first, add <input> first and then the <button>.

Example: Adding buttons within the input field

In this example, we have added the buttons within the input field with bootstrap 5.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap </title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet"> 
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script></head>
<body>
    <h2> Button at left of input field </h2>
	<div class="input-group mb-3">
	  <button class="btn btn-primary" type="button" id="inputGroupFileAddon03">Button</button>
	  <input type="file" class="form-control" id="inputGroupFile03" aria-describedby="inputGroupFileAddon03" aria-label="Upload">
	</div>	
</body>
</html>

Output

Here is the output of the above program.

input field button

Example: Adding a button to the right of the input field

To add the button to the right of the input field, add it after the <input> element.

Conclusion

We can easily create an input file field using the input group class and add buttons within. The buttons can be placed on either side. Bootstrap 5 made it easier to add buttons within the input field.



About the author: