Programatically trigger form validation with JQuery Validator don't work - jquery-validate

According to the docs of jQuery Validator doing this should programatically trigger form validation.
var validator = $( "#myform" ).validate();
validator.form();
But in my code it does nothing, why? I have a submit button on my form that is working fine, but validator.form() doesn't work at all. I've updated the post with my HTML form as well as the javascript code.
This is my form
<form class="kt-form kt-form--label-right" id="frm_sok" action="ajax/artikkel.php?a=sok_artikler" method="post">
<div class="kt-portlet__body">
<div class="kt-blog-post">
<div class="form-group ">
<div class="col-12">
<input class="form-control" type="search" value="{{ sok }}" id="searchinput" name="searchinput">
</div>
</div>
<div class="row">
<div class="col-4">
<label>Ikke søk i :</label>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="skjulnyheter" name="skjulnyheter">
<label class="form-check-label" for="skjulnyheter">Nyheter</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="skjulforum" name="skjulforum">
<label class="form-check-label" for="skjulforum">Forum</label>
</div>
</div>
<div class="col-4">
<label for="sorter">Sorter:</label><br />
<select class="form-control" name="sorter" id="sorter">
<option value="a.opp_dato DESC">Nyeste</option>
<option value="score">Beste treff</option>
<option value="a.opp_dato ASC">Eldste</option>
</select>
</div>
</div>
</div>
</div>
<div class="kt-portlet__foot">
<div class="kt-form__actions">
<input type="submit" class="btn btn-primary sokknapp" value="Søk" />
</div>
</div>
</form>
Here is my Javascript:
$( window ).on( 'load', function()
{
var validator = $("#frm_sok").validate(
{
rules:
{
searchinput:
{
required: true
}
},
messages:
{
searchinput :
{
required : 'Du må neste søke etter noe. Noe som helst. Ett eller annet.'
}
},
invalidHandler: function(event, validator)
{
$('.error').css( "display", "inline-block !important");
},
submitHandler: function(form)
{
preload_kamp();
$(form).ajaxSubmit(
{
success: function(data)
{
$( "#sokcontent" ).html(data);
}
});
}
});
validator.form();
});

Related

Laravel ajax, the page keeps on refreshing. I want to stop it from refreshing after posting data

I am using laravel and ajax to update records from table. Currently, the records are successfully being updated but somehow a refresh is triggered, making the ajax feature useless. i need a way to just post the form to update my database record without refreshing the page.
The following is my code.
View File Ajax
$(document).on("click", "#primaryButton", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type: "post",
url: "{{ route('event-qr-post') }}",
data: $("#message").serialize(),
success: function(store) {
location.href = store;
console.log("success!");
console.log(location.href);
console.log($("#message").serialize());
},
error: function() {
console.log("fail");
}
}).done(function(store) {
console.log("itsdone");
});
// e.preventDefault();
return false;
});
View File Submit Form
<form enctype="multipart/form-data" id="message">
#csrf
<div class="form-l">
<div id="ref-lookup">
<label style="font-size: 22px; font-weight: 700;margin-block:10px;" for="eventTitle">Reference
number</label>
<input id="id" name="id" value="{{ '' }}" required>
{{-- <input type="hidden" name="name" value="{{ $eid->name }}" required> --}}
<input type="hidden" name="staffName" value="{{ $sid->name }}" required>
<input type="hidden" name="submitType" id="submitType" value="">
<input type="hidden" name="pageType" id="pageType" value="{{ $type }}">
{{-- <input type="hidden" name="guestLeft" id="guestLeft" value=""> --}}
<div style="display:flex;justify-content:space-between;gap:10px">
<button type="button" style="background-color:green"
onclick="findGuest(document.getElementById('id').value);">Find Contact</button>
<button id="addGuest" type="button" style="background-color:red" onclick="addGuests();">Add a
Replacement</button>
</div>
</div>
<div id="guestForm">
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">First Name</label>
<input id="guestFirstName" name="first_name" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Last Name</label>
<input id="guestSurname" name="last_name" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Email</label>
<input id="guestEmail" name="email" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Company</label>
<input id="companyName" name="company" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Job Title</label>
<input id="guestTitle" name="title" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Tel</label>
<input id="guestPhone" name="tel" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Country</label>
<input id="guestCountry" name="country" value="">
</div>
<div class="form-group">
<label for="" style="width:120px; margin-top:10px; ">Notes</label>
<input id="guestNotes" name="notes" value="">
</div>
<button type="button" class="btn-blue" id="primaryButton">
Submit
<span class="foo fa fa-star checked"></span>
</button>
</div>
</div>
Controller
public function post_eventQR_attendance(Request $request)
{
// $ins = $request->all();
// unset($ins['_token']);
// dd($ins);
$User = MasterTempAward::where('id', $request->get('id'))->first();
$User->modified_by = $request->get('staffName');
$User->attended = "Yes";
$User->time = Carbon::now();
$User->business_card = "";
$User->save();
}
Your page is being refreshed because of the location.href = store; that you passed after the ajax request receives a success response.
location.href redirects the webpage to the specified URL.
So change your Ajax code to this:
$(document).on("click", "#primaryButton", function(e) {
e.preventDefault(); // Prevent Default form Submission
$.ajax({
type: "post",
url: "{{ route('event-qr-post') }}",
data: $("#message").serialize(),
success: function(store) {
// location.href = store;
console.log("success!");
// console.log(location.href);
console.log($("#message").serialize());
},
error: function() {
console.log("fail");
}
}).done(function(store) {
console.log("itsdone");
});
// e.preventDefault();
return false;
});

Laravel Batch Update Data Based on Checked Checkboxes Error

I have a table that has checkboxes on the left column that looks like this :
Table
What I want to try to do is assign a surveyor name using the select option in a modal to the surveyor column for all of the checked rows.
Modal
If I checked the first 4 rows of the table and then click the "Try Assign", it will only fill the last checked row (4th row), not all of the checked rows.
I think I've already used Foreach in my Controller so I don't know yet what is wrong with my code.
Result
This is my modal code :
<div class="modal fade" id="city-modal" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="CityModal"></h4>
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="CityForm" name="CityForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" id="labelname" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter City Name" maxlength="50">
</div>
</div>
<div class="form-group">
<label for="name" id="labelpopulation" class="col-sm-2 control-label">Population</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="population" name="population" placeholder="Enter City Population" maxlength="50">
</div>
</div>
<div class="form-group">
<label id="labelsurveyor" class="col-sm-2 control-label">Surveyor</label>
<div class="col-sm-12">
<select class="form-control select2" id="surveyor_id" name="surveyor_id" ">
<option value="">--Select Surveyor--</option>
#foreach($users as $surveyor)
<option value="{{ $surveyor->id }}">
{{$surveyor->name}}
</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save">Save changes</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
This is my JavaScript code for assigning the surveyor:
$(document).on('click', '.try-assign', function(e) {
var cityId = [];
var svrid;
$('.checkbox:checked').each(function() {
cityId.push($(this).val());
console.log(cityId);
});
if (cityId.length > 0) {
$.ajax({
type: "PUT",
url: "{{ url('try-assign') }}",
data: {
cityId,
svrid
},
dataType: "json",
success: function(res) {
$('#CityModal').html("Assign Surveyor");
$('#city-modal').modal('show');
$('#labelname').attr('hidden', true);
$('#labelpopulation').attr('hidden', true);
$('#labelsurveyor').attr('hidden', false);
$('#id').val(res.id);
$('#name').val(res.name).attr('hidden', true);
$('#population').val(res.population).attr('hidden', true);
$('#surveyor_id').val(res.surveyor_id).attr('disabled', false);
$('#surveyor_id').trigger('change');
svrid = res.surveyor_id;
}
});
} else {
alert('Please select atleast one row');
}
});
This is my tryAssign() function on the Controller :
public function tryAssign(Request $request)
{
$cityId = $request->cityId;
$svrid = $request->svrid;
foreach ($cityId as $key => $value) {
$city = City::find($value);
$city->surveyor_id = $svrid;
$city->update();
}
return Response()->json($city);
}
And, this is my route :
Route::put('try-assign', [CityController::class, 'tryAssign']);

Laravel inertia multi-part form data

I want to create a membership form with picture upload and other input data required. I have a form with input file and input text which to be considered as multi-part data. I am using the Laravel 8 and Inertia.js.
Here is what I've tried:
In my Form, I have like this:
<form action="/member" method="POST" #submit.prevent="createMember">
<div class="card-body">
<div class="form-group">
<label for="exampleInputFile">Picture</label>
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="exampleInputFile" #input="form.picture">
<label class="custom-file-label" for="exampleInputFile">Choose image</label>
</div>
<div class="input-group-append">
<span class="input-group-text">Upload</span>
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">First name</label>
<input type="text" class="form-control" id="fname" placeholder="First name" v-model="form.firstname">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Middle name</label>
<input type="text" class="form-control" id="mname" placeholder="Middle name" v-model="form.middlename">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Last name</label>
<input type="text" class="form-control" id="lname" placeholder="Last name" v-model="form.lastname">
</div>
<div class="col-md-12">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Name ext</label>
<input type="text" class="form-control" id="next" placeholder="Name extension" v-model="form.name_ext">
</div>
<div class="form-group">
<label>Membership Date:</label>
<div class="input-group date" id="reservationdate" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" id="mem_date" data-target="#reservationdate" v-model="form.membership_date"/>
<div class="input-group-append" data-target="#reservationdate" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
<div class="form-group">
<label>Date of Birth:</label>
<div class="input-group date" id="reservationdate" data-target-input="nearest">
<input type="text" class="form-control datetimepicker-input" id="date_of_birth" data-target="#reservationdate" v-model="form.date_of_birth"/>
<div class="input-group-append" data-target="#reservationdate" data-toggle="datetimepicker">
<div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
</div>
<div class="form-group">
<label>Sex:</label>
<div class="radio-inline">
<label class="radio radio-solid">
<input type="radio" name="travel_radio" class="details-input" value="Male" v-model="form.sex"/> Male
<span></span>
</label>
<label class="radio radio-solid">
<input type="radio" name="travel_radio" class="details-input" value="Female" v-model="form.sex"/> Female
<span></span>
</label>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
then I have tried vue and inertia implementation like this:
export default {
props: [],
components: {
AppLayout,
},
data() {
return {
form: {
picture: '',
firstname: '',
middlename: '',
lastname: '',
name_ext: '',
date_of_birth: '',
sex: '',
membership_date: '',
}
}
},
methods: {
createMember() {
this.$inertia.post('/member', this.form, {
_method: 'put',
picture: this.form.picture,
onSuccess: () => {
console.log('success');
// $('.toastrDefaultSuccess').click(function() {
// toastr.success('Successfully Added');
// });
},
onError: (errors) => {
console.log(errors);
},
})
}
}
}
then from my backend, I tried to dd the request and got null from picture:
public function store(MemberPost $request) {
dd($request);
}
Assuming you are using inertia 0.8.0 or above, you can use the inertia form helper. This will automatically transform the data to a FormData object if necessary.
Change your data method to:
data() {
return {
form: this.$inertia.form({
picture: '',
firstname: '',
middlename: '',
lastname: '',
name_ext: '',
date_of_birth: '',
sex: '',
membership_date: '',
})
}
}
and the createMember function to:
createMember() {
// abbreviated for clarity
this.form.post('/member')
}
More info: docs. If you need to migrate FormData from inertia < 0.8.0 to a current version, see this page.
if you using multi-upload remove array from files
before: <input type="file" #input="form.image = $event.target.files[0]" multiple/>
after: <input type="file" #input="form.image = $event.target.files" multiple/>
add enctype="multipart/form-data" to form tag
and you need move the picture to directory. example
$name = $file->getClientOriginalName();
$file->move('uploads/posts/',$name);
sorry, i dont know how to implement this code to inertia.
This way works for me
this.$inertia.post('/member', this.form)

getting typerror in Vue JS while trying to bind the JSON data in select model

I want to bind the select option with returned JSON data. However, when I do the API call and set the options model groups to the returned JSON, I get the error 'TypeError: Cannot set property 'groups' of undefined'.
Here is the vue file
<template>
<div class="register">
<div class="container">
<div class="row">
<div class="col">
<h3 class="mb-10">Register as a volunteer</h3>
<form action="">
<div class="form-group">
<label for="first_name">First Name</label>
<input type="text" v-model="first_name" placeholder="First Name" class="form-control" id="first_name">
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input type="text" v-model="last_name" placeholder="Last Name" class="form-control" id="last_name">
</div>
<div class="form-group">
<label for="group">Select Institution/Organization/Company</label>
<select v-model="group" class="form-control" id="group">
<option v-for="group in groups" v-bind:name="name">{{ group.code }}</option>
</select>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="text" v-model="adv_phone" placeholder="Phone" class="form-control" id="phone">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" v-model="adv_password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label for="confirm-password">Confirm Password</label>
<input type="password" v-model="adv_password" class="form-control" id="confirm-password" placeholder="Confirm Password">
</div>
<div class="from-group">
<input type="submit" class="btn btn-primary" value="Register">
<router-link :to="{name:'home'}">
<a class="btn btn-outline-secondary">Cancel</a>
</router-link>
</div>
</form>
</div>
</div>
</div>
<div class="register-form"></div>
</div>
</template>
<script>
export default {
mounted(){
this.getGroups()
},
data (){
return {
group: '',
groups:'',
first_name:'',
last_name:'',
adv_email:'',
adv_phone:'',
adv_password:'',
confirm_password:''
}
},
methods:{
getGroups(){
axios.get('/api/group/get/all')
.then(function (response) {
console.log(response);
this.groups = response.data;
//console.log(groups);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});
}
}
}
</script>
and here is my json returned
[{"id":8,"name":"Villa Maria Academy","code":"Vil-9458-3786","advisors":25,"students":99,"subscription_time":99,"subscription_type":0,"admin_name":"","admin_email":"","phone":"817879234","address":"Abcde street","state":"Pennsylvania","zip":16502,"apt":"","city":"Erie"},{"id":9,"name":"Cathedral Prep","code":"Cat-1959-1432","advisors":99,"students":99,"subscription_time":99,"subscription_type":0,"admin_name":"","admin_email":"","phone":"0","address":"","state":"","zip":0,"apt":"","city":""}]
Why am I getting a type error, when I set this.groups = response.data?
You can use arrow function to fix problem.
methods:{
getGroups(){
axios.get('/api/group/get/all')
.then(response => {
console.log(response);
this.groups = response.data;
//console.log(groups);
})
.catch(error => {
console.log(error);
})
.then(() => {
// always executed
});
}
}

how to highlight invalid section — twitter bootstrap/jquery/validate plugin

I have a form in twitter bootstrap:
<div class="form-div">
<form id="fvujq-form1" method="post" action="">
<div class="control-group name">
<fieldset>
<label>Name *</label>
<input type="text" name="name">
</fieldset>
</div>
<div class="control-group email">
<fieldset>
<label>E-Mail *</label>
<input type="text" name="email">
</fieldset>
</div>
<div class="control-group comment">
<fieldset>
<label>Your comment *</label>
<textarea name="comment"></textarea>
</fieldset>
</div>
<button class="btn btn-primary">Submit</button>
</form>
</div>
and this is how I validate it with bassistance Validate plugin:
$(document).ready(function() {
$("#fvujq-form1").validate({
submitHandler:function(form) {
SubmittingForm();
},
success: function(label) {
label.html("✔").addClass("valid");
},
onfocusout: function(element) { $(element).valid(); },
focusInvalid: false,
highlight: function(element, errorClass, validClass) {
$('.form-div').find('.control-group' + element.id).addClass('error');
},
unhighlight: function(element, errorClass, validClass) {
$('.form-div').find('.control-group' + element.id).removeClass('error');
},
errorClass: "help-inline",
errorElement: "strong"
I want to add .error to the div currently validated, but this code adds class to every .control-group occurence, not only validated one :(
thx 4 yr help.
JSFiddler Example
This will validate as you leave each field or when you hit the submit button all fields that meet the rules will present errors.
HTML
<form action="" id="fvujq-form1" class="form-horizontal">
<fieldset>
<div class="control-group">
<label class="control-label" for="name">Your Name</label>
<div class="controls">
<input type="text" class="input-xlarge" name="name" id="name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email Address</label>
<div class="controls">
<input type="text" class="input-xlarge" name="email" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="comment">Comment</label>
<div class="controls">
<input type="text" class="input-xlarge" name="comment" id="comment">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
Javascript
$(document).ready(function(){
$('#fvujq-form1').validate(
{
rules: {
name: {
minlength: 2,
required: true
},
email: {
required: true,
email: true
},
comment: {
minlength: 2,
required: true
},
},
highlight: function(element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function(element) {
element
.text('OK!').addClass('valid')
.closest('.control-group').removeClass('error').addClass('success');
}
});
});

Resources