JQuery-UI Form Modal Example For Beginners
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<div id="books-table" class="ui-widget"> <table id="books" class="ui-widget ui-widget-content"> <!-- better practise to have caption instead of heading styles --> <caption>Books in the Library</caption> <thead> <tr class="ui-widget-header"> <th>Name</th> <th>Author</th> </tr> </thead> <tbody> <tr> <td>Hobbit</td> <td>J.R.R. Tolkien</td> </tr> </tbody> </table> <input id="add-book-modal" type="button" name="button" value="Add new book"> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
body { background: rgba(254, 254, 254, 1) fixed; background: linear-gradient(top, rgba(254, 254, 254, 1) 0%, rgba(209, 209, 209, 1) 49%, rgba(219, 219, 219, 1) 90%, rgba(226, 226, 226, 1) 100%) fixed; filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#fefefe', endColorstr='#e2e2e2', GradientType=0); } label, input { display: block; } input.text { margin-bottom: 20px; width: 90%; padding: .2em; } #books-table { width: 300px; margin: auto; } #books-table table { margin: 1em 0; width: 100%; } #books-table table td, #books-table table th { border: 1px solid #669; text-align: center; } #add-book { position: absolute; top: -1000px; } .required { border: 1px solid transparent; padding: 0.3em; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
var dialog, form, required = $(".required-fields"), title = $("#title"), author = $("#author"), allFields = $([]).add(title).add(author); function setMessage(message) { required .text(message) .addClass("ui-state-highlight"); setTimeout(function() { required.removeClass("ui-state-highlight", 1500); }, 500); } function addBook() { var valid = true; allFields.removeClass("ui-state-error"); valid = valid && checkLength(title, "Title", 1, 80); valid = valid && checkLength(author, "Author name", 1, 60); if (valid) { $("#books tbody").append("<tr>" + "<td>" + title.val() + "</td>" + "<td>" + author.val() + "</td>" + "</tr>"); dialog.dialog("close"); } return valid; } function checkLength(field, name, min, max) { if (field.val().length > max || field.val().length < min) { field.addClass("ui-state-error"); setMessage(name + " length must be between " + min + " and " + max + "."); return false; } else { return true; } } dialog = $("#book-modal").dialog({ autoOpen: false, height: 400, width: 300, modal: true, buttons: { "Add new book": addBook, Cancel: function() { dialog.dialog("close"); } }, close: function() { form[0].reset(); allFields.removeClass("ui-state-error"); } }); $("#add-book-modal").button().on("click", function() { dialog.dialog("open"); }); form = dialog.find("form").on("submit", function(event) { event.preventDefault(); addBook(); }); |