MARyan87
MARyan87

Reputation: 1806

Storing value in var from form submission with jQuery

I have looked at many answers and none seem to fit the issue. I have a simple search box and submit button, and want to store the value of the input field in a variable. It seems to store at first, then disappears. Code:

JavaScript

$(document).ready(function(){

    $('form').submit(function(){
        var input = $('#search').val();
        $('p').append(input);
    });
});

HTML

 <form>
    <input id='search' class='form-control' type='text' name='search'>
    <input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
 </form>
 <p></p>

The variable will display for a second and disappear, presumably when the search box becomes empty again.

Upvotes: 0

Views: 3054

Answers (3)

Ujwal Khairnar
Ujwal Khairnar

Reputation: 548

$(document).ready(function(){

    $('form').submit(function(){
        var input = $('#search').val();
        $('p').append(input);
        return false;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
    <input id='search' class='form-control' type='text' name='search'>
    <input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
 </form>
 <p></p>

Upvotes: 1

Haresh Vidja
Haresh Vidja

Reputation: 8496

For getting result you can do something like this

In HTML code

<form action="" method="get" id="search_form">
    <input id='search' class='form-control' type='text' name='search'>
    <input id='submit' type='submit' value='Submit' class='btn btn-lg btn-primary'>
 </form>
 <p></p>
<div id="search_result"></div>

in Javascript code

$('#search_form').submit(function(){
    var input = $('#search').val();
    $('p').text(input);
    $("#search_result").load($(this).attr("action")+ " #search_result", function(){
        alert("result loaded for "+ input)
    })
    return false;
});

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038750

The reason this happens is because when you submit a form the browser will send a new HTTP request to the server and reload your page. You could prevent this behavior by returning false from the submit handler:

$('form').submit(function() {
    var input = $('#search').val();
    $('p').append(input);
    return false;
});

or alternatively:

$('form').submit(function(e) {
    e.preventDefault();
    var input = $('#search').val();
    $('p').append(input);
});

This will prevent the page from reloading and the changes you did to the DOM will remain.

Upvotes: 3

Related Questions