Skip to content Skip to sidebar Skip to footer

Build URL From Form Fields With JavaScript Or JQuery

I'm trying to create a URL builder form with JavaScript or jQuery. Basically, it will take the value of the two form fields, add them to a preset URL and show it on a third field o

Solution 1:

jQuery has serialize which builds the query string values.

So if you want to do the entire form:

alert($("#form1").serialize());

If you want to do only a few fields, then just make the selector select those fields.

alert($("#variable1, #variable2").serialize());

Solution 2:

Use something like...

var inputs = $('#form1').find('input[type=text]').not('#url');
var str = "http://www.base.url/path/file.ext?"
inputs.each(function (i, item) {
    str += encodeURIComponent(item.name) + "=" + encodeURIComponent(item.value) + "&";
});
$('#url').val(str);

This will select all <input>s on in form1 with type='text', and concatenate them into a query string. See encodeURIComponent().


Orrrr.....you could just use .serialize(). Thank you, prodigitalson.


Solution 3:

Something like the following should work:

var partFields = '#variable1,#variable2';

$(partFields).change(function(){
  var url = 'static/URL/to/file.php?';
  $('#url').val(url + $(partFields).serialize());
});

However, unless you want people to be able to override the URL, you might want to use a hidden field and a regular element for display and submission of the URL value in which case you'd have something like the following:

var partFields = '#variable1,#variable2';

$(partFields).change(function(){
  var url = 'static/URL/to/file.php?';
  var urlValue = url + $(partFields).serialize();
  $('#url-display').text(urlValue); // Set the displaying element
  $('#url').val(urlValue); // Set the hidden input value
});

Post a Comment for "Build URL From Form Fields With JavaScript Or JQuery"