Search code examples
javascriptjqueryformsjquery-hoverdetach

detach form element with jquery but keep text


I am doing a hover style effect to access a form field and text prompt for a Wikipedia viewer and everything works just fine so far but there's a big difference between fine and happy with it.

When hovered over the well enlarges to open the form field but when the mouse leaves and the field collapses, the text inside vanishes, is there any way to keep the input text?

var toggler = true;

var wellToggle = function(){
  $("#well").toggleClass("toggleMe")
  if (toggler === true){
    $("#magniText").append('<input class="formstyle" type="text" name="wikiFind" placeholder="***">') //if true adds input form field for user
$("#jiggyText").text("Random Article")
toggler = false;
  } else {
    $("input").detach() //removes user input here, unable to find another solution that retains user text input
    $("#jiggyText").text("")
    toggler = true
  }
};

$("#well").hover(wellToggle, wellToggle);

I know .remove() wipes the element completely but I was hoping .detach() would keep the text but it seems it only keeps data, I'm hoping to have the user input which replaces the *** hint to persist through .detach().

The closest i could find for a solution was this which checks for the text and only replaces in it's absence, but i need to keep the text.

Here's a link to my code


Solution

  • why not save the text in the input before removing it and then setting the text of the input on

    var toggler = true;
    var inputText ='';
    var wellToggle = function(){
      $("#well").toggleClass("toggleMe")
      if (toggler === true){
        $("#magniText").append('<input class="formstyle" type="text" name="wikiFind" placeholder="***">')
        $("#jiggyText").text("Random Article")
        $("input").val(inputText);
        toggler = false;
      } else {
        inputText = $("input").val()
        $("input").detach()
        $("#jiggyText").text("")
        toggler = true
      }
    };
    
    $("#well").hover(wellToggle, wellToggle);
    

    here is the code in paste bin http://jsbin.com/vozuheduti/edit?html,js,output