iterate and replace span at the same time - javascript

Say I have the following code that iterates over the <span> inside the <div>:
$('#recommendTextArea').children('span').each(function () {
//mentionedFriends.push($(this).html());
var mentionedFriendName = $(this).html();
jQuery.each(friendsList, function () {
if (this.name == mentionedFriendName) {
var facebookId = '#[' + this.id + ']';
}
});
});
I essentially wanted to replace this <span> with the string of facebookId. Is such thing possible? If yes how?

Use replaceWith.
$('#recommendTextArea').children('span').each(function () {
var $span = $(this);
//mentionedFriends.push($(this).html());
var mentionedFriendName = $(this).html();
jQuery.each(friendsList, function () {
if (this.name == mentionedFriendName) {
var facebookId = '#[' + this.id + ']';
$span.replaceWith(facebookId);
}
});
});
EDIT: If you need to deal with special characters, etc. You can do this instead:
$span.replaceWith($("<div>").text(facebookId).contents());

Related

Evaluation problems with Jasmine JavaScript testing framework

I'm experiencing problems with the Jasmine (ver. 2.4) JavaScript testing framework.
I'm creating a course on udemy.com, but the online checker won't accept the last part of my code, where I'm using the "expect(variable).toBe(true);" function of Jasmine.
describe('A div with class', function() {
var parent = document.getElementsByClassName('media')[0];
it('"media" should exist.', function() {
expect(parent).toBeDefined();
});
var child = document.getElementsByClassName('media-body')[0];
it('"media-body" should exist.', function() {
expect(child).toBeDefined();
});
});
describe('A div with class "media"', function() {
var parent = document.getElementsByClassName('media')[0];
var child = document.getElementsByClassName('media-body')[0];
var answer;
if (parent.firstChild == child) {
answer = true;
} else {
answer = false;
}
it('should have a div with class "media-body" as its child.', function() {
expect(answer).toBe(true);
});
});
My test output from the udemy.com page is:
"A div with class "media" should have a div with class "media-body" as its child.
Expected false to be true"
My updated code which now works very well:
describe('A div with the class', function() {
var class1 = 'media';
var failClass1 = '"' + class1 + '"' + ' should exist.'
var class2 = 'media-body';
var failClass2 = '"' + class2 + '"' + ' should exist.'
var element1 = null;
var element2 = null;
var relationship1_2 = null;
var failRelationship = '"' + class2 + '"' + ' should be nested in a div with the class "' + class1 + '".'
beforeEach(function() {
element1 = document.getElementsByClassName(class1)[0];
element2 = document.getElementsByClassName(class2)[0];
relationship1_2 = element1.contains(element2);
})
it(failClass1, function() {
expect(element1).toBeDefined();
});
it(failClass2, function() {
expect(element2).toBeDefined();
});
it(failRelationship, function() {
expect(relationship1_2).toBe(true);
});
});
I'd recommend re-organize it using beforeEach blocks as the following example:
describe('testing media tag hierarchy', function() {
var parent = null;
beforeEach(function() {
parent = document.getElementsByClassName('media')[0];
})
it('"media" should exist.', function() {
expect(parent).toBeDefined();
});
it('should have a div with class "media-body" as its child.', function() {
expect(parent.firstChild.hasClass('media-body')).toBeTruthy();
});
});
I'm not sure this will fix your problem but it might... it's easier to read.

jQuery filter select options by text input

I have a select list where I want to filter the options from a text input.
I wrote this jQuery code:
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
if (e.text().indexOf(filterText) != -1) {
e.show();
console.log("show");
} else {
e.hide();
console.log("hide");
}
});
});
However I get the error Uncaught TypeError: e.text is not a function. I get into the each loop so there should be some option for e.
What am I doing wrong?
You must use the current value in a jQuery object to have access to the .text() method. Try:
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
if ($(this).text().indexOf(filterText) != -1) {
$(this).show();
console.log("show");
} else {
$(this).hide();
console.log("hide");
}
});
});
Try to change your selector within loop :-
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
if ($(e).text().indexOf(filterText) != -1) {
$(e).show();
console.log("show");
} else {
$(e).hide();
console.log("hide");
}
});
});
It may help you.
You need object variable, but accessing event variable. So please use this one
$('#NotPublishedSelectFilter').keyup(function () {
console.log("NotPublishedSelectFilter keyup");
var filterText = $(this).val();
console.log("filterText: " + filterText);
var allOptions = $('#NotPublishedSelect').find('option');
allOptions.each(function (i, e) {
console.log(i);
$(this).text()
if ($(this).text().indexOf(filterText) != -1) {
$(this).show();
console.log("show");
} else {
$(this).hide();
console.log("hide");
}
});
});

How can I get an element with a string regardless if it corresponds to its class or its ID?

Let us consider this function:
function validateField(selector) {
$(selector).on("change, blur", function() {
// do stuff
});
}
That element could have an id=selector or a class=selector. How can I proceed with such abstraction?
You could simply refer to both by doing something like this:
function validateField(selector) {
var $selector = $('#'+selector+', .'+selector); // This will reference every class and id with the selector's name
$selector.on("change, blur", function() {
// do stuff
});
}
You might wanna try something like this, try to see if it's ID first, if it returns 0 as length, try class. But this isn't an good way to do it, maybe you can also try with a flag
function validateField(selector) {
var $selector = $('#' + selector);
if ($selector.length === 0) {
$selector = $('.' + selector)
}
$selector.on("change, blur", function() {
// do stuff
});
}
With an flag
function validateField(selector, classSelect) {
var $selector;
if (classSelect === true) {
$selector = $('.' + selector)
} else {
$selector = $('#' + selector)
}
$selector.on("change, blur", function() {
// do stuff
});
}
This function will accommodate both ID and class selectors:
function validateField(selector, Type) {
var SelectorString = "";
if (Type == "ID")
SelectorString = "#" + selector;
else if (Type == "Class")
SelectorString = "." + selector;
else
return; // invalid so don't create event handler.
$(SelectorString).on("change, blur", function() {
// do stuff
});
}

Remove item from array and html list using jquery

I have a javascript array called names[] which stores names. (ofcourse)
The names are also stored in list items in my html document, I have this code that removes a name when you click on it;
$(document).ready(function(){
$(document).on('click', 'li', function(){
$(this).remove();
});
});
Can anyone tell me how I remove the same item from the array names[]?
UPDATE: names[] is defined as follows:
function submit() {
var theName = document.getElementById("enter").value;
if (theName == "" || theName.length == 0) {
return false;
}
names.push(theName);
document.getElementById("name").children[0].innerHTML += "<li>" + names[names.length - 1] + "</li>";
document.getElementById("enter").value = "";
}
This is done with an <input>.
Array.prototype.remove = function(item) {
var index = this.indexOf(item);
if (index > -1) {
this.splice(index, 1);
return true;
}
return false;
};
$(document).ready(function(){
$(document).on('click', 'li', function(){
var text = $(this).text();
names.remove(text);
$(this).remove();
});
});

How to change onclick event to on mouseover

I am new to javascript I have a doubt in changing onclick event to mouseover please help
<script>
$(document).ready(function() {
(function ($) {
$.fn.readmore = function (settings) {
var opts = $.extend({}, $.fn.readmore.defaults, settings);
this.each(function () {
$(this).data("opts", opts);
if ($(this).html().length > opts.substr_len) {
abridge($(this));
linkage($(this));
}
});
function linkage(elem) {
elem.append(elem.data("opts").more_link);
elem.children(".more").click( function () {
$(this).hide();
$(this).siblings("span:not(.hidden)").hide().siblings("span.hidden").animate({'opacity' : 'toggle'},1000);
});
}
function abridge(elem) {
var opts = elem.data("opts");
var txt = elem.html();
var len = opts.substr_len;
var dots = "<span>" + opts.ellipses + "</span>";
var charAtLen = txt.substr(len, 1);
while (len < txt.length && !/\s/.test(charAtLen)) {
len++;
charAtLen = txt.substr(len, 1);
}
var shown = txt.substring(0, len) + dots;
var hidden = '<span class="hidden" style="display:none;">' + txt.substring(len, txt.length) + '</span>';
elem.html(shown + hidden);
}
return this;
};
$.fn.readmore.defaults = {
substr_len: 500,
ellipses: '…',
more_link: '<a class="more">Read More</a>'
};
})(jQuery);
$(function(){
$('.des_details').readmore({ substr_len: 150 });
});
});
</script>
Any suggestions?
There's a bit of API doc about .hover() which explains what I think you're trying to do. Hope this helps.
http://api.jquery.com/hover/
where you have
elem.children(".more").click( function ()
replace it with
elem.children(".more").hover( function ()
Try this code
$(urid).trigger('mouseover');

Categories