How can I pre-populate html form input fields from url parameters?

前端 未结 3 444
再見小時候
再見小時候 2020-12-01 03:53

I have a vanilla html page which has a form in it. A requirement has come in to be able to pre-populate the form via the url. Something like:

http://some.s         


        
3条回答
  •  醉话见心
    2020-12-01 04:35

    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    
        for(var i = 0; i < hashes.length; i++)
            {
             hash = hashes[i].split('=');
             vars.push(hash[0]);
             vars[hash[0]] = hash[1];
             }
    
         return vars;
    }
    
    var get = getUrlVars();
    
    //returns get['forename'] == bob; surname == jones
    

提交回复
热议问题