Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

html - How to add input value of of buttons into two different input fields in jQuery

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);
            
        });
    }
});
question from:https://stackoverflow.com/questions/65897529/how-to-add-input-value-of-of-buttons-into-two-different-input-fields-in-jquery

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...