MrNew
MrNew

Reputation: 1414

jquery select option to construct queryString

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

Upvotes: 0

Views: 70

Answers (2)

Shibi
Shibi

Reputation: 1383

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/

Upvotes: 1

Matvey Andreyev
Matvey Andreyev

Reputation: 1061

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>

Upvotes: 2

Related Questions