<!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(','));
});
});
<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>