0

Is there a way I can split the query part of an input field into variables and it's associated value into new input fields?

Let's say I have an input field like:

<input type="text" name="sUrl" value="http://site.com/index.php?var1=1&var2=1&var3=foo" />

What I'm trying to achieve is that jQuery turns the query into:

<input type="text" name="var1" value="1" />
<input type="text" name="var2" value="1" />
<input type="text" name="var3" value="foo" />

In PHP I could do an explode on the query part but sadly php!=jquery, what would be the best way to get this done?

Thanks in advance.

JustaN00b
  • 317
  • 3
  • 6
  • 19
  • Yeah, bummer. PHP + jQuery = *asplode*. Soo would be worth like 50 rainbow unicorns. Sad, really. – Jared Farrish Jan 12 '13 at 18:37
  • The hardest part is actually parsing the request parameters from the URL. Don't use regular expressions or string operations - let the browser do the hard work for you. This has been covered on the site before; see http://stackoverflow.com/a/6168370/221061 for the best example I could find. – Chris Laplante Jan 12 '13 at 18:39
  • Why not have php do it before you output the html in first place??? Crazy. – keyboardSmasher Jan 12 '13 at 18:44

1 Answers1

0

Try this:

<script>
function myfunction() {
    var target = $('body');
    var input = $('#myinput');
    var pathname = input.val();

    pathname = pathname.replace('?','');
    pathname = pathname.split('&');

    $(pathname).each(function() {
        var request = this.split('=');
        $('<input>',{type:'text',name:request[0],value:request[1]}).appendTo(target);
    });

    return false;
}
</script>

<form onsubmit='return myfunction();'>
   <input type='text' id='myinput'>
</form>

Replace the $('body') with your actual target and $('#myinput') with your input.

Felipe Francisco
  • 1,064
  • 2
  • 21
  • 45