Returning no result matches in autocomplete - javascript

How do i return a no results label in my autocomplete when there is no matches to the data, currently it just shows nothing..
here is my current code:
HTML:
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9">
{!! Form::text('searchlocation', null, array('class' => 'form-control', 'maxlength' =>'55', 'placeholder' => 'Eg. England, London or Sports', 'id' => 'sl')) !!}
</div>
{!! Form::hidden('country', null, array('id' => 'country')) !!}
{!! Form::hidden('city', null, array('id' => 'city')) !!}
<div class="col-md-3">
{!! Form::submit('Find Sights', array('class' => 'btn btn-homepage-search')) !!}
</div>
{!! Form::close() !!}
JS:
$('#sl').autocomplete({
source: '/autocomplete',
select: function(event, ui) {
event.preventDefault();
$("#country").val(ui.item.country);
$("#city").val(ui.item.value);
$('#sl').val(ui.item.label);
},
focus: function(event, ui){
event.preventDefault();
$('#sl').val(ui.item.label);
},
})

You can set this in php as :
if(count($usersArray) < 1){
$usersArray[] = array(
"label" => "No Result",
"value" => "-1",
"country" => "-1"
);
}

you can use client side check to show no records found. please take a look below.
$(function() {
$("#SearchUser").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://api.stackexchange.com/2.1/users",
data: {
site: 'stackoverflow',
inname: request.term
},
dataType: 'jsonp'
}).done(function(data) {
if (data.items) {
response($.map(data.items, function(item) {
console.log(item);
return item.display_name + " " + item.location;
}));
}
});
},
minLength: 1,
response: function(event, ui) {
if (!ui.content.length) {
var message = { value:"",label:"No records found" };
ui.content.push(message);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" rel="stylesheet"/>
<label for="SearchUser">StackOverflow user:</label>
<input id="SearchUser" type="text" />
.

Related

Method Illuminate\Validation\Validator::validateVideo does not exist

i´m traying to upload a video with dropzone, i did method in controller, view, model, trait, etc... But when i call my route to my function, returned me this:
Method Illuminate\Validation\Validator::validateVideo does not exist.
i understand where i have my problem...
i attachd my actual code:
route
Route::post('uploads/storeVideo', 'UploadController#storeVideo')->name('medias.createVideo');
Controller
public function storeVideo(UploadRequest $request)
{
$input = $request->all();
try {
$upload = $this->uploadRepository->create($input);
$upload->addMedia($input['file'])
->withCustomProperties(['uuid' => $input['uuid'], 'user_id' => auth()->id()])
->toMediaCollection($input['field']);
} catch (ValidatorException $e) {
return $this->sendResponse(false, $e->getMessage());
}
}
view
<div class="form-group row">
{!! Form::label('video', trans("lang.restaurant_video"), ['class' => 'col-3 control-label text-right ']) !!}
<div class="col-9">
<div style="width: 100%" class="dropzone video" id="video" data-field="video">
<input type="hidden" name="video">
</div>
{{ trans('lang.media_select')}}
<div class="form-text text-muted w-50">
{{ trans("lang.restaurant_video_help") }}
</div>
</div>
</div>
#prepend('scripts')
<script type="text/javascript">
var var15671147011688676454bleVideo = '';
#if(isset($restaurant) && $restaurant->hasMedia('video'))
var15671147011688676454bleVideo = {
name: "{!! $restaurant->getFirstMediaVideoUrl('video')->name !!}",
size: "{!! $restaurant->getFirstMediaVideoUrl('video')->size !!}",
type: "{!! $restaurant->getFirstMediaVideoUrl('video')->mime_type !!}",
collection_name: "{!! $restaurant->getFirstMediaVideoUrl('video')->collection_name !!}"
};
#endif
var dz_var15671147011688676454bleVideo = $(".dropzone.video").dropzone({
url: "{!! url('panel/uploads/storeVideo') !!}",
/*dictDefaultMessage: "{{trans('validation.dropzone_dictDefaultMessage')}}",
dictFallbackMessage: "{{trans('validation.dropzone_dictFallbackMessage')}}",
dictFallbackText: "{{trans('validation.dropzone_dictFallbackText')}}",
dictFileTooBig: "{{trans('validation.dropzone_dictFileTooBig', [ 'size' => config('medialibrary.max_file_size') / 1024 / 1024 ])}}",
dictInvalidFileType: "{{trans('validation.dropzone_dictInvalidFileType')}}",
dictResponseError: "{{trans('validation.dropzone_dictResponseError')}}",
dictCancelUpload: "{{trans('validation.dropzone_dictCancelUpload')}}",
dictCancelUploadConfirmation: "{{trans('validation.dropzone_dictCancelUploadConfirmation')}}",
dictRemoveFile: "{{trans('validation.dropzone_dictRemoveFile')}}",*/
dictMaxFilesExceeded: "{{ trans('validation.dropzone_dictMaxFilesExceeded') }}",
maxFilesize: {!! config('medialibrary.max_file_size_video') / 1024 / 1024 !!},
acceptedFiles: "video/*",
addRemoveLinks: true,
maxFiles: 1,
init: function () {
#if(isset($restaurant) && $restaurant->hasMedia('video'))
dzInit(this, var15671147011688676454bleVideo, '{!! url($restaurant->getFirstMediaVideoUrl('video','mp4')) !!}')
#endif
this.on("error", function(file, message) {
console.log(message);
$('.video').after(`<ul class="alert alert-danger" style="list-style: none;">
<li>
${message}
</li>
</ul>`);
this.removeFile(file);
});
this.on("success", function(file, message) {
$('.alert-danger').remove();
$('.video').after(`<ul class="alert alert-success" style="list-style: none;">
<li>
{{trans('validation.dropzone_success')}}
</li>
</ul>`);
});
},
accept: function (file, done) {
dzAccept(file, done, this.element, "{!! config('medialibrary.videos_folder') !!}");
},
sending: function (file, xhr, formData) {
dzSending(this, file, formData, '{!! csrf_token() !!}');
},
maxfilesexceeded: function (file) {
dz_var15671147011688676454bleVideo[0].mockFile = '';
dzMaxfile(this, file);
},
complete: function (file) {
dzComplete(this, file, var15671147011688676454bleVideo, dz_var15671147011688676454bleVideo[0].mockFile);
dz_var15671147011688676454bleVideo[0].mockFile = file;
},
removedfile: function (file) {
dzRemoveFile(
file, var15671147011688676454bleVideo, '{!! url("panel/restaurants/remove-media") !!}',
'video', '{!! isset($restaurant) ? $restaurant->id : 0 !!}', '{!! url("panel/uploads/clear") !!}', '{!! csrf_token() !!}'
);
}
});
dz_var15671147011688676454bleVideo[0].mockFile = var15671147011688676454bleVideo;
dropzoneFields['video'] = dz_var15671147011688676454bleVideo;
</script>
#endprepend
UploadRequest deault in laravel
public function rules()
{
return [
'file' => 'image|video|mimes:jpeg,png,jpg,gif,svg,mp4,mov,avi,mkv',
];
}
Model
// VIDEO AND ALLOWED TYPES
public function getFirstMediaUrlVideo($collectionName = 'default', $conversion = '')
{
$url = $this->getFirstMediaVideoUrlTrait($collectionName);
if($url){
$array = explode('.', $url);
$extension = strtolower(end($array));
if (in_array($extension, ['.mp4', '.mkv'])) {
return asset($this->getFirstMediaVideoUrlTrait($collectionName, $conversion));
} else {
return asset('videos/' . $extension . '.mp4');
}
}else{
return asset('videos/video_default.mp4');
}
}
thanks for all help, i don´t know why does this happen. Thanks
Your error, at least the first one, is here:
public function rules()
{
return [
'file' => 'image|video|mimes:jpeg,png,jpg,gif,svg,mp4,mov,avi,mkv',
]; ^^^^^
}
There is no video validation rule (you can check the full list here). What you should do, instead, is make use of the mimes (or mimetypes) rule alone:
return [
'file' => 'mimes:mp4,mov,avi,mkv',
];
For the full list of mime extensions that you could use, here's the list.

stopping the no results label being added to input and if input matches a label

I have created an autocomplete input, it works well but i want to expand it and make it better. But this is a struggle with my limited jquery ui knowledge and despite some trial and error i cannot seem to work out two problems.
The first problem i would like to address is making the noresult label not selectable meaning that it can't be added to the input on focus or on select or at all.
I want to make it so that if what the user has entered into the input box matched the label value but they did not select it for some reason then when they press the submit button on my form the label that is a match is selected and therefore inputted.
Here is what i have so far:
html:
<div class="search-homepage-input">
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9 col-l">
{!! Form::text('sl', null, array('class' => 'form-control shop-input', 'maxlength' =>'50', 'placeholder' => 'Search by city. Eg. London, New York, Paris...', 'id' => 'sl')) !!}
</div>
{!! Form::hidden('country', null, array('id' => 'country')) !!}
{!! Form::hidden('city', null, array('id' => 'city')) !!}
<div class="col-md-3 col-r">
{!! Form::submit('Find Shops', array('class' => 'btn btn-homepage-search')) !!}
</div>
{!! Form::close() !!}
</div>
PHP laravel:
public function autoComplete(Request $request){
$query = $request->term;
$res = City::where('name', 'LIKE', "%$query%")->orderBy('name')->paginate(5);
foreach($res as $cities ){
$usersArray[] = array(
"label" => $cities->name,
"value" => $cities->id,
"country" => $cities->countries->id,
"countryname" => $cities->countries->country
);
}
return response()->json($usersArray);
}
JS:
$('#sl').autocomplete({
source: '/autocomplete',
select: function(event, ui) {
event.preventDefault();
$("#country").val(ui.item.country); // save selected id to hidden input
$("#city").val(ui.item.value); // save selected id to hidden input
$('#sl').val(ui.item.label +', '+ ui.item.countryname)
},
focus: function(event, ui){
event.preventDefault();
$('#sl').val(ui.item.label+', '+ui.item.countryname);
},
response: function(event, ui) {
if (!ui.content.length) {
var noResult = { value:"",label:'No results found', countryname:"" };
ui.content.push(noResult);
}
}
}).autocomplete( "instance" )._renderItem = function( ul, item ) {
var li = $("<li>");
if (item.country == undefined) {
li.append("<div>" + item.label +"</div>");
} else {
li.append("<div><strong>" + item.label + "</strong>, " + item.countryname + "</div>");
}
return li.appendTo(ul);
};
An example of how to disable a selection item is found here: http://jqueryui.com/autocomplete/#categories
This example is a bit complex, since we're accessing the menu widget inside the autocomplete widget. For your code, a similar method can be used:
$("#sl").autocomplete("widget").menu("option", "items", "> li:not('.no-select')");
widget()
Returns a jQuery object containing the menu element. Although the menu items are constantly created and destroyed, the menu element itself is created during initialization and is constantly reused.
This addresses point #1.
To address point #2, you need to consider the logic of assuming a selection if the user has not made a selection. For example, if the user typed in l and got 10 results, or even just 2 results... which do you select for the user? Also, if the user has navigated away from the field, autoselect would close it's menu and destroy the results.
In my opinion, it would be better to examine the hidden fields, if they are empty, prevent the form from being submitted and force the user to select an option, make it a required field.
$(function() {
var countries = [{
country: 1,
countryname: "UK",
label: "London",
value: 1
}, {
country: 1,
countryname: "UK",
label: "Manchester",
value: 2
}];
$('#sl').autocomplete({
source: countries,
select: function(event, ui) {
event.preventDefault();
if (ui.item.label === "No results found") {
$("#sl").val("");
return false;
}
$("#country").val(ui.item.country); // save selected id to hidden input
$("#city").val(ui.item.value); // save selected id to hidden input
$('#sl').val(ui.item.label + ', ' + ui.item.countryname)
},
focus: function(event, ui) {
event.preventDefault();
$('#sl').val(ui.item.label);
},
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: 'No results found'
};
ui.content.push(noResult);
}
}
});
$("#sl").autocomplete("widget").menu("option", "items", "> li:not('.no-select')");
$("#sl").autocomplete("instance")._renderItem = function(ul, item) {
var li = $("<li>");
if (item.country == undefined) {
li.addClass("no-select").append(item.label);
} else {
li.append("<div><strong>" + item.label + "</strong>, " + item.countryname + "</div>");
}
return li.appendTo(ul);
}
$("form").submit(function(e) {
e.preventDefault();
console.log($(this).serialize());
if ($("#country").val() == "" || $("#city").val() == "") {
$("#sl").focus();
return false;
}
return true;
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="search-homepage-input">
<form>
<div class="col-md-9">
<input type="text" name="sl" class="form-control shop-input" max-length="50" placeholder="Eg. England, London, Manchester" id="sl" /> <span style="color: red; font-size: 65%;">* Required</span>
<input type="text" name="country" id="country" style="display: none;" />
<input type="text" name="city" id="city" style="display: none;" />
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-homepage">Find Teams</button>
</div>
</form>
</div>
Hope that helps.

Selecting the matching label to input on submit - autocomplete

I am creating an autocomplete on one of my search inputs and have pretty much most of it working fine except one final part which is getting the system to recognise if the input matches a label if the label has not been clicked.
For example if 'London' is typed into the input box but the user does not click on the label for 'London' then the values of the label are not sent and it does not achieve the results that their are for london as the values are sent as null.
So what i want to achieve is that if london is typed into the input box but the label is not clicked then when the submit button is clicked the matching label for london is sent. This has to be for a direct match only so if "london" matches "london". How do i go about doing this?
here is my code so far :
html:
<div class="search-homepage-input">
{!! Form::open(['route' => 'search.index', 'method' => 'GET']) !!}
<div class="col-md-9 col-l">
{!! Form::text('sl', null, array('class' => 'form-control shop-input', 'maxlength' =>'50', 'placeholder' => 'Search by city. Eg. London, New York, Paris...', 'id' => 'sl')) !!}
</div>
{!! Form::hidden('country', null, array('id' => 'country')) !!}
{!! Form::hidden('city', null, array('id' => 'city')) !!}
<div class="col-md-3 col-r">
{!! Form::submit('Find Shops', array('class' => 'btn btn-homepage-search')) !!}
</div>
{!! Form::close() !!}
</div>
PHP laravel:
public function autoComplete(Request $request){
$query = $request->term;
$res = City::where('name', 'LIKE', "%$query%")->orderBy('name')->paginate(5);
foreach($res as $cities ){
$usersArray[] = array(
"label" => $cities->name,
"value" => $cities->id,
"country" => $cities->countries->id,
"countryname" => $cities->countries->country
);
}
return response()->json($usersArray);
}
JS:
$('#sl').autocomplete({
source: countries,
select: function(event, ui) {
event.preventDefault();
if (ui.item.label === "No results found") {
$("#sl").val("");
return false;
}
$("#country").val(ui.item.country); // save selected id to hidden input
$("#city").val(ui.item.value); // save selected id to hidden input
$('#sl').val(ui.item.label + ', ' + ui.item.countryname)
},
focus: function(event, ui) {
event.preventDefault();
$('#sl').val(ui.item.label);
},
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: 'No results found'
};
ui.content.push(noResult);
}
}
});
$("#sl").autocomplete("widget").menu("option", "items", "> li:not('.no-select')");
$("#sl").autocomplete("instance")._renderItem = function(ul, item) {
var li = $("<li>");
if (item.country == undefined) {
li.addClass("no-select").append(item.label);
} else {
li.append("<div><strong>" + item.label + "</strong>, " + item.countryname + "</div>");
}
return li.appendTo(ul);
}

How to get post filedata in jQUERY

I have a form with three post data along with that I have to append a filedata(input type="file"). I didn't get the filedata, when I alert the post data in js. How can I resolve it? please suggest a solution..
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/Q0qdk.png
$('#employerid_contactus').click(function (event) {
cs_data_loader_load('#cs_employer_contactus #loader-data');
var default_message = jQuery("#cs_employer_contactus").data('validationmsg');
event.preventDefault();
var ajaxurl = jQuery(".cs-profile-contact-detail").data('adminurl');
var employerid = jQuery(".profile-contact-btn").data('employerid');
var captcha_id = jQuery(".cs-profile-contact-detail").data('cap');
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: "html",
data: $('#ajaxcontactemployer').serialize() + "&employerid=" + employerid + "&action=ajaxcontact_employer_send_mail",
success: function (response) {
jQuery("#ajaxcontactemail").removeClass('has_error');
jQuery("#ajaxcontactname").removeClass('has_error');
jQuery("#ajaxcontactcontents").removeClass("has_error");
var pattern = /^([a-zA-Z0-9_.-])+#([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
var response_data = response.split("|");
if (jQuery("#ajaxcontactname").val() == '') {
jQuery("#ajaxcontactname").addClass('has_error');
} else
if (!pattern.test(jQuery("#ajaxcontactemail").val())) {
jQuery("#ajaxcontactemail").addClass('has_error');
} else
if (jQuery("#ajaxcontactcontents").val().length < 35) {
jQuery("#ajaxcontactcontents").addClass('has_error');
}
var error_container = '';
if (response_data[1] == 1) {
error_container = '<div class="alert alert-danger"><button aria-hidden="true" data-dismiss="alert" type="button" class="close">×</button><p><i class="icon-warning4"></i>' + response_data[0] + '</p></div>';
jQuery("#ajaxcontact-response").html(error_container);
} else {
error_container = '<div class="alert success"><button aria-hidden="true" data-dismiss="alert" type="button" class="close">×</button><p><i class="icon-warning4"></i>' + response_data[0] + '</p></div>';
jQuery("#ajaxcontact-response").html(error_container);
jQuery("#ajaxcontactcontents").val('');
captcha_reload(ajaxurl, captcha_id);
}
jQuery('#cs_employer_contactus #loader-data').html('');
}
});
return false;
});
this is how form view code:
<div class="input-filed"> <i class="icon-mobile4"></i>
<?php
$cs_opt_array = array(
'id' => '',
'std' => isset($login_user_phone) ? esc_html($login_user_phone) : '',
'cust_id' => "ajaxcontactphone",
'cust_name' => "ajaxcontactphone",
'classes' => 'form-control',
'extra_atr' => 'placeholder="' . esc_html__('Phone Number', 'jobhunt') . '"',
);
$cs_form_fields2->cs_form_text_render($cs_opt_array);
?>
</div>
<div class="input-filed"> <i class="icon-mobile4"></i>
<?php
$cs_opt_array = array(
'id' => '',
'std' => '',
'cust_id' => "ajaxcontactfile",
'cust_name' => "ajaxcontactfile",
'cust_type' => "file",
'classes' => 'form-control',
'extra_atr' => '',
);
$cs_form_fields2->cs_form_text_render($cs_opt_array);
?>
</div>
When serialize the postdata I didn't get the filedata
I need to send an email using ajax. I can send name, email and phone number but not the file. I need to include file along with these fields. When I alert the serialized data in js it not showing the filedata. How can I append the file with postdata. Please help me with this.

How to Validating hidden input field of a form using jquery in MVC 4?

I am trying to Validated hidden input fields of a form in mvc4 but i failed. I try several ways but every time i failed. I searched in google and get some result but those are not work in my case. There is my code which I trying
#using (Html.BeginForm("NewSku","Product"))
{
#Html.AntiForgeryToken()
<label>Company Name :</label>
#(Html.Kendo().ComboBoxFor(x => x.CompanyId)
.Name("CompanyId")
.DataValueField("Id")
.DataTextField("CompanyName")
.Placeholder("Select Company")
.Filter(FilterType.Contains)
.DataSource(source => source.Read(read => read.Action("GetAllCompanys", "Product"))))
<br />
<label>Brand Name :</label>
#(Html.Kendo().ComboBoxFor(x => x.BrandId)
.Name("BrandId")
.DataTextField("BrandName")
.DataValueField("Id")
.Placeholder("Select Brand")
.DataSource(source => source.Read(read => read.Action("GetAllBrandsByCompany", "Product").Data("filterBrand")).ServerFiltering(true))
.AutoBind(false)
.CascadeFrom("company"))
<br />
<label>Product Name :</label>
#(Html.Kendo().ComboBoxFor(x => x.ProductId)
.HtmlAttributes(new { style = "Id=ProductComboBox" })
.Name("ProductId")
.DataTextField("ProductName")
.DataValueField("Id")
.Placeholder("Select Product")
.DataSource(source => source.Read(read => read.Action("GetAllProductsByBrand", "Product").Data("filterProduct")).ServerFiltering(true))
.AutoBind(false)
.CascadeFrom("brand"))
<br />
<label>Sku Name :</label>
#(Html.Kendo().ComboBoxFor(x => x.SkuId)
.Name("SkuId")
.HtmlAttributes(new { style = "Id=SkuComboBox" })
.DataTextField("SkuName")
.DataValueField("Id")
.Placeholder("Select Sku")
.DataSource(source => source.Read(read => read.Action("GetAllSkusByProduct", "Product").Data("filerSku")).ServerFiltering(true))
.AutoBind(false)
.CascadeFrom("product"))
<br />
<span id="ErrorMessagess" class="alert-error">
</span>
#Html.HiddenFor(x => x.CompanyName)
#Html.ValidationMessageFor(x=>x.CompanyName)
#Html.HiddenFor(x => x.BrandName)
#Html.ValidationMessageFor(x=>x.BrandName)
#Html.HiddenFor(x => x.ProductName)
#Html.ValidationMessageFor(x=>x.ProductName)
#Html.HiddenFor(x => x.SkuName)
#Html.ValidationMessageFor(x=>x.SkuName)
<input type="submit" class="k-button keep-right" value="Update" />
#Html.ValidationSummary(true)
}
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script>
$(document).ready(function () {
//$('form').validate().settings.ignore = [];
//$('form').validate({
// rules: {
// CompanyName: {
// required: true
// },
// BrandName: {
// required: true
// }
// }
//});
});
$('form').submit(function (e) {
var validator = $('form').data('validator');
validator.settings.ignore = "";
var errorList = $('form').validate().errorList;
console.log(errorList);
$("form").validate().form();
var form = $(this);
$("#CompanyName").val($("#CompanyId").data("kendoComboBox").text());
$("#BrandName").val($("#BrandId").data("kendoComboBox").text());
$("#ProductName").val($("#ProductId").data("kendoComboBox").text());
$("#SkuName").val($("#SkuId").data("kendoComboBox").text());
$.ajax({
url: form.attr("action"),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify($('form').serializeJSON()),
success: function (result) {
// console.log(result);
$("#ErrorMessagess").val(result);
return;
}
});
e.preventDefault();
});
I am defiantly doing something wrong but I am does not understand what I am doing wrong.
You must do/add this in order to enable to validate hidden input:
$(document).ready(function () {
$.validator.setDefaults({
ignore: ""
});
});

Categories