Show validation message on a non-form element
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<form method="post">
<div>
<table id="tblDemo" class="table table-bordered table-striped" style="z-index:0;">
<thead>
<tr>
<th>Last</th>
<th>First</th>
</tr>
</thead>
<tbody>
<tr>
<td>Kuehn</td>
<td>Chad</td>
</tr>
<tr>
<td>Forrest</td>
<td>Andrew</td>
</tr>
<tr>
<td>Smith</td>
<td>Hannah</td>
</tr>
<tr>
<td>Reynolds</td>
<td>Ryan</td>
</tr>
</tbody>
</table>
<input type="text" id="dummy" style="position:absolute;margin-top:-48px;width:100%;z-index:-1" />
</div>
<input type="submit" value="Submit" id="btnSubmit" />
</form>
CSS
.table-striped>tbody>tr:nth-of-type(even) {
background-color: #FFF;
}
.selected {
background-color: red !important;
}
JavaScript
$("#btnSubmit").click(function(e) {
if (selected.length == 0) {
$("#dummy")[0].setCustomValidity("Select a row");
return;
}
$("#dummy")[0].setCustomValidity("");
e.preventDefault();
alert("do ajax");
});
var selected = [];
$("#tblDemo tbody tr").click(function() {
var tr = $(this);
var id = tr.find("td:first-child").html();
if (tr.hasClass("selected")) {
tr.removeClass("selected");
var pos = selected.indexOf(id);
selected.splice(pos, 1);
} else {
tr.addClass("selected");
selected.push(id);
}
});