JohnDotOwl
JohnDotOwl

Reputation: 3755

Loading Javascript for a Modal inserted at runtime

How do i execute this javascript only after the html is loaded.

<input type="text" id="rmb" name="price" class="price span1" value="2" />
<input type="text" id="sgd" />


    $('#rmb').keyup(function(){
        $('#sgd').val(Number(this.value/4.7).toFixed(2));
    });

inside my .js file , used to detect for submit button clicked

dialogEditItem.one('click', '.submit', function(e){

my jsfiddle http://jsfiddle.net/ZLr9N/

my modal html

<script id="product-data" type="text/html">

        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h3><%= data.name %></h3>
        </div>
        <div class="modal-body">
            ...
        <input type="text" id="rmb" name="price" class="price span1" value="<%= data.price %>">
                        <input type="text" id="sgd" />
                    ...
        <div class="modal-footer">
            <button class="btn green submit">Submit</button>
            <button class="btn red cancel" data-dismiss="modal">Cancel</button>
        </div>
    </script>

Upvotes: 1

Views: 105

Answers (1)

m90
m90

Reputation: 11822

You are trying to bind a handler to your input element before it is part of the DOM:

$('#rmb').keyup(handlerFn); // when #rmb is not present yet the jQuery object will be empty and no handler will be bound

Instead use event delegation, binding the handler to the document object that is always present:

$(document).on('keyup', '#rmb', handlerFn); //document will always be present, no matter if #rmb is added to the DOM lateron, so binding will be successful

See the docs on .on() and delegation.

Upvotes: 1

Related Questions