Change Text Box Value Based on Select Input with Selected Attribute

后端 未结 7 1141
再見小時候
再見小時候 2020-12-14 23:03

I am attempting to change the value of a text input based on the user selecting a value from a pulldown. I have got it working using the following,



        
7条回答
  •  鱼传尺愫
    2020-12-14 23:47

    To remember the form values you can use cookie functions:

    $(document).ready(function() {
        var value = readCookie('fname');
        if (value) {
            $("#firstname").val(value);
            $('#name option[value="'+value+'"]').prop('selected', true);
        }
        $("#name").on("change", function() {
            var value = $(this).find("option:selected").attr("value");
            $("#firstname").val(value);
            createCookie('fname',value,31);
        });
    });
    
    function createCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }
    
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    

    jsfiddle - if you revisit this page, the name will be set back as on the page leave.

提交回复
热议问题