Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text from user input variable not staying in div element

I am taking a variable from an HTML form element and trying to put it into a div to be displayed on the website whenever I click a button. However it shows up for a second then pops away.

I tried taking it out of the document.ready() block but that didn't work. When I put a string literal in the $(".output").html the same problem occurs as well. Similar questions like mine seem to be a syntax error, but I don't seem to have any I can find.

$(document).ready(function(){
  $(".sub").on("click",function(){
    var searchstring = $("#searchfield");
    $(".output").html(searchstring.val());
  });
});

Here is my site on codepen: http://codepen.io/arcjackson06/pen/NNeQvJ

like image 205
Acacia Holliday Avatar asked Apr 29 '26 01:04

Acacia Holliday


2 Answers

Your <button> will submit the surrounding form. You need to use:

<button class="..." type="button"></button>

Which will prevent the form from submitting when clicked.

Alternative you can prevent the default click event, with:

$('.sub').on('click', function(event) {
  event.preventDefault();
  // ...
like image 63
Andreas Louv Avatar answered May 01 '26 15:05

Andreas Louv


This should do the trick:

$(".sub").on("click",function(e)
{
    e.preventDefault();
    var searchstring = $("#searchfield").val();
    $(".output").html(searchstring);
}
like image 21
Billy Moat Avatar answered May 01 '26 13:05

Billy Moat