Jimmy
Jimmy

Reputation: 12497

Focusing a field using jquery

I was wondering how I can focus the field. This is my code: http://jsfiddle.net/spadez/9sX6X/31/

var container = $('.copies'),
    value_src = $('#current'),
    maxFields = 10,
    currentFields = 1;

$('.copy_form').on('click', '.add', function () {
    if ($.trim(value_src.val()) != '') {
        if (currentFields < maxFields) {
            var value = value_src.val();
            var html = '<div class="line">' +
                '<input id="accepted" type="text" value="' + value + '" />' +
                '<input type="button" value="X" class="remove" />' +
                '</div>';

            $(html).appendTo(container);
            value_src.val('');
            currentFields++;
        } else {
            alert("You tried to add a field when there are already " + maxFields);
        }
    } else {
        alert("You didn't enter anything");
    }
})
    .on('click', '.remove', function () {
    $(this).parents('.line').remove();
    currentFields--;
});

When I add a value into "content" and click add I would like it to re focus on the field "current" so I can start typing in more content.

Upvotes: 1

Views: 75

Answers (4)

epsilones
epsilones

Reputation: 11609

If you take your target as #target (which is here #current), you should put in the event on('click', '.add'...) function

$('#target').focus();

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113455

You need the focus() jQuery function:

.focus()

Bind an event handler to the "focus" JavaScript event, or trigger that event on an element.

This method is a shortcut for .on('focus', handler) in the first and second variations, and .trigger('focus') in the third.

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (, , etc.) and links (). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element. The focus is used to determine which element is the first to receive keyboard-related events


So, in your code just add:

 $("#current").focus();

JSFIDDLE

Upvotes: 2

user925885
user925885

Reputation:

Check the documentation for jQuery.focus()

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

just use this inside click event of .copy_form -

 value_src.focus();

Demo --> http://jsfiddle.net/9sX6X/35/

Upvotes: 2

Related Questions