Build URL from form fields with JavaScript or jQuery

后端 未结 3 991
时光取名叫无心
时光取名叫无心 2021-02-07 06:22

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 th

3条回答
  •  梦如初夏
    2021-02-07 06:52

    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
    });
    

提交回复
热议问题