A
A
Andmax2015-03-10 21:13:45
JavaScript
Andmax, 2015-03-10 21:13:45

How to pass parameters from form to URL?

There is this form:

<form role="form" action="catalog/vse-tovaryi/">
  <select name="ms|price">
      <option value="">Любая</option>
      <option value="500">500 рублей</option>
  </select>
        <select name="msoption|tags">
      <option value="1">Тэг 1</option>
      <option value="2">Тэг 2</option>
  </select>

  <button type="submit">Подобрать</button>
</form>


We choose the price of 500 rubles,
when we click on the button, we go to the page catalog/vse-tovaryi/?ms|price=500&msoption|tags=1

And if we choose "Any", we go to catalog/vse-tovaryi/?ms|price= &msoption|tags=1

Q: How do I not print this "ms|price=" option in the URL at all if a value with an empty value is selected?
So that when choosing the price "Any" during the transition, the link would be like this: catalog/vse-products/?msoption|tags=1

I searched all over google, I did not find the answer.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Mikhail Goryachkin, 2015-03-10
@Andmax

Here's an example dashed off:
HTML:

<form role="form" id="form" action="catalog/vse-tovaryi/" data-def="catalog/vse-tovaryi/">
  <select name="ms|price">
      <option value="">Любая</option>
      <option value="500">500 рублей</option>
  </select>
        <select name="msoption|tags">
      <option value="1">Тэг 1</option>
      <option value="2">Тэг 2</option>
  </select>

  <button type="submit">Подобрать</button>
</form>

JS:
window.onload = function () {
  var form = $('#form'), def = form.data('def'), data = {}, action;
  
  $(document).on('change', '#form select', function () {
  	var el = $(this), val = el.val(), name = el.attr('name');
    if (val) {
    	data[name] = val;
    } else {
      delete data[name];
    }
    action = def + "?";
    for(var i in data) {
      action += i + "=" + data[i] + '&';
    }
    action = action.substr(0, action.length - 1);
    form.attr('action', action);
  });
};

The point is to generate the url you need and substitute it in the action attribute of your form, and therefore, after clicking on the submit button, you will go to the right place.

E
entermix, 2015-03-10
@entermix

You can remove this select when clicking on the submit button of the form JS script

G
Gluck Virtualen, 2015-03-10
@gluck59

Isn't it easier on the handler side to simply ignore the "empty" argument?
I suspect that this has already been done, and your real task is beyond the scope of your question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question