Breathing
Breathing

Reputation: 109

JavaScript function not getting called?

So I have a button that calls

<a class="btn btn-primary" id="btnAdd" href="#" onclick="ChangesJs.AddPlayList()"> <i class="fa fa-fw fa-plus fa-lg"></i>Add  </a>

and the JS function creates additional form on its own.

function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>*</span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' onchange='CommonJs.HideErrorMessage(this)' placeholder='Break No.' type='text'></div>";

This is the definition of IsNumeric function

function IsNumeric(selectinput) {
        var _value = selectinput.value;
        var ID = selectinput.id;
        if (_value !== "" && !$.isNumeric(_value)) {
            $("#div_" + ID).show();
            $("#span_" + ID).html("Please Enter numeric value !");
            selectinput.value = "";
            selectinput.focus();
        }
    }

When I get of out focus in the text field no validation is shown.

Upvotes: 1

Views: 91

Answers (1)

factorypolaris
factorypolaris

Reputation: 2847

The elements created in the dom after initial load need to have an event listener added.

function AddPlayList() {
var form = "<div class='form-group col-sm-3 clscommercial_" + addPlayList + "' style='display:none;' ><label>Break No.</label> <span class='red_color'>* </span><input class='form-control' id='txtBreakno_" + x + "' maxlength='2' onblur='ChangesJS.IsNumeric(this)' placeholder='Break No.' type='text'></div>";

// append it to the DOM....

var element = document.getElementsByClassName("clscommercial_" + addPlayList);
    element.addEventListener('change', function() { 
        CommonJs.HideErrorMessage(this);
    }, false);

}

Also, don't forget to remove the listener if you remove the element it you may end up having it fire multiple times.

The jQuery way handles this well if your using it.

$('body').on('change', '.clscommercial', function() {
    // This will fire even on elements added programmatically as long 
    // as your top selector is (body) was created on page load.
    CommonJs.HideErrorMessage($(this)[0]);
)};

Upvotes: 1

Related Questions