如何在提交表单后保留选定的值--JQuery

时间:2016-04-21 19:53:09

标签: javascript jquery

我有一张表格:

<form id="new_user" class="simple_form new_user" method="post" accept-charset="UTF-8" action="/admin/stats" novalidate="novalidate">
    <div class="col-lg-4">
        <h2>Stats by:</h2>
        <div class="col-md-10 col-sm-10">
            <div class="form-group country optional user_country">
                <select id="user_country" class="country optional wabi-form-control select form-control" name="user[country]">
            </div>
        </div>
        <div class="col-md-10 col-sm-10">
            <input class="btn btn-wabi btn-block" type="submit" value="Show Stats" name="commit">
        </div>
    </div>
</form>'

在点击user_country按钮后,我是否保持Show Stats的选定值?

3 个答案:

答案 0 :(得分:0)

使用PHP,将其放入select / input:

value="<?php echo isset($_POST['user_country']) ? $_POST['user_country'] : '' ?>"

使用Javascript:

document.getElementById("user_country").value = localStorage.getItem("user_country");

function saveInput() {
    var country = document.getElementById("user_country").value;
    if (country == "") {
        alert("Please select a country first!");
        return false;
    }

    localStorage.setItem("user_country", country);
    alert("Your country has been saved!");

    location.reload();
    return false;
    //return true;
}

答案 1 :(得分:0)

你总是可以使用AJAX(通过jQuery)。

$('.btn-wabi').on('click', function (evt) {
    evt.preventDefault():

$.post('/admin/stats')
   .success(function (result) {
        $('#somdivID').html(result);
   });
});

答案 2 :(得分:0)

只需使用jquery访问该值:

https://jsfiddle.net/voeo8j7p/

HTML:

<form id="new_user" class="simple_form new_user" method="post" accept-charset="UTF-8" action="/admin/stats" novalidate="novalidate">
    <div class="col-lg-4">
        <h2>Stats by:</h2>
        <div class="col-md-10 col-sm-10">
            <div class="form-group country optional user_country">
                <select id="user_country" class="country optional wabi-form-control select form-control" name="user[country]">
    <option value="1">USA</option>
    <option value="2">Mongolia</option>
    <option value="3">Egypt</option>
                </select>
            </div>
        </div>
        <div class="col-md-10 col-sm-10">
            <a id="showCountryLink" class="btn btn-wabi btn-block">Show Stats</a>
        </div>
    </div>
    <div id="current_country_div"></div>
    Current Country: <input id="current_country" val="">
</form>

JS:

 var current_country = "";

    $('#showCountryLink').click(function(evt) {
        evt.preventDefault();

         console.log("Showing country");
         current_country =  $( "#user_country" ).val();
         $("#current_country_div").html("Current Country: " + current_country);
         $("#current_country").val(current_country);
    });