Как получить счетчик при изменении формы входов, выбора и т. Д. - PullRequest
0 голосов
/ 16 апреля 2019

	var inpts = $('.map-form .val-input');
	var radio = $('.map-form .radio-input');
	var counter = $('.filtr-map-count');

	$('.detect-change').change(function() { 
		countInputs();
	});


	function countInputs() {
		var click = 0; 
			$(inpts).each(function(){
				if($(this).val() != ""){
					click++;
				} 
				counter.text(click);
			});

			$(radio).each(function() {
				if($(this).val() != ""){
					click++;
				} 
				counter.text(click);
			});
	};


	$(window).on('load', function() { 
			countInputs();
		});
.filtr-map {
			background-color: red;
			width: 100px;
			height: 40px;
			color: #fff;
			z-index: 99;
			font-weight: bolder;
			cursor: pointer;
			display: flex;
			justify-content: center;
			align-items: center;
      margin-top: 50px;
		}

		.filtr-map-count {
			font-size: 10px;
			position: relative;
			top: -5px;
			left: 5px;
			background-color: #000;
			border-radius: 50%;
			width: 20px;
			height: 20px;
			display: flex;
			align-items: center;
			justify-content: center;
		}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class='map-form'>
		<div>
			<h2>Search</h2>
			<fieldset>
				<label>Price</label>
				<span>min</span>
				<input type="text" class='val-input detect-change ' value="" />
				<span>max</span>
				<input type="text" class='val-input detect-change ' value="" />
			</fieldset>
			<fieldset>
				<label>Category</label>
				<div class="styled_select">
					<select class='val-input detect-change '>
						<option value="">Default</option>
						<option value="1">Option 1</option>
						<option value="2">Option 2</option>
					</select>
				</div>
			</fieldset>
			<fieldset>
				<div class="styled_radio"><input class='radio-input detect-change' checked="checked" type="radio" id="Radio1" name="Radio" /><label
						class="input" for="Radio1"><span class="circle"><span></span></span><span>Test One Test</span></label></div>
				<div class="styled_radio"><input class='detect-change' type="radio" id="Radio2" name="Radio" /><label class="input"
						for="Radio2"><span class="circle"><span></span></span><span>Test test</span></label></div>
			</fieldset>
			<input type="submit" value='Send'>
		</div>
	</form>

			<div class="filtr-map">
				Filter<span class='filtr-map-count'>0</span>
			</div>

Эй, как получить счетчик, когда входы, выбор и т. Д. Меняются в форме? Как сделать счетчик. Если изменение входа / выбора / радио в счетчике набора полей должно увеличиться, если вернуться к значению по умолчанию, уменьшится. Номер счетчика также должен работать после перезагрузки страницы. Я добавил js-код, над которым я работаю, но что-то идет не так.

--- UPDATE --- Я добавил рабочий код jquery для этого примера, может быть, он будет полезен для кого-то еще. Также я добавил классы, которые помогают с выбором измененных элементов.

1 Ответ

1 голос
/ 16 апреля 2019

Хорошо, так что это становится немного сложнее, если вы рассматриваете все типы ввода.

Я написал код ниже в качестве отправной точки. Да, он делает то, что вам нужно. НО он не был полностью протестирован и может быть улучшен.

См. Рабочий пример здесь: https://jsfiddle.net/hber3q0z/

JQuery, который делает тяжелую работу ...

var $form = $('.map-form');
var $counter = $('.filtr-map-count');
var changed = {};

// Listen for an `update` event on counter element
$counter.on('update', function() {
  // Update the text value
  $(this).text(function() {
    var count = 0;
    // Loop through the `changed` object and count if value has changed
    $.each(changed, function(key, hasChanged) {
      if (hasChanged) {
        count++;
      }
    });

    // Return count
    return count;
  });
});

// Find all form inputs
$form.find(':input').each(function(key) {
  var $this = $(this);
  // Get the input name, else create a temporary name
  var name = $this.attr('name') || new Date().getTime().toString() + key;

  // Store the original value
  var original = $this.val();

  // If the input is a checkbox
  if ($this.is(':checkbox')) {

    // Create a function to get checkbox group values
    var checkboxValue = function() {
      var values = [];
      // Find all `checked` inputs with the same type and name
      $form.find('[type="' + $this.attr('type') + '"][name="' + $this.attr('name') + '"]:checked').each(function() {
        // Push values to array
        values.push($(this).val());
      });
      // Join them for easier comparisom
      return values.join(',');
    };

    // Store original group value
    original = checkboxValue();

    // Listen to checkbox events
    $this.on('change keyup keydown mouseup', function() {
      // Perform value changed check
      changed[name] = checkboxValue() !== original;

      // Tell the counter element to update contents
      $counter.trigger('update');
    });

  }

  // If the input is a radio
  else if ($this.is(':radio')) {

    // Create a function to get radio group value
    var radioValue = function() {
      // Find the first `checked` input with the same type and name
      return $form.find('[type="' + $this.attr('type') + '"][name="' + $this.attr('name') + '"]:checked').val();
    };

    // Store original group value
    original = radioValue();

    // Listen to radio input events
    $this.on('change keyup keydown mouseup', function() {
      // Perform value changed check
      changed[name] = radioValue() !== original;

      // Tell the counter element to update contents
      $counter.trigger('update');
    });
  }

  // Catch-all other input types
  else {

    // Listen to input events
    $this.on('change keyup keydown cut paste', function() {
      // Perform value changed check
      changed[name] = $this.val() !== original;

      // Tell the counter element to update contents
      $counter.trigger('update');
    });
  }
});

Код проверяет все входные данные в форме на предмет фактического измененного значения, а не только события изменения. Я также включил поддержку для флажков и радиогрупп.

...