Juodvirshis
@Juodvirshis

Как передать выбранные значения Checkbox в строку Input через запятую?

(Checkbox)
один(checked)
два
три(checked)
(input)
один, три
  • Вопрос задан
  • 5082 просмотра
Решения вопроса 1
miraage
@miraage
Старый прогер
DEMO

<!DOCTYPE html>
<html>

  <head>
    <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script src="script.js"></script>
  </head>

  <body>
    <div>
      <input type="text" id="text-input" />
    </div>
    <div>
      <div>
        <label>
          <input type="checkbox" class="my-checkbox" value="1" />
          First
        </label>
      </div>
      <div>
        <label>
          <input type="checkbox" class="my-checkbox" value="2" />
          Second
        </label>
      </div>
      <div>
        <label>
          <input type="checkbox" class="my-checkbox" value="3" />
          Third
        </label>
      </div>
    </div>
  </body>

</html>


jQuery(function($) {
  var $text = $('#text-input'),
      $box = $('.my-checkbox');
  
  $box.on('click change', function() {
    var values = [];
    
    $box.filter(':checked').each(function() {
      values.push(this.value);
    });
    
    $text.val(values.join(','));
  });
});
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
DMShamonov
@DMShamonov
Frontend developer
Алгоритм такой - повесить событие на чекбокс, при его активации/деактивации найти все со статусом checked и из их содержимого построить нужного вида строку.
Ответ написан
@petya_petrelly
Демо
<form action="" method="" accept-charset="utf-8">
	<input type="checkbox" name="option1" value="1">
	<input type="checkbox" name="option2" value="2">
	<input type="checkbox" name="option3" value="3">
	<input type="checkbox" name="option4" value="4">
	<input type="text">
	<input type="submit" value="Отправить">
</form>

<script>

var GetValue = (function() {
  function GetValue() {
    this.init();
    this.events();
  }

  GetValue.prototype.init = function() {
  	this.form = document.querySelector('form');
  	this.textInput = this.form.querySelector('input[type="text"]');
  	this.checkboxes = [].slice.call(this.form.querySelectorAll('input[type="checkbox"]'));
  	this.arraySelected = new Array();
  };

  GetValue.prototype.events = function() {
  	return this.checkboxes.forEach((function(_this) {
  	  return function(el) {
	      return el.addEventListener('click', function() {
	        return _this.set(el);
	      });
  	  };
  	})(this));
  };

  GetValue.prototype.set = function (el) {
  	if (this.arraySelected.indexOf(el.value) >= 0) {
  		this.arraySelected.splice(this.arraySelected.indexOf(el.value), 1);
  		this.textInput.value = this.arraySelected;
  	} else {
  		this.arraySelected.push(el.value)
  		this.textInput.value = this.arraySelected;
  	}
  };

  return GetValue;

})();

new GetValue();

</script>
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы