Wade73
Wade73

Reputation: 4509

Adding input buttons using JQuery

I have a interesting problem I need to solve. A customer wants to enter a customer id (using a scanner) in a input element and using AJAX, it will fill another input element with the customer name. A new input element should be added and focus set, so the customer can enter another customer id. I have two issues that I need help solving. First, I need to capture the enter sent by the scanner and move to the newly added input element. Second, I need to add events to the new input element to handle the AJAX call and the next enter sent from the scanner. Any help would be greatly appreciated.

Wade

Upvotes: 0

Views: 237

Answers (3)

Kevin
Kevin

Reputation: 3841

Here's a fairly simple template you can work from:

<form>
    <fieldset>
        Customer ID: <input name="id" />
        Customer Name: <input name="name" />
    </fieldset>
</form>​​​​​​

with Javascript:

​jQuery(function($) {
    var form = $('form'),
        fieldset; // defined here but set below after we get our event attached

    $('input[name=id]').keyup(function(e) {
        if(e.keyCode === 13) {
            var clone = fieldset.clone(true).appendTo(form);

            clone.children('input[name=id]').focus();

            $.get('getCustomerName.php', {id: this.value}, function(data) {
                clone.children('input[name=name]').val(data);
            });
        }
    });

    fieldset = $('fieldset').clone(true); // clones our fieldset template with events
});​

Upvotes: 1

Felix
Felix

Reputation: 3134

Maybe this can answer your doubt:

When input gets focus

 $('#inputId').focus(function(){

      ///your code here
    });

Or

$('#inputId').keypress(function(e) {
    if(e.keyCode == 13) {
        //your code here
    }
});

Upvotes: 1

griegs
griegs

Reputation: 22760

@Wade73, adding a new control is the easy bit. You'll need to pick an element to place the control within or to though.

$('#PlaceButtonIn').appendTo("new button html");
$('#PlaceButtonIn').append("new button html");

#PlaceButtonIn can be a div or a td or something useful to place the new control in.

New controls do not have events so use the live commend for this.

$('#PlaceButtonIn').append("<input type='button' class='NewButton'>");

$(document).ready(function(){

  $('.NewButton').live('click', function() { //Do click event here });

});

NewButton class does not need to exist in your CSS. It's a handy way to use the jQuery selector if you don't know control Id's or names.

Hope this is helpful.

Upvotes: 1

Related Questions