Reputation: 253
<form id="form1">
<ul>
<li>Content</li>
<li>Content</li>
<li>Content</li>
</ul>
<input type="submit" value="Submit" />
</form>
I want to send the content in the ul tag when clicking the submit button.
the submitted data should be
<li>Content</li>
<li>Content</li>
<li>Content</li>
How would I write this in jquery and with proper char. escaping for the <>'s
Upvotes: 0
Views: 1273
Reputation: 54593
Disclaimer: This is an alternative to my other AJAX based answer.
You can do this by setting the value of a hidden field with javascript. Also, your form needs an "action" attribute - it has to be submitted to somewhere.
<!-- HTML -->
<form action="/my_script.php" id="my_id">
<ul>
Stuff...
</ul>
<input type="hidden" name="html />
</form>
The script:
$("#my_id").submit(function () {
var html = $(this).find("ul").html();
$(this).find("input[name=html]").val(escape(html));
// don't return false, we want the submit event to go through
});
The form will submit, and the hidden field will have the escaped HTML from the <ul></ul>
tag as value.
Upvotes: 2
Reputation: 54593
To hook the submit, do this:
$("#form1").submit(function () {
// do stuff
return false;
});
Replace the // do stuff
part with one of the following:
$.ajax({
url: "...",
type: "POST",
data: $("#form1 ul").html()
});
If you want to escape it, I'd do it on the server side. You can also do this, to perform a client side escape:
$.ajax({
url: "...",
type: "POST",
data: escape($("#form1 ul").html())
});
I think the most elegant solution would be to send it as JSON to the server.
$.ajax({
url: "...",
dataType: "json",
// the value of `type` is irrelevant here
data: {html: $("#form1 ul").html(), moreMetadDtaIfYouWant: 5}
});
But that's your call ;)
Upvotes: 3
Reputation: 6866
Well I think you're going to have to submit your values inside some form field so you're going to first have to create a input of some type, probably hidden if I had to venture a guess, with in your form.
<input id="your_id" type="hidden" />
Then using jquery you could do this in the onSubmit of the form...
$("#form1").submit(function(){
$("#your_id").val($("#form1 ul").html());
}
I'm not sure if the form will automatically escape the html you're submitting or not though.
Upvotes: 0