dqwcdqs358367 2015-03-14 17:56
浏览 717
已采纳

触发单击单选按钮,并在页面刷新时记住选择

This question is not duplicated.

I have two radio buttons (radio1, radio2).

I was able to achieve the following, BUT separately:

  1. Trigger a click on "radio1" on page load. So whenever the page is loaded, the button is clicked.
  2. Remember the selected radio button that is manually clicked by user, using local storage described in this answer by Joseph Silber. So if the user manually clicked on "radio2" and then refreshed the page, it remembers that selection.

The problem is that I cannot use both methods at the same time. Because the triggered click always takes over the local storage, which makes the selected radio button not remembered when page is refreshed.

I need "radio1" to be clicked (not checked) on page load by default, but when the user manually clicks on "radio2" it remembers that selection, and whenever the page is refreshed the "radio2" will be clicked with respect to the user's selection.

I tried a lot to make a combination of codes I have to get them both works together, but I couldn't figure it out.

The code for trigger a click on radio button on page load:

<script type="text/javascript">
$(document).ready(function() {
  $("#radio1 input:radio").click(function() {
    alert("clicked");
   });
  $("input:radio:first").prop("checked", true).trigger("click");
});
</script>

The code for local storage; remembering radio selection:

<script type="text/javascript">
$(function()
{
    $('input[type=radio]').each(function()
    {
        var state = JSON.parse( localStorage.getItem('radio_'  + this.id) );

        if (state) this.checked = state.checked;
    });
});

$(window).bind('unload', function()
{
    $('input[type=radio]').each(function()
    {
        localStorage.setItem(
            'radio_' + this.id, JSON.stringify({checked: this.checked})
        );
    });
});
</script>

Again, they both works fine but separately, either one of them will work.

If anyone can help me to make both methods work together, I will really appreciate it.

  • 写回答

1条回答 默认 最新

  • douguai7291 2015-03-14 18:20
    关注

    Why not just set the default radio :checked property but .trigger('click') ?

    $(function(){
        //state default radio ':checked' property there:
        $("input:radio:first").prop("checked", true);
    
        $("#radio1 input:radio").click(function() {
            alert("clicked");
        });
    
        // overwrite radio ':checked' property there (if exists in localStorage) :
        $('input[type=radio]').each(function(){
            var state = JSON.parse( localStorage.getItem('radio_'  + this.id) );
    
            if (state) this.checked = state.checked;
        });
    });
    
    $(window).bind('unload', function(){
        $('input[type=radio]').each(function(){
            localStorage.setItem(
                'radio_' + this.id, JSON.stringify({checked: this.checked})
            );
        });
    });
    

    JSFiddle


    Or, if you need to trigger an event handler for default radio (as you do in your code using .trigger('click')) on DOM ready, use this:

    $(function(){
        //state default radio ':checked' property there and run its `click` event handler:
        radioClick.call($("input:radio:first").prop("checked", true));
    
        $("#radio1 input:radio").click(radioClick);
    
        // method triggered on radio click, will skip the localStorage modification:
        function radioClick() {
            // you can refer here to 'this' as to clicked radio
            alert($(this).val());
        }
    
        // overwrite radio ':checked' property there (if exists in localStorage) :
        $('input[type=radio]').each(function(){
            var state = JSON.parse( localStorage.getItem('radio_'  + this.id) );
    
            if (state) this.checked = state.checked;
        });
    });
    
    $(window).bind('unload', function(){
        $('input[type=radio]').each(function(){
            localStorage.setItem(
                'radio_' + this.id, JSON.stringify({checked: this.checked})
            );
        });
    });
    

    JSFiddle


    Alternatively, and even better, set the default radio checked property right in the HTML:

    <input type=radio id=radio1 value=radio1 name=radio checked />
    <input type=radio id=radio2 value=radio2 name=radio />
    <input type=radio id=radio3 value=radio3 name=radio />
    ...
    

    So that you have it checked natively, not programatically. Then overwrite its prop depends on what is in the localStorage


    EDIT (OP comment to the answer)

    $(function () {
    
        $('input[type="radio"]').click(function () {
            localStorage.setItem('radioIdSelected', $(this).attr('id'));
            // your method to run on selected radio button (alert for demo):
            alert($(this).attr('id'));
        });
    
        var storageRadio = localStorage.getItem('radioIdSelected');
    
        if (storageRadio !== null && storageRadio !== undefined && $('#' + storageRadio).length) {
            $('#' + storageRadio).trigger('click');
        } else {
            $('input[type="radio"]:first').trigger('click');
        }
    
    });
    

    JSFiddle

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败