Deleting a comment leaves gaps - javascript

I'm currently working on an idea whiteboard, but it seems that whenever I try to delete comments, blank spaces are left between the ideas.
For example, if I have the following comments:
But when I delete something:
How would I make it so that no gaps are left between comments?
Here is my code so far:
jQuery(function ($) {
$('#chat').on('click', '.delete', function(e) {
$(this).parent().remove();
});
var socket = io.connect();
var $messageForm = $('#sendmessage');
var $messageTitle = $('#title');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.click(function (e) {
if ($.trim($("#title").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
}
if ($.trim($("#message").val()).length === 0) {
alert('You must provide valid input');
$messageTitle.val('');
$messageBox.val('');
return false;
} else {
e.preventDefault();
socket.emit('send message', '<span class="idea"><b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val() + ' ' + '[' + '<a class="delete" href="#">Delete</a>' + ']</span>');
$messageTitle.val('');
$messageBox.val('');
}
});
socket.on('new message', function (data) {
$chat.prepend(data + "<br/>");
});
});
The HTML that remains:
<div id="chat"><span class="idea"><b>sfdf</b> - czxczxc [<a class="delete" href="#">Delete</a>]</span>
<br><span class="idea"><b>dsdfsd</b> - sdfsdfsdf [<a class="delete" href="#">Delete</a>]</span>
<br>
<br><span class="idea"><b>dsfsdf</b> - sdfsdf [<a class="delete" href="#">Delete</a>]</span>
<br>
</div>

Instead of using <br>s to separate ideas, just add a CSS rule so that each idea is on its own line
<style>span.idea { display: block }</style>
and then
$chat.prepend(data + "<br/>");
becomes
$chat.prepend(data);
hopefully after you've filtered data to prevent XSS.

I believe you should use 'remove' instead of 'empty'.
Empty does not remove the element, it just empties it.
Manual:
http://api.jquery.com/remove/

i guess its the br that is still in the dom, that you insert by doing this:
$chat.prepend(data + "<br/>");
maybe you change you code so that it uses a list, that would look like this:
<ul>
<li class="id">message1</li>
<li class="id">message2</li>
</ul>
you would have to edit change these lines:
socket.emit('send message', '<li class="idea"><b>' + $messageTitle.val() + '</b>' + ' - ' + $messageBox.val() + ' ' + '[' + '<a class="delete" href="#">Delete</a>' + ']</li>');
some lines below change this:
$chat.prepend(data);
and on top add this:
var chatUlElement = $('ul');
var $chat = $('#chat').append(chatUlElement);

Related

getJSON does not work on button click but does with hitting enter key

My getJSON request and the rest of my function works fine if the user hits enter after filling out the field however my function does not get past the getJSON request if they click the search button.
I've found some similar post on SO but haven't been able to fix my issue yet. I've tried adding .live before my .click event and also tried adding e.preventDefault in a couple different spots but that hasn't resolved it either.
My HTML looks like this
<input id="zipCode" maxlength="5" type="text"> <button id="zipSearch" onclick="findByZip()">Search</button></p>
My JS looks like this
$(document).ready(function () {
$('#zipSearch').click(findByZip);
$('#zipCode').bind('keydown', function (e) {
if (e.keyCode === 13) { // 13 is enter key
e.preventDefault();
findByZip();
return false;
}
});
}
);
function findByZip() {
console.log('running findByZip');
var zip = $('#zipCode').val();
var stateName = $('#stateName');
stateName.text("Reps for " + zip);
$("#results").empty();
var url='//something.com/api/Reps?Zipcode=' + zip;
console.log(url);
$.getJSON(url, function (data) {
console.log(data);
if (data.length == 0) {
var header = "<h3>No matches found.</h3>"
$('#result').append(header);
}
else {
$.each(data, function (i, item) {
var header = "<h3>Manufacturer's Representative</h3>";
var businessName = $("<h4 id=businessName" + i + "></h4>").text(item.BusinessName);
var contactName = $("<h4 id=contactName" + i + "></h4>").text(item.Contact);
var address = $("<div id=address" + i + "></div>").text(item.Address);
var address2 = $("<div id=address2" + i + "></div>").text(item.City + ", " + item.State + " " + item.Zipcode);
var phone1 = $("<div id=phone1" + i + "></div>").text("PH: " + item.Phone1);
var phone2 = $("<div id=phone2" + i + "></div>").text("PH2: " + item.Phone2);
var fax = $("<div id=fax" + i + "></div>").text("FAX: " + item.Fax);
var email = '<div id=email' + i + '>' + item.Email + '</div>';
var website = '<div id=website' + i + '>' + item.Website + '</div>';
if (item.RegionalRepId == item.Id) {
header = "<h3>Regional Manager</h3>";
}
$("#results").append(header, businessName, contactName, address, address2, phone1, phone2, fax, email, website);
if (businessName[0].textContent == "null") {
$("#businessName" + i).remove();
}
if (contactName[0].textContent == "null") {
$("#contactName" + i).remove();
}
if (address[0].textContent == "null") {
$("#address" + i).remove();
$("#address" + i).remove();
}
if (phone1[0].textContent == "PH:null") {
$("#phone1" + i).remove();
}
if (phone2[0].textContent == "PH2:null") {
$("#phone2" + i).remove();
}
if (fax[0].textContent == "FAX:null") {
$("#fax" + i).remove();
}
if (email.includes("null")) {
$("#email" + i).remove();
}
if (website.includes("null")) {
$("#website" + i).remove();
}
});
}
});
}
expected result is to just pull and display data by different click events and searches to a map. Clicking on a state works, typing in a zipcode and hitting enter works, but typing in a zipcode and clicking search does not work.
If you guys have any suggestions it would be greatly appreciated. Young in my career, mostly have worked in .NET, C#, and Xamarin. Unfortunatly JS and JQuery are a little new to me. Thanks!
My form wasn't preventing a default on form via the submit button. It was only preventing the default on enter. Once I added type="button" inside my <button> tag everything worked fine.

Creating dynamic objects in a loop - array is not working

Basically I have two exact same divs and I want to add to both of them Bootstrap 4 color palette. Hard coding it is easy but I would like to do it in a dynamic way so theoretically future divs can have color palettes without writing new code manually.
The divs are (only the id is different):
<div id="myContainer">
<a class="color-picker">Pick color</a>
<input class="box" type="text" value="Write about yourself here">
</div>
<div id="myContainer2">
<a class="color-picker">Pick color</a>
<input class="box" type="text" value="Write about yourself here">
If I write this code, everything works fine:
var colorPickerArray = [];
$(function(){
colorPickerArray[0] = $('#myContainer .color-picker');
colorPickerArray[0].colorpicker();
colorPickerArray[0].on('changeColor', function(e){
$('#myContainer .color-picker').empty();
$('#myContainer .color-picker').append(' ');
if(e.color==null)
$(this).val('transparent').css('background-color', '#fff');//tranparent
else
$('#myContainer .box').css('color', e.color.toHex())
});
});
$(function(){
colorPickerArray[1] = $('#myContainer2 .color-picker');
colorPickerArray[1].colorpicker();
colorPickerArray[1].on('changeColor', function(e){
$('#myContainer2 .color-picker').empty();
$('#myContainer2 .color-picker').append(' ');
if(e.color==null)
$(this).val('transparent').css('background-color', '#fff');//tranparent
else
$('#myContainer2 .box').css('color', e.color.toHex())
});
});
It's just a duplication with different keys (0 and 1) and different divs ('#myContainer' and 'myContainer2'). But when I transform this code to a loop, it doesn't work:
var resizeArr = ['#myContainer', '#myContainer2'];
$(function(){
for (var i = 0; i < resizeArr.length; i++) {
colorPickerArray[i] = $(resizeArr[i] + ' .color-picker');
colorPickerArray[i].colorpicker();
colorPickerArray[i].on('changeColor', function(e){
$(resizeArr[i] + ' .color-picker').empty();
$(resizeArr[i] + ' .color-picker').append(' ');
if(e.color==null)
$(this).val('transparent').css('background-color', '#fff');//tranparent
else
$(resizeArr[i] + ' .box').css('color', e.color.toHex())
});
}
});
The actual code is exactly the same, just duplicated by the loop this time. Is it because changing the value of i affects the event listeners? What should I do instead of using arrays here?
Edit
I did come out with a solution to create those dynamic color palettes and I would like to share it for whom it may help. But please I would still love to know why the previous method doesn't work, just for deeper understanding of js.
Anyway, here is the solution:
$('body > div .color-picker').mousedown(function(e) {
var target = $(e.target);
for (var i = 0; i < resizeArr.length; i++) {
if (target.is($(resizeArr[i] + ' .color-picker i'))) {
var a = $(resizeArr[i] + ' .color-picker');
a.colorpicker();
a.on('changeColor', function(e){
var b = (a[0].parentElement);
b = '#' + b.id
$(b + ' .color-picker').empty();
$(b + ' .color-picker').append(' ');
if(e.color==null)
$(this).val('transparent').css('background-color', '#fff');//tranparent
else
$(b + ' .color-picker').val(e.color).css('background-color', e.color);
$(b + ' .box').css('color', e.color.toHex())
});
}
}
});
one problem i see is you're using resizeArr[i] in event 'changeColor', i is resizeArr.length when it executes due to scoping.
you can read more about let here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
You can use follow method, by create current name variable for each colorPickerArray[i]:
var colorPickerArray = [];
var resizeArr = ['#myContainer', '#myContainer2'];
$(function(){
for (var i = 0; i < resizeArr.length; i++) {
colorPickerArray[i] = $(resizeArr[i] + ' .color-picker');
colorPickerArray[i].colorpicker();
colorPickerArray[i].on('changeColor', function(e){
//console.log(resizeArr[i]); //undefined here!
var current = $(this).parent();
var name = "#" + current[0].id; //console.log(current[0].id);
$(name + ' .color-picker').empty();
$(name + ' .color-picker').append(' ');
if(e.color==null)
$(this).val('transparent').css('background-color', '#fff');//tranparent
else
$(name + ' .color-picker').val(e.color).css('background-color', e.color);
$(name + ' .box').css('color', e.color.toHex())
});
}
});

Verify if data already in db, with more inputs same class

I have (part of) a form HTML produced by a PHP loop:
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
<input type="text" class="store">
The input goes in a db tables:
store
-------
cityID
cityname
store
I have a JavaScript that alerts me if the store entered is already in other cities:
$(document).ready(function() {
$('.store').on('change', function() {
var storeValue = $('.store').val();
$.post('stores.php', {'word': storeValue}, function(data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v) {
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
alert('Already in the following cities: ' + '\n' + verifStore);
});
});
});
Problem is that JavaScript is fired by the .class and I have more .class inputs in my form, so (of course) it doesn't work properly. How should I modify my JavaScript code? Maybe there is in JavaScript a way to consider each .class field separately... Something like .each or .foreach ...?
Let's say, you have been asked to put 4 different values for the city and they are not supposed to be present in the DB. I would create a class named error:
.error {border: 1px solid #f00; background: #f99;}
And now, I would go through each of the input using $.each:
$(".store").each(function () {
$this = $(this);
$this.removeClass("error");
$.post('stores.php', {'word': $this.val()}, function (data) {
if ( /* Your condition if the word is present. */ )
alert("Already there!");
});
});
Note that this code will send as many as requests to the server as many inputs are there. So handle with care.
You can optimize your function if you do just one request.
var values = $(".store").map(function(){
return this.value;
}); // values is an array
$this.removeClass("error");
// stores.php should be ready to receive an array of values
$.post('stores.php', {'word': JSON.stringify(values)}, function (data) {
var verifStore = '';
var json = $.parseJSON(data);
$.each(json, function(k, v){
verifStore += '[' + v.cityID + '] ' + v.cityName + '\n';
});
if(varifStore)
alert('Already in the following cities: ' + '\n' + verifStore);
});
SOLUTION (at least for me...)
After reading all answers and suggestions, I was able to make it work with this code. Hope it will be helpful for others :)
$(document).ready(function() {
$('.store').each (function(){//do it for every class .store
var $this = $(this); //get this object
$this.on('change', function(){ //when this change...
var searchValue = this.value; //assign the input to a variable
if (searchValue != ''){ //if the variable is not emprty
$.post('stores.php',{'term' : searchValue}, function(data) { //check and return data in alert
if (data.length < 10){ // if number not in db, green
$this.css({'border' : 'solid 4px #17BC17'});
}
var resultAlert = '';
var jsonData = $.parseJSON(data);
$.each(jsonData, function(k, v){
resultAlert += '[' + v.cityID + '] ' + v.cityname + ' ' + v.value + '\n';
}); //each
alert('ALERT!' + '\n' + 'store in other cities' + '\n' + searchValue + ': ' + '\n' + resultAlert );
$this.css({'border' : 'solid 4px #FFCC11'}); // if in db, yellow
});// post
}//close if
if (searchValue == ''){ //if the variable is empty, this turn green, if you delete a yellow number
$this.css({'border' : ''});
}
}); //close on change
});//close .each
});

Manipulating JQuery .text() output

I am building a Twitter like site that is fed random tweets that I want to export to the website in a particular manner. I have most of my requirements met up to this point, the only issue I am having is turning the jQuery text of a Twitter user and handle it into a link that can be clicked.
My code snippet below exhibits my work so far:
<script>
$(document).ready(function(){
var $body = $('.middle');
$body.html();
var index = streams.home.length - 1;
var newTweets = function(index){
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div class=tweetBox></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
$tweet.appendTo($body);
index -= 1;
}
}
newTweets(index);
$('button').on('click', function(){
index = streams.home.length - 1;
newTweets(index);
});
});
</script>
The line that is giving the issue is $tweet.text('#' + tweet.user + ': ' + tweet.message + tweet.created_at);
I want to take tweet.user and convert it into a click-able link. Any suggestions on ways to attack this would be very much appreciated.
You have to use the HTML function of jQuery. http://api.jquery.com/html/
like this:
var link = $('<a>', {text: tweet.user, href: '#'}).prop('outerHTML');
$tweet.html('#' + link + ': ' + tweet.message + tweet.created_at);
it will do the work.
If I understand correctly, then this is what you want
var link = $('<a>', {text: tweet.user, href: '#'}).prop('outerHTML');
$tweet.html('#' + link + ': ' + tweet.message + tweet.created_at);

js bb codes duplicate action error

just made my own bbcodes plugin for textarea
but i wasn`t able to correct the error..
If the page uses 2 textareas, in 1st one actions are dublicated twice.
If the page uses 1 textarea, everything is ok.
How to fix it?
code:
/*
* plugin: bbcodes based on jquery.bbcode.js
* version: 0.2
*
* author: atomos
* site: http://light-engine.ru
*/
(function($){
$.fn.bbcode = function(options){
var options = $.extend({
tag_bold: true,
tag_italic: true,
tag_right: true,
tag_center: true,
tag_left: true,
tag_link: true,
tag_image: true,
image_url: 'bbimage/'
}, options||{});
var taid = $(this).attr('name');
var text = '<div class="btn-group">';
if(options.tag_bold)
{
text = text + '<a class="btn" title="Жирный" href="#" id="b"><i class="icon-bold"></i></a>';
}
if(options.tag_italic)
{
text = text + '<a class="btn" title="Курсив" href="#" id="i"><i class="icon-italic"></i></a>';
}
text = text + '</div><div class="btn-group">';
if(options.tag_right)
{
text = text + '<a class="btn" title="Направо" href="#" id="right"><i class="icon-align-right"></i></a>';
}
if(options.tag_center)
{
text = text + '<a class="btn" title="Центр" href="#" id="center"><i class="icon-align-center"></i></a>';
}
if(options.tag_left)
{
text = text + '<a class="btn" title="Налево" href="#" id="left"><i class="icon-align-left"></i></a>';
}
text = text + '</div><div class="btn-group">';
if(options.tag_link)
{
text = text + '<a class="btn" title="Ссылка" href="#" id="url"><i class="icon-share-alt"></i></a>';
}
if(options.tag_image)
{
text = text + '<a class="btn" title="Изображение" href="#" id="img"><i class="icon-picture"></i></a>';
}
text = text + '</div>';
$(this).wrap('<div id="bbcode-' + taid + '"></div>');
$('#bbcode-' + taid).prepend('<div class="btn-toolbar">' + text + '</div>');
$('.controls a[class=btn]').click(function()
{
var id = $(this).parent('.btn-group').parent('.btn-toolbar').parent().attr('id');
var area = $('textarea[name=' + id.substring(7) + ']').get(0);
var button_id = $(this).attr('id');
var param = '';
var start = '[' + button_id + ']';
var end = '[/' + button_id + ']';
if (button_id == 'img')
{
param = prompt('Введите адрес картинки:', 'http://');
if (param && param != 'http://') start += param;
else return false;
}
else if (button_id == 'url')
{
param = prompt('Введите адрес ссылки:', 'http://');
if (param && param != 'http://') start = '[url href=' + param + ']';
else return false;
}
insert(start, end, area);
return false;
});
}
function insert(start, end, element)
{
if (document.selection)
{
element.focus();
sel = document.selection.createRange();
sel.text = start + sel.text + end;
}
else if (element.selectionStart || element.selectionStart == '0')
{
element.focus();
var startPos = element.selectionStart;
var endPos = element.selectionEnd;
element.value = element.value.substring(0, startPos) + start + element.value.substring(startPos, endPos) + end + element.value.substring(endPos, element.value.length);
}
else
{
element.value += start + end;
}
}
})(jQuery);
i have demo: here
Your problem is this:
$(document).ready(function(){
$('textarea').each(function() {
$(this).bbcode();
});
});
That means that your script is going trough every textareas on the page and run bbcode() function on them.
For some reason it iterates trough the first textarea as many times as there are textareas on page.
So if you have 2 areas function will be executed 2 times on first area 1 time on second.
If you have 3 areas function will be executed 3 times on first, 2 times on second and 1 time on last one.
And so on...
I would suggest to heavily adjust your script so that you can forward an ID parameter of specific textarea that you wish to manipulate when you do an onclick event on osme of bbcode buttons like:
<textarea class="input-xxlarge" id="area_1" rows="3"></textarea>
<a onclick="$('#area_1').bbcode();" class="btn" title="Жирный" href="#" id="b"><i class="icon-bold"></i></a>
This is only a tip in which direction you should go... And also consider not doing it with jquery instead do it in pure JS it is much cleaner and on the end you will know every bit of your code. So that future maintaining of script would be fast and easy.

Categories

Resources