1

I want o display value in to two different field according to input is focused. When I put cursor in any one of two field and click on button, I want to only value of button appear in that field. but my code is keep adding value to the same field event I have two different fields. Anybody please help.

<input type="text" class="frm-control-input" name="multi">
<input type="text" class="frm-control-input-price" name="price">
    
    
<button type="button" class="btn" value="1">1</button>
<button type="button" class="btn" value="2">2</button>
<button type="button" class="btn" value="3">3</button>




$('.frm-control-input').click(function(){
    if($(this).is(':focus')){
        console.log('up')
        $('.btn').click(function(){
            var number = $(this).val();
            $('.frm-control-input').val($('.frm-control-input').val() + number);
            console.log(number);
        });
    }else{
        $(this).blur();
    }
});

$('.frm-control-input-price').click(function(){
    if($(this).is(':focus')){
        $('.btn').click(function(){
            var num = $(this).val();

            $('.frm-control-input-price').val($('.frm-control-input-price').val() + num);
            
        });
    }
});

1 Answer 1

1

You can use data-attribute here and change its value to true or false depending on which input is focus . Then ,whenever button is clicked check where is data-focus="true" and add number to that input.

Demo Code :

$('.frm-control-input').click(function() {
  //add data-focus true
  $(this).attr("data-focus", true);
  //remove from other
  $(".frm-control-input").not(this).attr("data-focus", false);
});



$('.btn').click(function() {
  var number = $(this).val();
  //add value to input where data-focus is true
  $('input[data-focus=true]').val($('input[data-focus=true]').val() + number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="frm-control-input" name="multi">
<input type="text" class="frm-control-input" name="price">


<button type="button" class="btn" value="1">1</button>
<button type="button" class="btn" value="2">2</button>
<button type="button" class="btn" value="3">3</button>

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.