简体   繁体   中英

How to store data from html form in variable?

Basically there is a Google-like search bar, once the user hits submit I need to store it in a variable. There is more to the jQuery than below, but all it is is document.ready . The reason I need the data in a variable is because after that, I will use $.post and send it to my API.

("#form").submit( function(res) {
    var id = $(this).JSON.parse(data);

//Other attempted ways of getting input. 
    // $(this).data
    // $(this).data('button')
    // document.getElementById('id').value
    // $(this).getElementById('id').value
    // $(this).JSON.parse(data) -> "cannot parse undenfined, means no JSON data."


$.post('/search', {id: id }, function(data) { 
        data = JSON.parse(data);
        $("#count").text("we analyzed...");
        $("#result1".text(data));
        $("#totals").text("with a score of..");
        $("#result2").text(data);
    });
    res.redirect('/test/' + id);
});
<form id="form">
    <div class="featurette">
        <div class="featurette-inner text-center">
            <div class="search">
                <div class="input-group input-group-lg">
                    <span class="input-group-btn">
                        <button class="btn btn-danger" type="submit">Search</button>
                    </span>
                    <input type="text" name="id" input id="searchbar" class="form-control" placeholder="Enter your search term....">
                </div>
            </div>
        </div>
</form>

Firstly, note that your #form selector is missing the $ .

Assuming that you mean that you want to retrieve the value the user typed in the #searchbar input field, you can just use $('#searchbar').val() :

$("#form").submit( function(res) {
    var search = $('#searchbar').val();
    // use the 'search' variable as needed here...
    // $.post('url...', { searchTerm: search });
});

Also note that your HTML is invalid. You're missing a closing </div> and there is no input attribute on an input element. Try this:

<form id="form">
    <div class="featurette">
        <div class="featurette-inner text-center">
            <div class="search">
                <div class="input-group input-group-lg">
                    <span class="input-group-btn">
                        <button class="btn btn-danger" type="submit">Search</button>
                    </span>
                    <input type="text" name="id" id="searchbar" class="form-control" placeholder="Enter your search term...." />
                </div>
            </div>
        </div>
    </div>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM