0

A wordpress plugin sets a number field, I'm unable to add extra HTML before and after the number field. I've already added some CSS to remove the default arrows.

So I've added two elements with jQuery before and after the input:

$('.enviso-group-form .quantity input').each(function(i, obj) {
    $(this).before('<span class="selectNumber__increase selectNumber__change">+</span>');
    $(this).after('<span class="selectNumber__decrease selectNumber__change">-</span>');

    $(this).val(0);
});

The code above loops over each input, adds two spans and sets the value to 0. Until now, everything works. This is what it looks like:

enter image description here

I've also created a function to increment the value of the number input:

$('.enviso-group-form .selectNumber__increase').on('click', function(e) {
  $oldValue = $(this).find('input').val();
  
  $newValue = parseInt($oldValue) + 1;
  console.log(parseInt($newValue));
  $(this).next('input').val($newValue);
});

This unfortunately doesn't work. It triggers the console.log but I get NaN and the input value stays 0.

1 Answer 1

2

.find('input') will find descendents

Get the descendants of each element in the current set of matched elements

You can either use next (prev for the other button) or siblings, either will return the right result.

$oldValue = $(this).next('input').val();

or

$oldValue = $(this).siblings('input').val();

$('.enviso-group-form .quantity input').each(function(i, obj) {
    $(this).before('<span class="selectNumber__increase selectNumber__change">+</span>');
    $(this).after('<span class="selectNumber__decrease selectNumber__change">-</span>');

    $(this).val(0);
});

$('.enviso-group-form .selectNumber__increase').on('click', function(e) {
  $oldValue = $(this).next('input').val();
  
  $newValue = parseInt($oldValue) + 1;
  console.log(parseInt($newValue));
  $(this).next('input').val($newValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="enviso-group-form">
  <div class="quantity">
    <input type="number">
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.