This is probably a very basic question and I know how to do it using plain DOM but would like to learn the JQuery way of doing it.
After identifying the set of nodes using the appropriate JQuery selector, I would like to append a textarea, Save and Cancel button to each node with appropriate callback functions attached to the buttons to store values into a database. If the database has a value stored already, it should be pre-populated in the textarea. I can handle the back-end interaction parts, I just wanted to know the best practice for doing this sort of thing as far adding/removing form elements.
Thanks
4 Answers 4
Something like this, perhaps:
jQuery(yourNodes).each(function(){
var self = this,
loading = $('<div>LOADING</div>').appendTo(self),
id = self.id.replace(/^edit/,'');
// Retrieve textarea from server
jQuery.get('/getDataForTextArea?id=' + id, function(textareaValue){
loading.remove();
var textarea = jQuery('<textarea/>')
.attr('id', 'txt' + id)
.val(textareaValue)
.add(
jQuery('<button>Save</button>')
.attr('id', 'btnSave' + id)
.click(function(){ /* Click handler */ })
)
.add(
jQuery('<button>Cancel</button>')
.attr('id', 'btnCancel' + id)
.click(function(){
/* Remove nodes */
tr.remove();
})
);
var tr = jQuery('<tr colspan="4"><td/></tr>');
tr.find('td').append(textarea);
tr.appendTo(self);
});
});
14 Comments
<input type="button"/> - you can use whichever one you want...Simply
$('<your nodes>').append('<textarea name="...">' + textarea_value + '</textarea>');
or using $(html) form:
$('<textarea name="...">' + textarea_value + '</textarea>').appendTo('<your nodes>');
You may also use $().clone method if you need repeating values. Take a look at official docs.
Comments
As far as appending textarea, buttons to selected nodes @Nikita Prokopov's answer will do the trick. But as you want to add callbacks and back-end interactions, the best way to do will be to write a plugin.
Comments
Nikita Prokopov..answered the question. I have been working with jquery for a little while and this is what I have discovered.
Always give actions a name like so:
var SubmitText = $('#form-text-idNumber').submit(function {
//do stuff here
return false;
}
Dont do this:
$('#form-text-idNumber').submit(function {
//do stuff here
return false;
}
if you give your actions a variable it will not interfere with other similar forms on the page
Just give all of your actions and sections a variable and you should be good.