简体   繁体   中英

Refresh page after selecting radio button but keep the radio button value

I'm creating a page where the user can select an option by clicking on a radio button. I want the page to refresh keeping the selected radio button value. These are my codes.

HTML

<div style="float:right">
    <label><input type="radio" name="colorRadio" value="f1">Option 1</label><br>
    <label><input type="radio" name="colorRadio" value="f2">Option 2</label><br>
    <label><input type="radio" name="colorRadio" value="f3">Option 3</label><br>
</div>

<div style="float:left;" class="f1 box">This is option 1</div>
<div style="float:left;" class="f2 box">This is option 2</div>
<div style="float:left;" class="f3 box">This is option 3</div>

JAVASCRIPT

 $('input[type="radio"]').click(function(){
        if($(this).attr("value")=="f1"){
            $(".box").hide();
            $(".f1").show();
        }

        if($(this).attr("value")=="f2"){
            $(".box").hide();
            $(".f2").show();
        }
        if($(this).attr("value")=="f3"){
            $(".box").hide();
            $(".f3").show();
        }

    });

CSS

 .box{
    padding: 20px;
    display: none;
    margin-top: 20px;
    border: 1px solid #000;
}

Is there aa way to reload just the div instead of refreshing the entire page?

If this is an HTML file, then use localStorage to store the <input> clicked by the value attribute and then when the page is loaded, run the onclick event of the right <input> element.

$(function() {
    $("input[type=\"radio\"]").click(function(){
        [...]
        //localStorage:
        localStorage.setItem("option", value);
    });
    //localStorage:
    var itemValue = localStorage.getItem("option");
    if (itemValue !== null) {
        $("input[value=\""+itemValue+"\"]").click();
    }
});

If this is run on a server, then use document.cookie to store the <input> clicked by the value attribute and when sending data to the client server-side, make the correct <input> checked and the correct box showing.

$(function() {
    $("input[type=\"radio\"]").click(function(){
        [...]
        //Cookies:
        document.cookie="option="+value;
    });
    //Cookies:
    /*Load the page with the correct input checked based off cookies*/
});

Here's the fiddle (unfortunately, cookies don't work here): http://jsfiddle.net/NobleMushtak/vTT7J/

autocomplete='on'属性添加到输入字段。

As your page will be refreshed new components will be created you can't persisit their value directly by using javascript , the value needs to be stored somewhere from where you can get your values later and reset value in your new radio button element.

In other words you want to save states of your objects in web application.For purpose of Maintaining state of object we have many methods as we often use request scope, Quesy String or a session.As your requirement is to save value only till next request(next page refresh) so for this purpose of maintaining that value for next page load you can use request scope or you need to add that value to your query string,in both of the ways you can get that value from request scope or query string and apply that value to your radio button.

How do I pass data between JavaScript pages?

  1. Submitting form data to a server-side script that then outputs a new JavaScript page containing the data. This is simple and reliable and works in all browsers, but requires support for server-side scripting of some kind (PHP, ASP, etc).

  2. Passing form-style data in a URL to a new JavaScript page, without using any server-side scripts. This works in all browsers but supports a limited amount of data. It is the traditional way of solving the problem without server-side scripting.

  3. Passing data via the window.name property. Although this is not the intended purpose of window.name, it seems to work quite well and supports larger amounts of data than the second method. And it works in Safari, Firefox, and Internet Explorer. So why not use it? Because it is highly insecure! If the user follows a link to another website that doesn't belong to you, that other website can still see the data stored in window.name, which was never meant to be a secure, site-specific property. So I strongly discourage the use of this method.

For refreshing the page, you can use in jquery location.reload(). For storing the radio button value which is clicked, you need to store the data in the local storage if you are not using server.

You can set the cookie when select radio button and then refresh the page. When page loads again read the cookie value and select radio button according to cookie value.

Load by $("#divWhichExcludesRadiobutton").load("current/url"); or add next script in the head tag

var myVal;
$("body").load("current/url", function () { $('input[type="radio"]').val(myVal) });
$('input[type="radio"]').on('change',function(){
       myVal = $(this).attr("value");
       if($(this).attr("value")=="f1"){
           $(".box").hide();
           $(".f1").show();
       }
       if($(this).attr("value")=="f2"){
           $(".box").hide();
           $(".f2").show();
       }
       if($(this).attr("value")=="f3"){
           $(".box").hide();
           $(".f3").show();
       }
});

Here's my solution to your problem: Fiddle

I used the localStorage to save which radioButton is checked with a fallback to cookies:

function saveData(key,value) {
   localStorage.setItem(key,value) || (document.cookie = key + "=" + value);
}

On page load, the data is loaded from the used storage to check the belonging button and to activate the appropriate box.

Plus I simplified your function setting the active box.

If you have any questions, feel free to ask.

Your JSP looks like this

<input type="radio" id="aa" name="Options" value="val1">radio 1
<input type="radio" id="bb" name="Options" value="val2"> radio 2
<input type="radio" id="cc" name="Options" value="val3"> radio 3

jQuery

$(function() {
    $("input[type=\"radio\"]").click(function(){
        var thisElem = $(this);
        var value = thisElem.val();
   alert('value'+value);
        localStorage.setItem("option", value);

    });
    var itemValue = localStorage.getItem("option");
    if (itemValue !== null) {
        $("input[value=\""+itemValue+"\"]").click();
    }

});

On load of page radio button will not reset as your using local storage to retrieve.

This will solve the issue

" class="fieldLabel" valign="middle">' key="label.portin.country" />:

                    <nested:present name="VoyagerSession" property="accountSummaryInfo.mspSummaryInfo.countryList">
                    <html:select tabindex="7" size="1" property="country" styleClass="field"  onchange= "Javascript:getstateList();javascript:selectPortInType();"> 
                    <bean:define id="countrylist" name="VoyagerSession" property="accountSummaryInfo.mspSummaryInfo.countryList" type="java.util.List" />
                    <html:options collection="countrylist" property="key" labelProperty="value" />
                    </html:select>
                    </nested:present>  

                    </td>
                   <td width="20%" align="<%= session.getAttribute("pageRight")%>" class="fieldLabel" valign="middle"><bean:message bundle='<%=session.getAttribute("pageBundle").toString()%>' key="label.portin.state" />:&nbsp;</td>
                   <td width="30%" valign="middle" class="field">
                    <html:select size="1" property="state" styleClass="field"> 
                      <bean:define id="statelist" name="VoyagerSession" property="accountSummaryInfo.mspSummaryInfo.stateList" type="java.util.List" />
                      <html:options collection="statelist" property="key" labelProperty="value" />
                      </html:select>
                   </td>
                </tr>

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