jquery ui helper mvc Select event - asp.net-mvc

I'm trying to access "select" event when user select from jquery ui autocomplete populated list i want to fire an event when jquery ui autocomplete "Select" event called.
My Problem is
I am using JqueryUiHelper MVC and dont know how to use select event using htmlHelper http://jqueryuihelpers.apphb.com/Docmo/Autocomplete
#using JQueryUIHelpers
#Html.JQueryUI().AutocompleteFor(x => x.SearchText, Url.Action("SearchFilter"), new { #class = "form-control", placeholder = "Company name here for search..", style = "max-width:none;" }
)
#section Styles {
#Styles.Render("~/Content/jqueryui")
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
}
any help would be greatly appreciated.

I came with solution got from https://api.jqueryui.com/autocomplete/#event-select
Bind an event listener to the autocompleteselect event:
$(function () {
$("#SearchText").on("autocompleteselect", function (event, ui) {
event.preventDefault();
$(this).val(ui.item.value);
$('#btnGo').click();
});
});

Related

ASP.NET: How to get from Dropdownlist to Autocomplete

I have a dropdownlist and want to turn it into autocomplete using jquery.
The dropdown looks like this and works:
#Html.DropDownListFor(m => m.CategoryID, new SelectList(Model.Categories, "ID", "Name", Model.CategoryID), "Categories", new { #class = "form-control" })
I also added an autocomplete field using jquery that works. But so far I can only populate it with dummy data:
$(function () {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp"
];
$("#tags").autocomplete({
source: availableTags
});
});
How can I populate my dropdown field with the data that is available in the dropdown?
Thank you in advance!
You need to set the source as an action method which returns data you want to show as autocomplete option in JSON format.
$(function(){
$("#tags" ).autocomplete({
source: "#Url.Action("SearchCategories","Home")",
minLength: 1,
select: function (event, ui) {
//If you want to do something on the select event, you may do it here
//$("#tags").html(ui.item.label);
}
});
})
Make sure you have an action method called SearchCategories in your HomeController which returns the data you want.
public ActionResult SearchCategories(string term)
{
var db= new MyDbContext();
var results = db.Categories.Where(s => s.Name.StartsWith(term))
.Select(x=>new { id =x.Id,
label =x.Name }).ToList();
return Json(results,JsonRequestBehavior.AllowGet);
}
This should enable the autocomplete on an input with id tags,assuming you have jQuery ui library(and it's dependencies) loaded properly in your page and you do not have any other script errors in your page. I have used Url.Action helper method to generate the correct relative url to the action method. It will work fine if your js code is inside a razor view. But if your code is inside an external js file, you should follow the approach described in this post.

jquery-ui tag "a" inside tooltip click event

fellows! I'm doing some frontend work using doT.js for generating content and jquery-ui for displaying tooltips.
{{##def.defboardtooltip:
<div class='tooltip'>
<!-- some html code -->
<a id='bdetails' href='#'>Click for details</a></div>
</div>
#}}
And how it is used:
<div class="participant" title="{{#def.defboardtooltip}}">
I'm trying to add the event to the a element with jquery as such ():
$(document).ready(function () {
// ...enter code here
$('#bdetails').click(function (e) {
// some code
console.log('fired');
});
});
And I never see the "fired". I'm confused.
jQuery Event delegates are your friend here.
Try:
$(function()
{
$(document).on('click', '#bdetails', function(e)
{
var a = $(this);
});
});
This will filter the event to just your #bdetails element, you can use any valid jQuery seletor here also; e.g., 'a' to delegate all anchor tag clicks.

initialize select2 dropdown on jquery datepicker

I have an application with all the drop down boxes customized by select2 plugin, obviously like this:
$("select").select2();
However, the select element on a jquery datepicker is not customized. And I couldn't figure out where to initialize this in the jquery datepicker function. The following is what I want to achive. I want a function that can replace init that can get the datepicker dom element.
$(".datepickerInput").datepicker({
init : function(datepickerElement) {
datepickerElement.find("select").select2();
}
});
I appreciate your help. Thanks.
The issue you are facing is that Datepicker doesn't have a "after show" callback function. That is, there is no available method/option that can run code after the datepicker has been showned.
There is some discussion and some possible answers in jQuery Datepicker "After Update" Event or equivalent
So, for now, you can make that work by extending Datepicker, like this:
<p>Date: <input type="text" id="datepicker"></p>
<script>
$(document).ready(function() {
// Code from the related question. Used the answer from #Markus
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function(inst) {
$.datepicker._updateDatepicker_original(inst);
var afterShow = this._get(inst, 'afterShow');
if (afterShow)
afterShow.apply((inst.input ? inst.input[0] : null)); // trigger custom callback
}
// Now that we have `afterShow`, we can initialize Select2.
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true,
afterShow: function() {
$(".ui-datepicker select").select2();
}
});
});
</script>

Multiple elements with same class make jquery click event to fire multiple times

I display user comments. Each comment is one div and each div has <a> tag with class 'commentLikeLink'. I bind jquery click event to 'commentLikeLink' class but If I have 10 comments and click on one like button I get event fired 10 times.
I know that this happen's because I have same class multiple times. But How to stop this?
Here's the code:
...
<div class="commentBox"">
...
#Html.ActionLink(likeText, "LikeComment", "Comment", null, new { id = Model.CommentId, #class = "commentLikeLink" })
...
Event code:
$(function () {
$('.commentLikeLink').click(function (event) {
var commentId = event.target.id;
$.ajax({
url: this.href,
type: 'POST',
data: { commentId: commentId },
context: this,
success: function (result) {
if (result.msg == '1') {
$(this).text('Dislike');
}
else if(result.msg == '2') {
$(this).text('Like');
}
}
});
return false;
});
});
You shouldn't be getting 10 clicks. You can bind the click event to the class, but the context in which the event is fired is the individual element, so if you had some markup that looked like this:
<p>
Liked?
<br />
Liked?
<br />
Liked?
<br />
Liked?
</p>
Then this would work, setting the link text to "Liked!" as each one is clicked:
$(document).on("click", ".clickItem", function (ev) {
$(this).text("Liked!");
});
Have you debugged the code? Are you sure you're getting 10 clicks all at once?
yes binding the click event to the class is a better solution, but it can actually get fired multiple times if you use it on the item it self or the class it self !
so instead of having this : $('.commentLikeLink').click(function (event) {//do things here }
you should do this and it will only fire once :
$(document).on("click", ".commentLikeLink", function (ev) {
//do things here
});
I had this happen before when i accidently included the same .click script function multiple times in the page. Make sure your javascript is only included once

Ckeditor update textarea

I am trying to get the ckeditor working. Obviously it doesn't make use of the textarea so on submit the form doesn't submit the text in the editor. Beceause I make use of polymorphic associations etc. I can't make a onsubmit function to get the value of the textarea (when the form is submitted) .
So I found this question: Using jQuery to grab the content from CKEditor's iframe
with some very good answers. The answers posted there keep the textarea up to date. That is very nice and just what I need! Unfortunately I can't get it to work.
Does somebody know why (for example) this doesn't work?
I have a textarea (rails but it just translates to a normal textarea):
<%= f.text_area :body, :id => 'ckeditor', :rows => 3 %>
And the following js:
if(CKEDITOR.instances.ckeditor ) {
CKEDITOR.remove(CKEDITOR.instances.ckeditor);
}
CKEDITOR.replace( 'ckeditor',
{
skin : 'kama',
toolbar :[['Styles', 'Format', '-', 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', 'Link']]});
CKEDITOR.instances["ckeditor"].on("instanceReady", function()
{
//set keyup event
this.document.on("keyup", CK_jQ);
//and paste event
this.document.on("paste", CK_jQ);
}
function CK_jQ()
{
CKEDITOR.instances.ckeditor.updateElement();
}
I get the following "error" in my firebug.
missing ) after argument list
[Break on this error] function CK_jQ()\n
Before submit do:
for(var instanceName in CKEDITOR.instances)
CKEDITOR.instances[instanceName].updateElement();
have you figured it out?
I'm using CKEditor version 3.6.1 with jQuery form submit handler. On submit the textarea is empty, which to me is not correct. However there is an easy workaround which you can use, presuming all your CKEditor textareas have the css class ckeditor.
$('textarea.ckeditor').each(function () {
var $textarea = $(this);
$textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
});
Execute the above before you do your submit handling ie. form validation.
Thanks #JohnDel for the info, and i use onchange to make it update every change.
CKEDITOR.on('instanceReady', function(){
$.each( CKEDITOR.instances, function(instance) {
CKEDITOR.instances[instance].on("change", function(e) {
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
});
});
});
Combination of all of the above answers into one.
Create a new custom.js file and add this:
CKEDITOR.on('instanceReady', function(){
$.each( CKEDITOR.instances, function(instance) {
CKEDITOR.instances[instance].on("instanceReady", function() {
this.document.on("keyup", CK_jQ);
this.document.on("paste", CK_jQ);
this.document.on("keypress", CK_jQ);
this.document.on("blur", CK_jQ);
this.document.on("change", CK_jQ);
});
});
});
function CK_jQ() {
for ( var instance in CKEDITOR.instances ) { CKEDITOR.instances[instance].updateElement(); }
}
You don't have to worry about the name of the textarea, just add a class ckeditor in the textarea, the above and you are done.
ADD Function JavaScript for Update
function CKupdate() {
for (instance in CKEDITOR.instances)
CKEDITOR.instances[instance].updateElement();
}
It's work. Cool
Just Add
CKEDITOR.instances.textAreaClientId.on('blur', function(){CKEDITOR.instances. textAreaClientId.updateElement();});
where textAreaClientId is your instance name
Regards
CKEDITOR.instances["ckeditor"].on("instanceReady", function()
{
//set keyup event
this.document.on("keyup", CK_jQ);
//and paste event
this.document.on("paste", CK_jQ);
})
I just increase that to the response of T.J. and worked for me:
$("form").on("submit", function(e){
$('textarea.ckeditor').each(function () {
var $textarea = $(this);
$textarea.val(CKEDITOR.instances[$textarea.attr('name')].getData());
});
});
On load:
$(function () {
setTimeout(function () {
function CK_jQ(instance) {
return function () {
CKEDITOR.instances[instance].updateElement();
};
}
$.each(CKEDITOR.instances, function (instance) {
CKEDITOR.instances[instance].on("keyup", CK_jQ(instance));
CKEDITOR.instances[instance].on("paste", CK_jQ(instance));
CKEDITOR.instances[instance].on("keypress", CK_jQ(instance));
CKEDITOR.instances[instance].on("blur", CK_jQ(instance));
CKEDITOR.instances[instance].on("change", CK_jQ(instance));
});
}, 0 /* 0 => To run after all */);
});
There have been some API changes with the latest versions of CKEditor, so here's an answer for CKEditor 5:
let ckeditor;
// Create a CKEditor, and store its handle someplace that you may
// access later. In this example, we'll use the `ckeditor` variable:
ClassicEditor
.create(document.querySelector("textarea"), {})
.then(editor => { ckeditor = editor; });
// When your form submits, use the `updateSourceElement` method
// on the editor's handle:
document.querySelector("form").addEventListener("submit", function() {
ckeditor.updateSourceElement();
});
To my knowledge, CKEditor does this automatically when you submit a form, so this particular example shouldn't actually do anything. But it is useful when you need the content of the textarea to udpate without submitting the form that contains it.
All above answer are focusing on how to fix this error but I want to take the answer on what cause me this error
I had a
<textarea class="ckeditor" rows="6" name="Cms[description]"></textarea>
changed to
<textarea class="ckedit" rows="6" name="Cms[description]"></textarea>
I changed class attribute value to anything other than ckeditor and boom error gone.
Hope that help

Resources