To move the cursor of a text box from the active to a newly added text box, enter the key pressed from the keyboard only if the active text box is filled

Html

<table>
<thead>
<th>item</th>
<th>Cost</th>
</thead>
 <tbody id="tbody">
<tr>
    <td>Item 1</td>
    <td>
        <input type="text" class="elm" />
    </td>
</tr>


</tbody>
<tfoot>
<tr>
    <td>Total</td>
    <td>
        <label id="total">0</label>
    </td>
</tr>
</tfoot>

      

JQuery

$('body').on('keyup','.elm',function(e){
//Check Key Press is Enter
if (e.keyCode != 13) {
    var sum = 0;
    $('.elm').each(function() {
        if($(this).val() != '' && !isNaN($(this).val())){
            sum += parseInt($(this).val());
        }
    });

    $('#total').text(sum);
}
else{
var $itemNum = $('#tbody tr');
if($itemNum.find('input').val().length > 0) 
{
    var itemNum = $('#tbody tr').length + 1;
    var newRow = '<tr>'+
        '<td>Item'+itemNum+'</td>'+
        '<td>'+
            '<input type="text" class="elm">'+
        '</td>'+
    '</tr>';
    $('#tbody').append(newRow);
}
}
});

      

I am using the code above to add numeric values ​​when the user enters dynamically, adding a new textbox, pressing enter on the keyboard, regardless of the number of user inputs and calculating my output automatically. By pressing EnterKey, I have to add a new text box only after the user has entered a value in the previous text box and the cursor should automatically jump to the new text box. but in my code this only happens for the first textbox and not for the others, please help me with the coding. I am new to javascript.

+3


source to share


2 answers


http://jsfiddle.net/72ene5ob/

Hey, it looks like you only want to check the length of the last input field. so just add .last()

to your selector: var $ itemNum = $ ('# tbody tr'). last ();



$('body').on('keyup','.elm',function(e){
//Check Key Press is Enter
    console.log(e.keyCode);
if (e.keyCode != 13) {
    console.log('Enter detected');
    var sum = 0;
    $('.elm').each(function() {
        if($(this).val() != '' && !isNaN($(this).val())){
            sum += parseInt($(this).val());
        }
    });

    $('#total').text(sum);
}
else{
var $itemNum = $('#tbody tr').last();

if($itemNum.find('input').val().length > 0) 
{
    console.log('should add new input');
    var itemNum = $('#tbody tr').length + 1;
    var newRow = '<tr>'+
        '<td>Item'+itemNum+'</td>'+
        '<td>'+
            '<input type="text" class="elm">'+
        '</td>'+
    '</tr>';
    $('#tbody').append(newRow);
}
}
});

      

+2


source


I extended David Carlson's answer by adding the following line of code as the last line in the else block:

     $('#tbody tr:last-child td:last-child input').focus();

      



After that, the newly added line entry gets focus.

Fiddle

0


source







All Articles