skyguy skyguy - 6 months ago 18
HTML Question

Javascript/CSS: Change button to a text field on click?

I have a button that I need to change into a text field (Ideally expand into it using an animation) when clicked. Right now I have my button and text field beside each other on the page:

echo '<form id= "changePassForm" action="" method="post" enctype="multipart/form-data">';
echo '<div class="changePass">Change Password</div>';
echo '<div class="changePassBtn" method="post"></div>';
echo '<input type="password" placeholder="Password" name="password">';
echo '</form>';


I can set the password to hidden at start but I need to know how to make the changePass button "become" or expand into the password text field either using CSS or javascript.
I'm new to javascript and am unsure how to accomplish this on button click.

How can I change a button to a text field on click? I need to be able to change back to the button afterwards

Answer

Put both your button and input field in the same div and then overlap them using the positioning trick with relative and absolute. Then use JQuery to make it look pretty when hiding the elements.

JSFiddle: https://jsfiddle.net/wpbL3kjx/9/

//Shows Input Box When Focussed
$(".changePassBtn").click(function() {
  var neww = $(".changePass input").css("width");
  $(this).animate({
    width: neww
  }, 300, function() {
    $(".changePass input").fadeIn(300, function() {
      $(".changePassBtn").hide();
    }).focus();
  });
});

//Shows Button When Unfocussed
$(".changePass input").blur(function() {
  $(".changePassBtn").css("width", "auto");
  var neww = $(".changePassBtn").css("width");
  $(this).animate({
    width: neww
  }, 300, function() {
    $(".changePassBtn").show(0, function() {
      $(".changePass input").fadeOut(500, function() {
        $(".changePass input").css("width", "auto");
      });
    });
  });
});
.changePass {
  position: relative;
}
.changePass input {
  position: absolute;
  padding: 5px;
  display: none;
}
.changePass .changePassBtn {
  background: #2d89ef;
  border-bottom: 2px solid #2b5797;
  color: white;
  padding: 4px;
  display: inline;
  border-radius: 2px;
  position: absolute;
  overflow: hidden;
  white-space: nowrap;
}
.changePass .changePassBtn:hover {
  background: #2b5797;
  border-top: 2px solid #2d89ef;
  border-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="changePassForm" action="" method="post" enctype="multipart/form-data">
  <div class="changePass">
    <div class="changePassBtn">Change Password</div>
    <input type="password" placeholder="Password" name="password">
  </div>
</form>