问题
I tried to send some checkboxes values from HTML to Node JS. In my HTML file, I have some checkboxes in a table. I got the checked checkboxes values as following,
$("#createSS").click(function (event) {
event.preventDefault();
var searchIDs = $("#imgTable input:checkbox:checked").map(function () {
return $(this).val();
}).get();
console.log("selected::::" + searchIDs);
});
My HTML form is,
<form action="/addSlideShow" method="POST">
<table id="imgTable" class="table">
{{#images}}
<tr>
<td><input id={{imgURL}} type="checkbox" name="ch" value={{imgURL}}/></td>
</tr>
{{/images}}
</table>
<input id="createSS" type="submit" value="Create Slide Show" class="btn btn-success pull-left" disabled/>
</form>
In Node JS,
app.post('/addSlideShow', function (req, res) {
var $ = req.body;
$('td').each(function () {
console.log($(this).text());
});
});
When I'm clicking the button in HTML, the for isn't submit. How may I fix this?
Thanks in Advance!
回答1:
This is because you are not posting the data to the form url. As you have used event.preventDefault()
which will never submit nor you used $.ajax() to post data
Try to post the data using ajax like,
$("#createSS").click(function (event) {
event.preventDefault();
var searchIDs = $("#imgTable input:checkbox:checked").map(function () {
return $(this).val();
}).get();
console.log("selected::::" + searchIDs);
$.ajax({
url:'/addSlideShow',type:'post',
data:{searchid:searchIDs},
success:function(response){
console.log(response);
}
});
});
In node js you will get,
app.post('/addSlideShow', function(req, res) {
console.log(req.body); //Output=> like { searchid: 'Array of checked checkbox' }
console.log(req.body.searchid); // to get array of checked checkbox
});
回答2:
<input id="createSS" type="submit" value="Create Slide Show" class="btn btn-success pull-left" disabled/>
Your submit button is disabled. Remove that disabled
attribute right in the end.
回答3:
You are using event.preventDefault()
, which tells the browser not to do what it should upon click. Remove that line and your form will be submitted. I'm not a Node ninja, but your data in req.body won't be in an html format. Querying $("td") is frontend logic. You need to assign a different name to each checkbox like name="ch-{{$index}}"
(this would be like so in an angular ng-repeat). Or you should send {searchid: searchIDs}
via ajax.
来源:https://stackoverflow.com/questions/29072382/how-to-send-checkboxes-values-from-html-to-node-js