开发者

call jquery function from javascript not working

I read similar posts on this but fails to work at this time. Mine is slightly different.

I call a javascript function addFormField which creates a dynamic input element within a form. This part works fine. Within that function I call the JQuery function loadData(id) to test if the id of the dynamically created element exists but it does not. Is loadData being called correctly to wait $ for the input element id to be created before checking if it's created? Thanks!

function addFormField() {
var id = document.getElementById("id").value;

$("#divTxt").append("<p id='row" + id + "'><label for='txt" + id + "'>Field " + id + "&nbsp;&nbsp;<input type='text' size='20' id='txt" + id开发者_JAVA百科 + "'><p>");


$(function () {
    loadData(id);
});

id = (id - 1) + 2;
document.getElementById("id").value = id;
}

function loadData(id) {
if ( $('#txt' + id).length ){
        alert('success');
    }
    else {
        alert ('fail'); 
    }
}

<html>
<p><a href="#" onClick="addFormField(); return false;">Add</a></p>
<form method="get" id="form1" action='#'>
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
</html>


Your code works fine for me: http://jsfiddle.net/6t8eX/

Just make sure that the addFormField() method is global. If it isn't, the inline onClick won't be able to find it.

If it is wrapped in $(function () { }), (or in any other function body) it won't be global.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜