How to submit a form in Semantic UI?

Jon Carl picture Jon Carl · Oct 20, 2013 · Viewed 40.5k times · Source

I know how to validate a form using Semantic UI, and can even read in console the message "Form has no validation errors, submitting." However, where is this submitting to? I want to actually submit the form, but the way Semantic UI is laid out I don't seem to be able to specify where to submit to or anything.

I read this tutorial, but that uses Angular for submission and not just Semantic UI.

Am I missing something really simple here?

Answer

Agon Bina picture Agon Bina · Nov 26, 2013

You can use jQuery's ajax:

   //Get value from an input field
   function getFieldValue(fieldId) { 
      // 'get field' is part of Semantics form behavior API
      return $('.ui.form').form('get field', fieldId).val();
   }

   function submitForm() {
      var formData = {
          field1: getFieldValue('someId')
      };

      $.ajax({ type: 'POST', url: '/api/someRestEndpoint', data: formData, success: onFormSubmitted });
   }

   // Handle post response
   function onFormSubmitted(response) {
        // Do something with response ...
   }

EDIT: also, you can use the onSuccess method of the form to run the submitForm function, ie when you initialize the form:

$('.ui.form').form(validationRules, { onSuccess: submitForm });

onSuccess will only be called when the 'Submit' button is clicked and the form is valid based on the rules you specify.

EDIT: If you want the regular HTML form behavior, you will need to add the semantic css classes to the form tag.

<form class="ui form" method="POST" action="/signup">...</form>

And then you set up the validation rules using jQuery. This will give you the default HTML form behavior, ie when you hit the submit button, it will make a POST request to /signup in the case above. If any of your rules trigger, the submit is prevented until there is no validation errors.