In this topic,
We are going to see how to swap values between two input fields using jQuery.
Clicking on the “>>” button will swap the value of the left input box to the Right input box, and the icon of the “>>” button will be “<<“.
Step-1: Include the jQuery link in the <head>..</head>tag on index.html file.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Step-2: Create Html Code in the index.html file.
<body> <div class="row"> <div class="first-box"> <input type="text" name="box1" id="left"> </div> <div class="button"> <button type="button" id="btnleftside">>></button> </div> <div class="second-box"> <input type="text" name="box1" id="right"> </div> </div> </body>
Step-3: Add jQuery code in <script>…</script> tag on index.html.
In This code, first of all I have declared two variables.
When I click on the button, the value of the first input box goes to the second input box and, the button text change.
$("#btnleftside").click(function () { var left = $("#left").val(); var right = $("#right").val(); if ($("#btnleftside").text() == ">>") { $("#right").val(left); $("#left").val(""); $("#btnleftside").text("<<"); } else { $("#left").val(right); $("#right").val(""); $("#btnleftside").text(">>"); } });
Review the below video.
I hope you guys found something useful ??