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

前端 未结 3 416
再見小時候
再見小時候 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:25

    Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:

    <?php
    $forename = $_GET['forename'];
    $surname = $_GET['surname'];
    ?>
    ----------
    <input id='forename' type='text' value='<?php echo $forename; ?>' >
    <input id='surname' type='text' value='<?php echo $surname; ?>' >
    

    That should pre-populate for you.

    0 讨论(0)
  • 2020-12-01 04:29

    Use a custom query string Javascript function.

    function querySt(ji) {
    
        hu = window.location.search.substring(1);
        gy = hu.split("&");
    
        for (i=0;i<gy.length;i++) {
            ft = gy[i].split("=");
            if (ft[0] == ji) {
                return ft[1];
            }
        }
    }
    var koko = querySt("koko");
    

    Then assign the retrieved value to the input control; something like:

    document.getElementById('mytxt').value = koko;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题