ctown4life
ctown4life

Reputation: 965

jquery bind plugin to live element

I have some input text fields that are being generated on the fly (via javascript) by the user. I want those fields to accept integers only so I am using the alphanumeric plugin. The plugin works as expected on elements that already exist when the page loads but it does not work with the new on-the-fly elements. How can I live-bind the new elements to this plugin? Thanks!

Here is some sample code.

http://jsfiddle.net/ctown4life/tZPg4/780/

Upvotes: 0

Views: 1079

Answers (5)

maxedison
maxedison

Reputation: 17553

Just call the .numeric() method on the newly appended input field. After doing the .appendTo(scntDiv), you call:

scntDiv.children('p:last .intonly').numeric();

Full code:

http://jsfiddle.net/ebiewener/tZPg4/782/

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

One way is just to call the alphanumeric plugin for your dynamic inputs:

$('#addScnt').live('click', function() {
    $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i + '" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
    i++;
    $('#p_scents p:last input').numeric(); // Added this line...
    return false;
});

Upvotes: 0

ShankarSangoli
ShankarSangoli

Reputation: 69905

Here you go

http://jsfiddle.net/tZPg4/781/

You just need this

$('#addScnt').live('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv).find("input").numeric();

The issue is not because you are using live, its because you are not running the numberic plugin on the newly created input box.

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 219938

live will not help you here. You'll have to re-initiate the plugin whenever you add a new input:

$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>')
    .appendTo(scntDiv)
    .find('input').numeric(); 

Upvotes: 1

bfavaretto
bfavaretto

Reputation: 71918

Simple quick fix - change:

$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);

to

$('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" class="intonly" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').numeric().appendTo(scntDiv);

Please notice that the dynamically inserted fields are all getting the same id. That's not good, you should either use a unique id for each input, or no id at all.

Upvotes: 3

Related Questions