Как объединить входные данные массива формы перед отправкой? - PullRequest
0 голосов
/ 14 октября 2018

Пример кода:

<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>

При отправке формы URL должен выглядеть следующим образом:

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

То, что я сейчас наблюдаю,

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

serialize() или serializeArray() в этом случае не работает.Есть идеи?

Ответы [ 5 ]

0 голосов
/ 14 октября 2018

Если вам разрешено изменять html, вот решение с использованием скрытых полей.

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>
0 голосов
/ 14 октября 2018

Вы можете получить параметры строки запроса, используя метод serializeArray().Затем используйте reduce() для группировки значений параметров по имени и map() для получения массива пар ключ-значение.Затем можно объединить пары, разделенные &, используя метод join().Например, следующий фрагмент создает целевой URL-адрес, используя фактическое значение формы action (текущий URL-адрес по умолчанию) и значения отмеченных флажков:

$('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>

Последние 3 строки используются только для предотвращения отправки формы и отображения приведенного URL.

Также можно решить вопрос, используятолько serialize() выражения и регулярные выражения, но для этого требуется поддержка утверждений в браузерах.

0 голосов
/ 14 октября 2018

Вы можете получить результат .serializeArray и преобразовать его в нужный формат:

$(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>
0 голосов
/ 14 октября 2018

Если хотите, вы также можете использовать чистый javascript без jQuery, чтобы получить значение всех отмеченных флажков, 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);
});
0 голосов
/ 14 октября 2018

Вы можете собрать всех отмеченных боксеров и join различных частей строк. Это может быть не самым аккуратным или эффективным решением, но оно работает.Я использовал кнопку, чтобы вызвать объединение.Смотрите мои комментарии в коде.

$(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/>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...