take2 take2 - 2 months ago 4
jQuery Question

Pure javascript way of swapping input values on click

Is there a pure javascript way of swapping input values when you click a div? You can see a working example with jquery here:


<div id="swap">Click me</div>
<input id="one" value="One"/>
<input id="two" value="Two"/>

<script type="text/javascript">
$("#swap").click(function(e) {

var fromVal = $("#one").val();
var toVal = $("#two").val();


There are many examples of doing this with jquery, but I haven't found a pure javascript way of doing it.


Of course.

<button id="swap">Click me</button>
<input id="one" value="One"/>
<input id="two" value="Two"/>

    var btn = document.getElementById("swap");
    btn.addEventListener("click", function(e) {
      var from = document.getElementById("one"),
          to = document.getElementById("two");
      if(!!from && !!to) {
        var _ = from.value;
        from.value = to.value;
        to.value = _;
      } else {
        console.log("some input elements could not be found");

The equivalent of jQuery's $(...) is actually document.querySelector, so we could have used document.querySelector("#swap"), too, but if you have an element id, there is a dedicated getElementById that's faster, so you typically don't bother with query selecting.

Also note that the equivalent to jQuery's click is actually .addEventListner, not .onclick. The first lets you register arbitrarily many handlers, the latter is an exclusive handler that gets overwritten if you ever try to add a second, third, etc. event handler. It's from an older version of JavaScript, don't use it =)

The swap is then simply the same as with any programming language, where you get your two inputs, cache one of them, reassigned the one you just cached, and them assign the cached value to the other input.

cached <- a.val
a <- b.val
b <- cached

Finally, note this code doesn't say it's "text/javascript". In HTML5, this is not a thing you say anymore. Anything that's just <script> is assumed javascript unless you explicitly mention another type.