ckeditor validation for spaces - validation

How can i implement validation on ckeditor to prevent user from adding spaces only . Any answer within today will be greatly appreciated .
following is what i tried for validations so far :
//Save note from ckeditor
$("input.save_note").click(function()
{
var note_id1 = $(this).attr("rel");
var thiss1 = this;
var profile_user_id = $(this).attr("rel1");
var txt=CKEDITOR.instances.editor1.getData();
var no_space_txt = txt.replace(" ","");
// var txt = txt1.replace(/ +(?= )/g,'');
var editor_val1 = CKEDITOR.instances.editor1.document.getBody().getChild(0).getText() ;
var editor_val = editor_val1.replace(/ +(?= )/g,'');
// if( editor_val == "")
// {
// alert('sak');
// return;
// }
if(editor_val !=="" && editor_val !=="")
{
$(this).attr("disabled","disabled");
var loading_img = addLoadingImage($(this),"before");
jQuery.ajax({
url: "/" + PROJECT_NAME + "profile/save-note-in-editor",
type: "POST",
dataType: "json",
data: { "profile_user_id" : profile_user_id , "note" : txt },
timeout: 50000,
success: function(jsonData) {
if(jsonData){
$("p#clickable_note_"+note_id1).hide();
$(thiss1).hide();
$(thiss1).siblings("input.edit_note").fadeIn();
$("span#"+loading_img).remove();
$(".alert-box").remove();
$(".alert-box1").remove();
$(".alert-box2").remove();
showDefaultMsg( "Note saved successfully.", 1 );
$(thiss1).removeAttr('disabled');
// $(".cke_inner cke_reset").hide();
CKEDITOR.instances.editor1.destroy();
$(".editor1").hide();
$("p#clickable_note_"+note_id1).html(jsonData);//to display the saved note in clickable p tag .
$("p#clickable_note_"+note_id1).fadeIn('slow');// To display the note paragraph again after editing and saving note.
}
else{
$(thiss1).removeAttr('disabled');
$(thiss1).before('<span class="spanmsg" id="note-msg" style="color:red;">Server Error</span>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
else
{
alert("You cannot make an empty note. Please insert some text.");
}
});
I have implement alert to check if no text is entered but i want to check if user only enter spaces . please suggest some accurate way .

Since you are evidently using jQuery, you can add jQuery.trim() as an additional check for your condition:
jQuery.trim(editor_val).length != 0
This will trim all whitespace from the submitted form and check whether there are any characters remaining. If the input consists only of whitespace, the statement will evaluate to false. You would integrate it into the following line:
if (editor_val != "" && editor_val != "" && jQuery.trim(editor_val).length != 0)

Related

Trouble accessing the property of a class in Ajax

In index.cshtml I am using Ajax. In click event of .removelink to get changes from action controller as follows:
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '' || recordToDelete != null) {
// Perform the ajax post
$.ajax({
//contentType: 'application/json',
//dataType: 'text',
type: 'post',
dataType: 'JSON',
url: '/ShoppingCart/RemoveFromCart/',
data: { id: recordToDelete },
success: function (data) {
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
}
else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
});
}
});
And in controller:
//AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public IActionResult RemoveFromCart(int id)
{
//Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
//string albumName = _context.Carts
//.Single(item => item.RecordId == id).Album.Title;
Cart cartt = ShoppingCart.getCartForGetalbumName(id);
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = HtmlEncoder.Default.Encode(cartt.Album.Title) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
//CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
}
However, it does not work. Additionally, the text of the tags does not change and fadeOut() does not work.
When I send a unit field (eg, a string or an integer) Jason reads it well.
However, when I send a class containing some properties (like the example above), its value in the data parameter is problematic.
Please modify your property to lowercase , try to use :
success: function (data)
{
if (data.itemCount == 0) {
$('#row-' + data.deleteId).fadeOut('slow');
}
else {
$('#item-count-' + data.deleteId).text(data.itemCount);
}
$('#cart-total').text(data.cartTotal);
$('#update-message').text(data.message);
$('#cart-status').text('Cart (' + data.cartCount + ')');
}
i add The following code to convert data to json in RemoveFromCart controller action:
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);
and return json type :
[HttpPost]
public IActionResult RemoveFromCart(int id)
{
//Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
//string albumName = _context.Carts
//.Single(item => item.RecordId == id).Album.Title;
Cart cartt = ShoppingCart.getCartForGetalbumName(id);
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message ="محصول"+ cartt.Album.Title +
"از سبد خریدتان حذف گردید.",
CartTotal = cart.GetTotal(),
//CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
var resulTtoJson = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Json(resulTtoJson);
also add the following code in view to convert data to javascript type:
var data =JSON.parse(dataa);
and use it:
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
// alert(recordToDelete);
if (recordToDelete != '' || recordToDelete != null) {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart/", { id: recordToDelete},
function (dataa) {
// Successful requests get here
// Update the page elements
var data =JSON.parse(dataa);
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
});
}
});

Materialize autocomplete : Why AJAX called before entering any character?

I'm using autocomplete with materialize and i'm retrieving the data with ajax call, it works fine but when i want to call ajax only after entering caracters(using onkeyup event), the drop down list will not be showing correctly !!!!
Before i forget please help me to show a "NOT FOUND" in the drop down list if no data founded (because my else condition doesn't work). here is my code and thanks a lot in advance :
$(document).ready(function() {
var contents = $('#autocomplete-input')[0];
contents.onkeyup = function (e) {
$.ajax({
type: 'GET',
url: Routing.generate('crm_search_lead', {"search":
$(this).val()}),
success: function (response) {
var contacts = {};
if (true === response.success) {
var result = response.result;
for (var i = 0; i < result.length; i++) {
var lastName = result[i].lastName ?
result[i].lastName : '';
var firstName = result[i].firstName ?
result[i].firstName : '';
contacts[lastName + " " + firstName] = null;
}
$('input.autocomplete').autocomplete({
data: contacts,
minLength: 2,
});
} else {
$('input.autocomplete').autocomplete({
data: {
"NOT FOUND": null
}
});
}
}
});
}
});
Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered.

My jquery and ajax call is not responding and showing unexpected error in console

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text
Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

Ajax returned title value for tooltip isn't in one line, in Bootstrap

I am having a weird bug with dynamic created tooltips using ajax. I am creating a simple notes function. When data is coming from the database everything looks nice
But when i am creating a new note, using ajax i am creating the new entry in the db and then return the value to be shown in the new tooltip...But this is how it comes out to the user.
Is there a way to 'force' it to one line like the 1st image ?
Here is the code in question:
.js part
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
////////
var inText = $('.evnt-input').val(); //Whatever the user typed
$.ajax({
type: 'POST',
url: 'request.php',
data: {action:'addnotes', data: inText},
dataType: 'json',
success: function(s){
if(s.status == 'success'){
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
}
},
error: function(e)
{
console.log('error');
}
});
.php part
if ($_POST["action"] == "addnotes"){
function addnotes($data)
{
$insert = db_query("insert into notes(description) values('$data')");
if($insert)
return db_inserted_id();
}
$data = $_POST['data'];
$status = addnotes($data);
if($status != ''){
$timestamp = strtotime(date('Y-m-d G:i:s'));
$curTime = date( 'F j, Y, g:i a', $timestamp );
$output = array('status'=>'success','id'=>$status, 'curTime'=>$curTime);
}
else
$output = array('status'=>'error');
echo json_encode($output);
}
I have an identical code with the .js part to show the notes when the page loads...of course that works fine.
Lol it was so easy.... I changed the .js part to this, to 'reinitialize' the tooptip:
if(s.status == 'success'){
var curTime = s.curTime;
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
}

Javascript JSON results throws text is null error

I am using ajax to pull photos from instagram. Below is the ajax call:
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/media/search?lat=" + lat +"&lng=" + lng + "&distance=" + distance + "&access_token=" + accessToken + "",
success: function(data) {
for (var i = 0; i < 6; i++) {
$("#instagram").append("<li><a class='group' title='' href='" + data.data[i].images.standard_resolution.url +"'><img src='" + data.data[i].images.thumbnail.url +"' /></a>");
}
}
});
This works well due to the fact that the anchors title attribute is left blank. I was using title='" + data.data[i].caption.text + "' to pull the instagram caption as the anchor title. For the most part, this works, but I often get the following error: "Uncaught TypeError: Cannot read property 'text' of null"
I am assuming this is happening from one of two reasons:
A) no caption at all
B) a caption with characters that will not work as a title.
Does anyone know why this is happening, and also how I can fix this? I tried the following but it throws the same error:
if(data.data[i].caption.text != null) {
var title = data.data[i].caption.text;
} else {
var title = "";
}
Any ideas?
If there is no caption attached, Instagram does not return that field. Just add another null check.
if (data.data[i].caption !=null) {
if(data.data[i].caption.text != null) {
var title = data.data[i].caption.text;
}
} else {
var title = "";
}
for (x in data.data) {
var title_text = '';
if (data.data[x].caption != null) {
if (data.data[x].caption.text != null) {
title_text = data.data[x].caption.text;
}
} else {
title_text = "";
}
$("#instagram").append("<a target="_blank" href="' + data.data[x].link + '">" + title_text);
}

Resources