How to Define onsubmit on Blade Form Tag Laravel

Posted on

This is an article related to Javascript and also Laravel PHP Framework. In this article, the focus is about how to define onsubmit on blade form tag laravel. The main purpose for defining onsubmit attribute on the blade form tag in Laravel web-based framework is to try to validate user input using Javascript.

For an example, if there is a blade form tag defined in a blade view template file as shown below :

{{ Form::open(array('url' => '/user/save', 'class' => 'form-horizontal', 'id' => 'user_create_form', 'onsubmit'=>'checkForm()'))}}
 <div class="form-group"> 
 <label class="col-md-2 control-label">User Name</label>
 <div class="col-md-4">
 <input type="text" class="form-control" placeholder="User Name" id="username" name="username" 
 value="">
 <span class="text-danger" id="username" />
 </div>
 </div>
...
{{ Form::close }}

There are elements inside the form defined which is an input type text HTML element with the id of ‘username’. This is the input type HTML element which is going to be extracted its data inserted. But the most important thing is the reserved keyword ‘onsubmit’=>’checkForm()’ which is pointing out the method where the processing of the form will be continued on as shown below :

{{ Form::open(array('url' => '/user/save', 'class' => 'form-horizontal', 'id' => 'user_create_form', 'onsubmit'=>'checkForm()'))}}

The snippet code of Javascript which is the method processing the form as shown below :

<script type="text/javascript">
function checkForm(event){
var username = document.getElementById("username").value
alert(username);
}
</script>

So, to prove that the form submitted is actually processed through a form where its onsubmit attribute is setup to a function named checkForm, just alert the variable in the form of pop-up window with the message printed extracted from the variable. In the context of this article, the variable named as ‘username’ and it is retrieved from an inserted data of an input type text HTML element with the id of ‘username’. The following is the line of snippet code for extracting the inserted text from the input type text HTML element with the id of ‘username’ :

username = document.getElementById("username").value

And the above line is processed to be stored into a variable named ‘username’. The alert method specified which is written right after in the line of code above used to print out the value of the variable as stated before.

One thought on “How to Define onsubmit on Blade Form Tag Laravel

Leave a Reply