Dynamically adding values to a form with JQuery/Javascript
Posted
by bigstylee
on Stack Overflow
See other posts from Stack Overflow
or by bigstylee
Published on 2010-04-09T18:01:06Z
Indexed on
2010/04/09
18:03 UTC
Read the original article
Hit count: 350
I am creating a private message system to allow users to communicate between one another within the context of the website (ie, not emails).
I have created this function to handle all my form submissions. I would like to achieve a solution without modifying this function (ideally).
$("form.reload").submit(function(){
alert($(this).serialize()); /* Debugging */
$.post($(this).attr("action"),
$(this).serialize()
,function(data){
if(data){
$("#error").html(data);
}else{
location.reload();
};
});
return false;
});
Within my form I am using JQuery Autocomplete to find usernames. This function works perfectly. My first solution was to add buttons within the form with the necessary values.
select: function(event, ui) {
$("#message_to").append("<input type=\"button\" class=\"recipient\" name=\"recipients[]\" value=\"" + ui.item.label + "\" onclick=\"$(this).remove()\" />");
}
<form method="post" action="/messages-create">
<div id="message_to"></div>
</div>
For some reason the values of recipients are not getting posted.
My second solution was to add to a post array that already existed in the form
select: function(event, ui) {
$(input[name=recipeients[]).val = ui.item.label; /* Need to add to array, not replace! */
$("#message_to").append("<input type=\"button\" class=\"recipient\" name=\"recipient\" value=\"" + ui.item.label + "\" onclick=\"$(this).remove(); /* Remove from recipients */\" />");
}
<form method="post" action="/messages-create" class="reload">
<input type="hidden" name="recipients[]" value="" />
<div id="message_to"></div>
</div>
This works ok, but I have been unable to work out how to append to the recipients[]
array only replace with the new label. Moving on from this, I also need to know how to then remove this value from the array.
Thanks in advance!
© Stack Overflow or respective owner