JQuery-UI Form Modal Example For Beginners

JQuery-UI Form Modal Example For Beginners

JQuery-UI Form Modal Example For Beginners

 

 

 

 

<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>

 

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;
}

 

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();
});

 

Leave a Reply