1

Example code:

<form method="get">
<input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
<input type="checkbox" name="anythingOne[]" value='two'>
<input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->

<input type="checkbox" name="otherThingTwo[]" value='Forty'>
<input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->
</form>

On form submission the URL should look like:

http://some-website.tld/action?anythingOne=one,three&otherThingTwo=Fifty

What I am observing now is,

http://some-website.tld/action?anythingOne=one&anythingOne=three&otherThingTwo=Fifty

The serialize() or serializeArray() is not working in this case. Any ideas?

5
  • The result that you are observing now is valid. It will be correctly parsed on server-side as an array of strings. Why do you want to use specific format? Commented Oct 14, 2018 at 8:29
  • The URL may be shared in social sites and or among the visitors. So the expectation format may look more meaningful than the actual one. Commented Oct 14, 2018 at 9:07
  • If i remember right using array's on name's is only useful when using PHP. With JS you can do better than that. I would just select all the input-fields $('input[type="checkbox"]') and then filter and loop them by each unique name separately. See about filter developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 14, 2018 at 10:29
  • I have a feeling you should be handling the arrays server side rather than modifying with your query string. is this submitting to a php script or something else? if you really want a comma separated list of values in the end it would be easy enough to do something like implode(',',$_GET['anythingOne']) if it's php Commented Oct 14, 2018 at 11:13
  • Possible duplicate of How to Create query string in jquery? Commented Oct 21, 2018 at 15:02

5 Answers 5

0

You could grab the result of .serializeArray and transform it into the desired format:

$(function() {
  $('form').on('submit', function(e) {
    e.preventDefault();
    var data = $(this).serializeArray();
    
    var dataByKey = data
      .reduce((result, entry) => {
        var name = entry.name.replace(/\[\]$/, '');
        (result[name] || (result[name] = [])).push(entry.value);
        return result;
      }, {});
      
    Object.keys(dataByKey)
      .forEach((key, _) => dataByKey[key] = dataByKey[key].join(','));
    
    console.log(dataByKey);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
  <fieldset>
    <input type="checkbox" name="anythingOne[]" value='one'>1
    <input type="checkbox" name="anythingOne[]" value='two'>2
    <input type="checkbox" name="anythingOne[]" value='three'>3
  </fieldset>

  <fieldset>
    <input type="checkbox" name="otherThingTwo[]" value='Forty'>40
    <input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
  </fieldset>
  
  <input type="submit" />
</form>

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

Comments

0

If you want, you can also use pure javascript without jQuery to get all the checked checkboxes' value, http://jsfiddle.net/jx76dpkh/1/

<form id="myForm" method="get">
         <input type="checkbox" name="anythingOne[]" value='one'>1
         <input type="checkbox" name="anythingOne[]" value='two'>2
         <input type="checkbox" name="anythingOne[]" value='three'>3
         <input type="checkbox" name="otherThingTwo[]" value='Forty'>40
         <input type="checkbox" name="otherThingTwo[]" value='Fifty'>50
         <input type="submit" />
</form>

JS:

const myForm = document.getElementById('myForm');
myForm.addEventListener('submit', (e) => {
     e.preventDefault();
     let checkboxes = Array.from(myForm.querySelectorAll('input[type="checkbox"]:checked');// build the array like element list to an array
     let anythingOne = checkboxes.filter( box => box.name === 'anythingOne[]').map(item => item.value);
     let otherThingTwo = checkboxes.filter( box => box.name === 'otherThingTwo[]').map(item => item.value);
});

Comments

0

In case, you are allowed to change html, here is a solution using hidden fields.

function updateChecks() {

  $.each(['anythingOne', 'otherThingTwo'], function(i, field) {
    var values = $('input[type=checkbox][data-for=' + field + ']:checked').map(function() {
      return this.value;
    }).get().join(',');
    $('input[type=hidden][name=' + field + ']').val(values);

  });
}
$(function() {
  $('form').on('submit', function(e) {
    updateChecks();
  });
  updateChecks();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
  <input type="hidden" name="anythingOne" value='' />
  <input type="hidden" name="otherThingTwo" value='' />
  <input type="checkbox" data-for="anythingOne" value='one' checked='' />
  <input type="checkbox" data-for="anythingOne" value='two' />
  <input type="checkbox" data-for="anythingOne" value='three' checked='' />
  <input type="checkbox" data-for="otherThingTwo" value='Forty' />
  <input type="checkbox" data-for="otherThingTwo" value='Fifty' checked='' />
</form>

Comments

0

You could get query string parameters using by serializeArray() method. Then use reduce() to group parameter values by name, and map() to get array of key-value pairs. Then it is possible to concatenate the pairs separated by & using join() method. For example the following snippet creates a target URL using actual value of the form action (current URL by default) and values of checked checkboxes:

$('form').submit(function() {
  var queryString = $(this).serializeArray()
    .reduce(function(transformed, current) {
      var existing = transformed.find(function(param) {
        return param.name === current.name;
      });
      if (existing)
        existing.value += (',' + current.value);
      else
        transformed.push(current);
      return transformed;
    }, [])
    .map(function(param) {
      return param.name + '=' + param.value;
    })
    .join('&');
  var action = $(this).prop('action');
  var delimiter = (~action.indexOf('?')) ? '&' : '?';
  $(this).prop('action', action + delimiter + queryString);
  
  // Only for display result. Remove on real page.
  var url = $(this).prop('action');
  console.log(url);
  return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="GET">
  <input type="checkbox" name="anythingOne" value='one'>
  <input type="checkbox" name="anythingOne" value='two'>
  <input type="checkbox" name="anythingOne" value='three'>

  <input type="checkbox" name="otherThingTwo" value='Forty'>
  <input type="checkbox" name="otherThingTwo" value='Fifty'>

  <button type="submit">Show target URL</button>
</form>

The latest 3 lines are used only to prevent the form sending and display resulted URL.

Also it is possible to solve the question using only serialize() mathod and regular expressions, but it requires lookbehind assertion support in browsers.

Comments

0

You can collect all the checked boxer and join the different parts of the strings.This may not be the most neat or efficient solution, but it works. I used a button to trigger the concatenation. See my comments within the code.

$(document).ready(function(){
	$("button").click(function(){
		/* concatenate anythingOne form*/
		//collect anythingOne input
		var joined_serialized = []
		var anythingOne = [];
		$.each($("input[name='anythingOne[]']:checked"), function(){            
			anythingOne.push($(this).val());
		});
		//join otherThingTwo input
		var anythingOne_serialized = "";
		if(anythingOne.length > 0){ //only collect if checked
			anythingOne_serialized =  "anythingOne=" + anythingOne.join(",");
			joined_serialized.push(anythingOne_serialized)
		}
		
		/* concatenate otherThingTwo form*/
		//collect otherThingTwo input
		var otherThingTwo = []
		$.each($("input[name='otherThingTwo[]']:checked"), function(){            
			otherThingTwo.push($(this).val());
		});
		//join otherThingTwo input
		var otherThingTwo_serialized = "";
		if(otherThingTwo.length > 0){ //only collect if checked
			otherThingTwo_serialized =  "otherThingTwo=" + otherThingTwo.join(",");
			joined_serialized.push(otherThingTwo_serialized)
		}
		
		/*join different form names*/
		var joined_serialized = joined_serialized.join("&")
		
		if(joined_serialized.length == 1){ //remove last & if only one form is checked
			joined_serialized = joined_serialized.slice(0, -1)
		}
		
		/*concatenated forms with website*/
		var result = "http://some-website.tld/action?"+joined_serialized
		console.log(result) //E.g. when Two, Three and Forty are checked: http://some-website.tld/action?anythingOne=two,three&otherThingTwo=Forty 
	})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
    <input type="checkbox" name="anythingOne[]" value='one'> <!-- checked -->
    <input type="checkbox" name="anythingOne[]" value='two'>
    <input type="checkbox" name="anythingOne[]" value='three'> <!-- checked -->
    <input type="checkbox" name="otherThingTwo[]" value='Forty'>
    <input type="checkbox" name="otherThingTwo[]" value='Fifty'> <!-- checked -->      
</form>
<button>submit<button/>

Comments

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.