0

I'm using MailChimp to merge fields into a URL directing people to complete a form on my site. I want to prepopulate the text boxes with the information from the URL.

ex: http://www.sitename.com/page?fname=John&lname=Smith&email=jsmith@email.com

I'm a novice at this and not sure what I'm doing wrong here. Here's my core code:

<head>

<script>
$.extend({
  getUrlVars: function(){
    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;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
</script>

</head>

<body>

    <form id="form_id_name" method="POST" action="/forms/users">

    <label for="fname">First Name:</label>
    <input required="" class="text" id="user_first_name" name="user[first_name]" type="text" />

<script>
$("#user_first_name").val($.getUrlVar("fname"));
</script>  

    <label for="lname">Last Name:</label>
    <input class="text" id="user_last_name" name="user[last_name]" type="text" />

<script>
$("#user_last_name").val($.getUrlVar("lname"));
</script>  

    <label for="email">Email Address:</label>
    <input class="text" id="user_email" name="user[email]" type="email" />

<script>
$("#user_email").val($.getUrlVar("email"));
</script> 

    <input type="submit" name="commit" value="Submit" />

  </form>

</body>
  • It appears as though you're using jQuery, but I don't think you're using it correctly. `$.extend` returns an object that merges the properties of two objects. You only have one object, and don't use the outputted object. I'd make it easier on yourself and use a URL parsing library like [url.js](http://jillix.github.io/url.js/) or something. – Heretic Monkey Apr 07 '17 at 17:26

1 Answers1

0

The problem is, as @Mike McCaughan mentiones, you are extending nothing. As far as I can see where you used that function, you are trying to create a jquery function/plugin. Try this instead

$.fn.extend({
  getUrlVars: function(){
    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;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
serdar.sanri
  • 2,217
  • 1
  • 17
  • 21