Failed to append image along with text in asp.net - javascript

This is my code I want to append image along with my text
Code:
$(".ChatSend").click(function () {
strChatText = $('.ChatText', $(this).parent()).val();
var recievertext= $('.ausername').html();
if (strChatText != '') {
var strGroupName = $(this).parent().attr('groupname');
if (typeof strGroupName !== 'undefined' && strGroupName !== false)
chat.server.send($("#hdnUserName").val() + ' : ' + strChatText, $(this).parent().attr('groupname'));
//this code is not working
**var userphoto="<img height=\"18px\" width=\"18px\" src=\"userimages/5.jpg\" />";
$('.ChatText', $(this).parent()).find('ul').append(userphoto + strChatText);**
//end of this code is not working
$('.ChatText', $(this).parent()).val('');
}
return false;
});

How about putting the content in an li since you're appending to a ul
$('.ChatText', $(this).parent()).find('ul').append('<li>'+userphoto + strChatText+'</li>');

Related

document.elementFromPoint not precise

I defined a function in JS:
function getElementIDAtPoint(x,y) {
console.log("Touch Down ("+x+", "+y+")");
var id = '';
var element = document.elementFromPoint(x,y)
while(!element.id && element.tagName != 'BODY'){
element = element.parentElement;
alert('tagname: ' + element.tagName + ' id: ' + element.id)
}
return id;
}
Sometimes i don't get an id, even though the element i clicked on has an id. The elements are small and maybe that's causing the issue. How can i make this more precise? i'm not a js expert

Checking a div for duplicates before appending to the list using jQuery

This should be trivial but I'm having issues...
Basically what I am trying to do is append a new "div" to "selected-courses" when a user clicks on a "course". This should happen if and only if the current course is not already in the "selected-courses" box.
The problem I'm running into is that nothing is appended to the "selected-courses" section when this is executed. I have used alert statements to make sure the code is in fact being run. Is there something wrong with my understanding of the way .on and .each work ? can I use them this way.
Here is a fiddle http://jsfiddle.net/jq9dth4j/
$(document).on("click", "div.course", function() {
var title = $( this ).find("span").text();
var match_found = 0;
//if length 0 nothing in list, no need to check for a match
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (matched == 0) {
var out = '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
});
//checks to see if clicked course is already in list before adding.
function match(str) {
$(".selected-course").each(function() {
var retval = 0;
if(str == this.text()) {
//course already in selected-course section
retval = 1;
return false;
}
});
return retval;
}
There was a couple of little issues in your fiddle.
See fixed fiddle: http://jsfiddle.net/jq9dth4j/1/
function match(str) {
var retval = 0;
$(".selected-course").each(function() {
if(str == $(this).text()) {
retval = 1;
return false;
}
});
return retval;
}
You hadn't wrapped your this in a jquery object. So it threw an exception saying this had no method text().
Second your retval was declared inside the each so it wasn't available to return outside the each, wrong scope.
Lastly the if in the block:
if (matched== 0) {
var out = '';
out += '<div class="selected-course">' + '' + title + ''+'</div>';
$("#selected-box").append(out);
}
was looking at the wrong variable it was looking at matched which didn't exist causing an exception.
Relying on checking what text elements contain is not the best approach to solve this kind of question. It is prone to errors (as you have found out), it can be slow, it gives you long code and it is sensitive to small changes in the HTML. I would recommend using custom data-* attributes instead.
So you would get HTML like this:
<div class="course" data-course="Kite Flying 101">
<a href="#">
<span>Kite Flying 101</span>
</a>
</div>
Then the JS would be simple like this:
$(document).on('click', 'div.course', function() {
// Get the name of the course that was clicked from the attribute.
var title = $(this).attr('data-course');
// Create a selector that selects everything with class selected-course and the right data-course attribute.
var selector = '.selected-course[data-course="' + title + '"]';
if($(selector).length == 0) {
// If the selector didn't return anything, append the div.
// Do note that we need to add the data-course attribute here.
var out = '<div class="selected-course" data-course="' + title + '">' + title + '</div>';
$('#selected-box').append(out);
}
});
Beware of case sensitivity in course names, though!
Here is a working fiddle.
Try this code, read comment for where the changes are :
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text().trim(); // use trim to remove first and end whitespace
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) { // should change into match_found
var out = '';
out += '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0; // this variable should place in here
$(".selected-course").each(function () {
if (str == $(this).find('a').text().trim()) { // find a tag to catch values, and use $(this) instead of this
retval = 1;
return false;
}
});
return retval; // now can return variable, before will return undefined
}
Updated DEMO
Your Issues are :
1.this.text() is not valid. you have to use $(this).text().
2.you defined var retval = 0; inside each statement and trying to return it outside each statement. so move this line out of the each statement.
3.matched is not defined . it should be match_found in line if (matched == 0) {.
4. use trim() to get and set text, because text may contain leading and trailing spaces.
Your updated JS is
$(document).on("click", "div.course", function () {
var title = $(this).find("span").text();
var match_found = 0;
if ($(".selected-course").length > 0) {
match_found = match(title);
}
if (match_found == 0) {
var out = '<div class="selected-course">' + '' + title + '' + '</div>';
$("#selected-box").append(out);
}
});
function match(str) {
var retval = 0;
$(".selected-course").each(function () {
if (str.trim() == $(this).text().trim()) {
retval = 1;
return false;
}
});
return retval;
}
Updated you Fiddle

If list item exists do not append but change the fontcolor

I have this script that appends a list item if it's not allready there.
What i want it to do also is that if the list item does allready exist that it's font color(css)is set to another color.
var itemName = userName,
userFound = false;
$('#msgUserlist li').each(function () {
if ($(this).text() === itemName) {
userFound = true;
}
});
if (userFound === true) {
////// at this point i want the fontcolor of the allready existing item be set.///
return;
} else
var newNode = document.createElement('li');
newNode.innerHTML = '<a id="switchtoUser" name="' + userName + '" ' + 'onclick="ajaxChat.getHistory' + '(\'' + userName + '\')"' + ' href="javascript:ajaxChat.sendPrivateMessageWrapper(\'/query ' + userName + '\');">' + userName + '</a>';
document.getElementById('msgUserlist').appendChild(newNode);
},
You can do it while looping through the list when you're searching for the user:
// ...snip
$('#msgUserlist li').each(function () {
if ($(this).text() === itemName) {
userFound = true;
$(this).css({
color: "blue" // or whatever
});
return;
}
});
// ...snip
Why don't you do the moment you find it?
if ($(this).text() === itemName) {
userFound = true;
$(this).css('color', 'red'); // Example: change the color to red
}
I think this would be nicely solved by the Jquery function css()
HTML
<ul id=msgUserlist>
<li>Foo</li>
<li>userName</li>
<li>tball rulez</li>
</ul>
Javascript
var itemName = 'userName';
$( document ).ready(function() {
$("#msgUserlist li").each(function() {
if($(this).text() == itemName )
$(this).css("color", "red");
})
})
See working example (simple, but can be expanded with the logic you outlined in your question!): http://jsfiddle.net/PGfgv/601/

How can I change to a default background image

I use the following function to create dynamic elements using an ajax response.
function itemGroupSelection(elem,majorGroupId,itemGroupId){
var itemGroup;
var majorGroup;
if(elem == undefined || elem == null || elem == ""){
var itemGroup = itemGroupId;
var majorGroup = majorGroupId;
}else if(majorGroupId == null && itemGroupId == null){
var itemGroup = elem.attr("id");
var majorGroup = elem.attr("majorgroup");
}
$('.breadcrumb a').removeClass('active');
if(elem == ""){
$('.breadcrumb a').first().addClass('active');
}else{
elem.addClass('active');
}
var selectedOutlet = $('#outlets select').children(":selected").attr("id");
$('.item').show();
$('.breadcrumb').show('1');
var data = "majorGroupId=" + majorGroup + "&itemGroupId=" + itemGroup + "&outletCode=" + selectedOutlet;
if(selectedOutlet == undefined){
getSystemMessage('Please select an outlet.');
}else{
ajaxCall("/getItems","POST",data,function(result){
var element = $('#model-item').find('.item').first();
$('#item-list-section').empty();
for(var i = 0; i < result.items.length; i++){
var clone = element.clone();
clone.attr("id", result.items[i].itemId);
clone.find('.item-price').html("<h4>" + result.items[i].rate.toFixed(2) + "</h4>");
if(result.items[i].itemName.length >= 20){
clone.find('.item-name').css('overflow','hidden');
clone.attr('title', result.items[i].itemName )
}
clone.find('.item-name').html("<h4>"+ result.items[i].itemName + "</h4>");
clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg');
clone.draggable({
revert : false,
zIndex: 1,
containment: "window",
opacity: 0.5,
cursor: "move",
helper: function() { return $(this).clone().appendTo('body').show(); }
});
$('#item-list-section').append(clone);
}
});
}
}
Using the following command I try to select the background image in the local disc.
clone.css('background-image','c:/zharaimages/' + result.items[i].itemId + '/image.jpg');
How can i switch to a default image if there is no image in the path defined. I'm using jQuery 1.9.
Try using the onerror attribute of img, if the link given in src attribute fails to load, ur function in error is called and u can set your default image there (w3schools.com/jsref/event_img_onerror.asp)
You need to handle the onerror event of this image, which will occur whenever the file cannot be found:
$('#image').error(function(){
$(this).off('error'); // otherwise, inexistence of the default image is a real pain
$(this).attr('src', 'http://www.google.ca/images/srpr/logo4w.png');
});
Take a look at this working FIDDLE.
Then,
in your situation, you could have something like this:
var path='the path';
clone.css('background-image', 'url('+path+')');
$('<img src="'+path+'" />').error(function(){
$(this).off('error');
clone.css('background-image', 'url('+default_path+')');
});
Hope this helps :-)

Text area validation in javascript for html image tag

I want to validate a text area for img tag when it is duplicated. example, if i entered the image tag with src i should enter the same source with tag again i need to show alert how it could be done. my snippet to check whether the image is there or not. but i need to do for above validation also...
function validateEditor() {
var editor_val = $('#asset_html').val(), iSrc;
// Check for empty string
if(!string_IsEmpty(editor_val)) {
// Check whether img is available
if(editor_val.match(/img/g)) {
var src_cnt = (editor_val.match(/img/g).length);
//console.log(editor_val.match(/src/g).length);
$('#asset_html_preview').html(editor_val);
for(var j = 1; j <= src_cnt; j++) {
if($('#asset_html_preview img:nth-child(1)').attr('src')) {
iSrc = $('#asset_html_preview img:nth-child(1)').attr('src');
if(iSrc.indexOf('http://') != -1) {
$('#asset_html_preview img:nth-child(' + j + ')')
.error(function() { alert('Check ur image src'); });
//break;
}
}
}
}
}
}
You may be looking for this:
var arr = {};
var $div = $('<div />').html($('textarea').val());
$div.find('img').each(function (i) {
var src = $(this).attr('src');
if (src.indexOf('http://') >= 0 && arr[src] == undefined) {
arr[src] = 'foobar';
} else if (arr[src] !== undefined) {
alert('This url `' + src + '` already exists');
} else {
alert('This url `' + src + '` is wrong');
}
});
Demo: http://jsfiddle.net/LXgWU/3/
Assuming that your var src_cnt work perfect.
var src_cnt = (editor_val.match(/img/g).length);
if(src_cnt == 1)
{
alert("Plz choose Unique Image");
return false;
}

Categories