I’m totally newbie in javascript/jQuery and i have a little problem 🙂
I’m using AJAX to get datas to generate and populate form fields. After that, i would like to add and/or remove fields with javascript functions but it doesn’t work.
As i’m learning, i make my code step by step, so the following code implement the ajax request (which is working perfectly), and the function which i would like to call with an on click attribute on an + image.
$(document).ready(function(){
var id = $('#subId').val();
var num = $('.cloneSub').length;
var newNum = new Number(num + 1);
$.ajax({
type: 'POST',
dataType: 'json',
url: '/admin/popsub2/',
data: 'id='+id,
async: false,
success: function(data){
$.each(data, function(key, val){
// Add and populate the input text element
var newElem = $('#sub' + num).clone().attr('id', 'sub' + newNum);
newElem.children(':first').attr('id', 'sub' + newNum).attr('name', 'sub' + newNum);
$('#sub' + num).attr('value', val);
$('#sub' + num).after(newElem);
$(newElem).before('<br />');
// Simply add the select element
var newSelect = $('#editMenu_article' + num).clone().attr('id', 'editMenu_article' + newNum);
newSelect.children(':first').attr('id', 'editMenu_article' + newNum).attr('name', 'editMenu_article' + newNum);
$('#editMenu_article' + num).after(newSelect);
$(newSelect).before('<br />');
});
},
failure: function(){
alert('echec !!!');
}
});
function addField(){
// Add the input text element
var newElem = $('#sub' + num).clone().attr('id', 'sub' + newNum);
newElem.children(':first').attr('id', 'sub' + newNum).attr('name', 'sub' + newNum);
$('#sub' + num).attr('value', val);
$('#sub' + num).after(newElem);
$(newElem).before('<br />');
// Add the select element
var newSelect = $('#addMenu_article' + num).clone().attr('id', 'addMenu_article' + newNum);
newSelect.children(':first').attr('id', 'addMenu_article' + newNum).attr('name', 'addMenu_article' + newNum);
$('#addMenu_article' + num).after(newSelect);
$(newSelect).before('<br />');
}
});
The addField() function doesn’t work at all, and i don’t know why. AJAX seems to keep a hand on the script execution.
Thanx for your help.
UPDATE
My + image is :
<img src="images/plus.png" id="editSub2" />
Following your help i tried those codes :
$('#editSub2').live('click', function(){ ... });
$('#editSub2').bind('click', function(){ ... });
But nothing works.
You’ve declared
addField()inside the scope of your jQuery document ready callback. No one outside that function will be able to know about it. You can declare it as a global function, but you’ll be better encapsulating it. You might find something like Javascript Patterns a helpful resource.