Filling out a form from the URL

2019-09-07 05:18发布

问题:

I have an HTML page with a form, containing only one field. The submit doesn't actually do a page refresh, but rather does local JavaScript processing.

This works great, but has one downside: you can't give someone a URL with the form presubmitted (e.g. http://example.com/myform?field=val).

How can I tell jQuery that, on load, if the URL contains ?field=[val], to fill field with val and then do the submit JavaScript action?

(Bonus points if you can do this in reverse as well: when you submit, change the URL in the location bar from http://example.com/myform to http://example.com/myform?field=[val], without doing a page refresh)

回答1:

Untested, but maybe something like this:

// Setup a document ready to run on initial load
$(document).ready(function() {
    var urlParams = getUrlParams()
        , form;

    // Only proceed if there are URL params
    // Note this assumes that all URL params are valid input fields in your form, that they have been decoded, and that all the fields you need are there. Adjust accordingly.
    if (urlParams) {
        form = $('#your_form');
        $.each(urlParams, function(field, value) {
            form.find('input[name="' + field + '"]').val(value);
        });

        // Trigger your event listener
        form.submit();
    }
});

Also see here for a starting point on possible getUrlParams function.



回答2:

I have an answer.

$(document).ready(function(){
    var r = /[?|&](\w+)=(\w+)+/g;  //matches against a kv pair a=b
    var query = r.exec(window.location.href);  //gets the first query from the url
    while (query != null) {

            //index 0=whole match, index 1=first group(key) index 2=second group(value)
        $("input[name="+ query[1] +"]").attr("value",query[2]);

        query = r.exec(window.location.href);  //repeats to get next capture

    }



//handles when someone clicks a input button with id submit
$('#submit').click(function(){

    var url = window.location.pathname + "?";
    $("input[name]").each(function(){
      if (this.value)  //if the forms have values
         url += $(this).attr('name') + "=" + this.value + "&";  //appends the name and value
    });
    history.replaceState("hstory", "", url.substring(0, url.length - 1));   //changes the url without reloading and removes last &
  });

});

The first part handles the getting of values from the url and inserting them into the form inputs, while the second handles reloading values into the url when a person hits a button with the id of submit.