Присвоение класса при вводе значения в input

223
29 августа 2017, 13:41

Есть конструкция:

<div class="prod">
   <input class="mquantity" name="mquantity[{$v->id}]" value="" type="text" data-price="{$v->price}"> 
</div>

Как сделать проверку input, чтобы при любом значении, кроме пустого, классу prod присваивался еще один класс nod?

Answer 1

JavaScript

Не силен в чистом javascript, и не уверен, что нет более лаконичного варианта, но как-то так (просто строго проверяем на неравенство пустой строке, при этом пробел тоже будет считаться символом):

const input = document.getElementsByClassName('mquantity') 
 
for(let i = 0; i < input.length; i++) { 
  const thisInput = input[i], 
    thisInputParent = thisInput.parentNode; 
   
  if(thisInput.value !== '') thisInputParent.className += " nod"; 
   
  console.log(thisInputParent.className); 
}
<div class="prod"> 
   <input class="mquantity" name="mquantity[{$v->id}]" value="" type="text" data-price="{$v->price}">  
</div> 
<div class="prod"> 
   <input class="mquantity" name="mquantity[{$v->id}]" value="123" type="text" data-price="{$v->price}">  
</div>

jQuery

Тут я уже увереннее себя чувствую, по этому решение с проверкой на наличие любых символов кроме пробелов + динамическая обработка:

const $input = $('.mquantity'); 
     
$input.each(inputOnKeypress); 
$input.on('keyup keypress', inputOnKeypress); 
 
function inputOnKeypress() { 
  const $thisInput = $(this); 
 
  $thisInput.closest('.prod').toggleClass('nod', $thisInput.val().match(/[^\s]/) !== null); 
}
.nod .mquantity { 
  border-color: yellow; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div class="prod"> 
   <input class="mquantity" name="mquantity[{$v->id}]" value="" type="text" data-price="{$v->price}">  
</div> 
<div class="prod"> 
   <input class="mquantity" name="mquantity[{$v->id}]" value="123" type="text" data-price="{$v->price}">  
</div>

Answer 2

Вот вариант на jQuery:

$('#mquantity_input').bind('input', function() { 
    if ($(this).val() == '' || $(this).val() == ' ') { 
        $('#mquantity_div').removeClass('nod'); 
    } else { 
        if ($('#mquantity_div').hasClass('prod') && !$('#mquantity_div').hasClass('nod')) { 
            $('#mquantity_div').addClass('nod'); 
        } 
    } 
    $(this).next().html('class="' + $('#mquantity_div').attr('class') + '"'); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div id="mquantity_div" class="prod"> 
   <input id="mquantity_input" class="mquantity" name="mquantity" value="">  
   <span>class="prod"</span> 
</div>

READ ALSO
Отправка фрейма закрытия WebSocket Linux C

Отправка фрейма закрытия WebSocket Linux C

Пишу простой Socket server под Linux на ССтолкнулся к непонятной для меня проблемой

291
Найти id родителя Javascript

Найти id родителя Javascript

Есть такой код

218
как добавить несколько yAxis в nvd3 js

как добавить несколько yAxis в nvd3 js

Как получить такое расположение координат?

222