0

I'm trying to build a query parameter for when doing a search, I managed to build it with input field however there's a select dropdown menu to select other values.

<input type="text" id="dd">
<select name="" class="sel">
  <option value=""></option>
  <option value="Prepare">Prepare</option>
  <option value="Ready">Ready</option>
  <option value="Cancel">Cancel</option>
</select>

<button onclick="buildQuery()">Build query</button>

jQuery code for query building the query param

function buildQuery(){
  var result = "?";
  var getVal = $('input#dd').val();
  console.log('Input > ', getVal);
  var getSelectVal = $('select#sel').val();
  if (getVal != null && (getVal != "")) {
    let inputValues = getVal
    .split("\n")
    .filter(function (str) { return str !== "" })
    .join("&test=");
    // then add it to the overall query string for all searches
    result = result + 'test' + "=" + inputValues + "&";

    console.log('Results > ', result);
  }

Not sure how can I get the value from the select and construct it similar way to my input console.log output Results > ?test=f&

So if you fill in the input and select an option it the queryParam should say something like ?test=inputVal&test=selectVal or individual ?test=inputVal or ?test=selectVal

What I can do is copy the whole if() statement and replace the getVal with getSelectVal but it seems inefficient and duplicating the code.

Actual code --

newSearchParams.properties.forEach(function (inputSearch) {
        // first reparse the input values to individual key value pairs
        // Checks which field is not null and with empty string (space)
        var getVal = $('textarea.input_' + inputSearch.name).val();
        var getSelectVal = $('select.select_' + inputSearch.name).val();
        if (getVal != null && (getVal != "")) {
            let inputValues = getVal
                .split("\n")
                .filter(function (str) { return str !== "" })
                .join("&" + inputSearch.name + "=");
            // then add it to the overall query string for all searches
            result = result + inputSearch.name + "=" + inputValues + "&";
        }
    }, this);
    // remove trailing '&'
    result = result.slice(0, result.length - 1);
    return result;

Sample Fiddle

4
  • test=inputVal&test=selectVal is valid i mean same prop 2 values ? Commented Feb 3, 2017 at 13:24
  • yes I've tried and the select is valid and with proper values Commented Feb 3, 2017 at 13:28
  • Is this you trying to achieve jsfiddle.net/3wdecqe9/1 just remember to remove the last & symbol Commented Feb 3, 2017 at 13:29
  • not quite, that will only get the select value that will leave the input. Commented Feb 3, 2017 at 13:34

2 Answers 2

2

In case Shibi's answer passing test as array is not fine for some reasons,

The following serializes your two form elements' values into id=value&id2=value2 using jQuery.param():

function buildQuery(){
  var $elements = $('#dd, #sel'), //or your selector
      result = {};
  
    $elements.each(function(){
      if(this.value !== '') 
        result[this.id] = this.value; //uses id attribute as variable name
    });
  
    document.getElementById('log').innerHTML = '?' + $.param(result); //see jQuery.param() docs
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<input type="text" id="dd">
<select name="" id="sel">
  <option value=""></option>
  <option value="Prepare">Prepare</option>
  <option value="Ready">Ready</option>
  <option value="Cancel">Cancel</option>
</select>

<button onclick="buildQuery()">Build query</button>

<p id="log">(This element is here just for logging the result)</p>

Sign up to request clarification or add additional context in comments.

11 Comments

Interesting, ill give it a try. Yeah my first approach was to use jQuery but when I pass the queryString name jQuery.param({input.name:val}) something like that didn't accept it because of input.name
Yeah $.param look like its build for this reason. I would use it too. :)
See my edit above with my actual input and select code
@MrNew If you want to use a variable as an object key, first name that object ( var obj = {}), then use brackets: obj[yourVar] = 'some value'. This is already in the answer.
@MatveyAndreyev mind editing the answer using variable as an object key?
|
1

I will do it like this and then you can add more inputs as you wish..

function buildQuery(){
    var result = '?test=';
    var getVal = $('input#dd').val();
    var getSelectVal = $('select#sel').val();
    var resultArray = [getVal, getSelectVal]; // all values array
    resultArray = resultArray.filter(v=>v!=''); // filter empty results
    if(resultArray.length > 1) {
        result += resultArray.join("&test=");
    } else {
        result += resultArray[0];
    }

    result = encodeURI(result);
    console.log(result);
}

https://jsfiddle.net/3wdecqe9/6/

6 Comments

what's the weird encoded vals? ?test%5B%5D=s&test=1 is it possible to remove those and have a clean test=value instead? Looks like its the test[] can you explain that?
yes its because I did the test[] as an array so you could read all his values in the server side. its like when you doing form.serialize()
can it be just ?test=value instead?
I update the code so its be without the array now its ?test=value
Yeah get that remove [] will clean it, but what's with the encodURI(result)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.