Why isn't this working If I add spaces to it? - javascript

So I'm making a theme for a blogging platform and I have only template editing access to it(means I cannot control the content coming from the server).I want to remove duplicate I want to remove duplicate images from the blog post page.Here is the code
it is working fine if the alt tag has no spaces
<p>Alt with Spaces.Works fine!</p>
http://jsfiddle.net/mixin/mB7mz/2/
Doens't work if the alt contains spaces
http://jsfiddle.net/mixin/G27fk/
What's the problem here?

chnage single quote of alt property to double
try following
function postHeaderImage(){
headerImage = $('#post-header img').attr('alt');
$('#post-content img').each(function() {
postContentImage = $(this).attr('alt');
if(postContentImage == headerImage){
$("#post-content img[alt='"+ postContentImage+"']").remove();
}
});
}

Your selector points to a different id.
http://jsfiddle.net/G27fk/4/
Try this one:
$('#post-content img').each(function() {

The problem was the way you removed the duplicate images, there is a more elegant way to do so. I updated your JSFiddle to a working example: http://jsfiddle.net/mB7mz/3/
$(document).ready(function(){
function postHeaderImage(){
headerImage = $('#post-header img').attr('alt');
$('#post-content img').each(function() {
postContentImage = $(this).attr('alt');
if(postContentImage == headerImage){
$(this).remove();
}
});
}
postHeaderImage();
});

There are 2 problems.
One the id used in the second code is mismatched
Attribute selector is case sensitive alt & Alt in the value
So
$(document).ready(function () {
function postHeaderImage() {
var headerImage = $('#header-image img').attr('alt');
$('#post-content img[alt="' + headerImage + '"]').remove();
}
postHeaderImage();
});
Demo: Fiddle
If you want case insensitive search then
$(document).ready(function () {
function postHeaderImage() {
var headerImage = $('#header-image img').attr('alt').toLowerCase();
$('#post-content img[alt]').filter(function () {
return $(this).attr('alt').toLowerCase() == headerImage;
}).remove();
}
postHeaderImage();
});
Demo: Fiddle

Related

How do I remove an input field after it's being emptied

I am adding input fields on keystroke, by using an example from the answer for this question. This is my example. I was trying in various ways to remove field if user deletes content from it, so that there are always fields that have some content and one last empty field for adding more, but I just can't find a solution.
This is the code:
$(document.body).on("input", ".external-media-input:last", function () {
var inputID = (parseInt($(this).attr('id')) + 1);
$(".input_fields_wrap").append('<div><input class="external-media-input" id="' + inputID + '" name="external_media[]" type="text"/></div>');
});
You can use on('blur') or .on('focusout')
//...
.on('blur', ".external-media-input:not(:last)", function () {
if(!$(this).val()) $(this).remove();
});
JSFiddle
You can use also on('keyup')
$(document.body).on("keyup", ".external-media-input", function(){
if($(this).val() == '')
$(this).remove();
});
here is your fiddle: https://jsfiddle.net/bembvptx/2/
In your style add one more event:
$(document.body).on("input", ".external-media-input", function () {
if (!$(this).val())
{
$(this).remove();
}
});

If Statements with data attribute - load two different templates based on what product has been clicked

I would like to open two templates based on the data attribute, if brand is SIM then open template1, if Samsung open the other.
Here is my code:
$('.item .show-detail').click(function(){
if($(this).find('[data-brand="SIM"]')) {
var myLink1 = $(this);
alert('hey');
$('.content .row').fadeOut({complete: function(){detailTemplate1('Voice',$(myLink1).parent().data('brand'), $(myLink1).parent().data('model'), $(myLink1).parent().data('subcat')); $('.content .row').fadeIn(400)}});
}else
($(this).find('[data-brand="Samsung"]'))
var myLink = $(this);
alert('link All');
$('.content .row').fadeOut({complete: function(){detailTemplate('Voice',$(myLink).parent().data('brand'), $(myLink).parent().data('model'), $(myLink).parent().data('subcat')); $('.content .row').fadeIn(400)}});
})
You have a lot of problems in your code.
You can't specify a condition for else, you have to say else if
Wrap else if block in figure brackets.
Use length to find if element exists.
This is assuming that data-brands exist inside item element you're clicking on:
$(document).ready(function(){
$('.item').click(function(){
if( $(this).find('[data-brand="SIM"]').length ) {
var myLink1 = $(this);
alert('SIM');
}
else if ( $(this).find('[data-brand="Samsung"]').length ) {
var myLink = $(this);
alert('Samsung');
}
});
});
http://jsfiddle.net/f32epg16/
jquery objects will always be truthy, you need to check the length.
if($(this).find('[data-brand="SIM"]').length)
Second else does not have a clause. You need to either drop it or use else if.
Try this
$(document).ready(function(){
$('.item .show-detail').click(function(){
if($(this).attr("data-brand")=="SIM")
alert("SIM");
else if($(this).attr("data-brand")=="Samsung")
alert("Samsung");
});
});
Use jquery attr method to find its value and do the relevant work

jQuery Toggle not working using this.name

I've created a contact form with validation and was trying to bolt on a help function whereby someone clicks on the question mark and a div with the explanation pops up.
I found a way to do it using a variable and "this" selector which seemed to work fine but it's stopped working and I can't seem to prevent the default # behaviour.
Having looked at similar questions, nothing has indicated what the problem might be. Here is the function:
$(function() {
//show/hide
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
var divname= this.name;
$("#"+divname).toggle();
return false;
});
});
jsFiddle link:http://jsfiddle.net/dvmac/dpVzL/2/
The # selector selects based off of id. If you want to select off of name, you need the attribute slector: '[name="' + divname + '"]'
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
var divname= this.name;
$('[name="' + divname + '"]').toggle();
return false;
});
An even better way is to just to do this: $(this)
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
$(this).toggle();
return false;
});
And if you have dynamically created elements, then you may want to try this:
$(document).on('click', 'a.form-question-help-link', function(e) {
$(this).toggle();
e.preventDefault();
});
use $(this).attr('name') or $(this).prop('name').
Check this fiddle.
should be $(this) instead of this
$(function() {
//show/hide
$('a.form-question-help-link').click(function(event) {
event.preventDefault();
var divname= $(this).name;
$("#"+divname).toggle();
return false;
});
});

create stackoverflow tagging system?

I am trying to create a tagging system just like SO has.
I have added the tags,now I want to remove them.
MyQuestion:
How do I remove the tags appended?
how do I make the cross button(a span) look identical to that in SO tagging system?
SO TAGGING
var tags = [];
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>'+ "");
function remove_tag(){
//what to do here?
}
tags.push(this.value);
this.value = "";
}
});
Here's my JSFiddle: http://jsfiddle.net/Wky2Z/11/
Basically, listen on the .cross to be clicked, and then remove from array and delete element
//enter something in textbox and press enter....
var tags = [];
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>'+ "");
tags.push(this.value);
this.value = "";
}
});
$('body').on('click','.cross',function(){
tags.splice($(this).parent('a').html(), 1);
$(this).parent('a').remove();
});
As for the look of the cross, SO use a CSS Sprite, so you can do the same by making a png or gif or jpeg of the two states, off(grey) and hover(red) and switch the background-position to red with css eg: .cross:hover { background-position:0px -20px }
You can delete elements making use of remove().
Also, i would recommend you to make use of jQuery events instead of using inline events. (if you take a look at the source code of stackoverflow you will notice there are no inline javascript calls)
In this case you would need to add an event handler to the document object as you want to assign the events to elements which are not loaded in the DOM from the start.
$(document).on('click', '.tag span', function(){
$(this).parent().remove();
});
Living example: http://jsfiddle.net/Wky2Z/7/
Update
I updated the example removing the element from the list of tags too:
http://jsfiddle.net/Wky2Z/8/
Added a data-value for the tag links:
$(".target").append("X</span>'+ "");
And modified the click event:
$(document).on('click', '.tag span', function(){
$(this).parent().remove();
var removeItem = $(this).parent().data('value');
tags = $.grep(tags, function(value) {
return value != removeItem;
});
});
For a full jQuery solution you can remove the inline remove_tag function and use jQuery on function. it works for dynamically created elements too.
Attach an event handler function for one or more events to the
selected elements.
Here you can get the parent element of the deleted element and remove it from the DOM using remove.
To "sync" the array with the current situation you can use grep to delete the item from the array; note the removedItem variable used to get the text only of the parent excluding the children from the text.
Code:
//enter something in textbox and press enter....
var tags = [];
$(document).ready(function () {
$('body').on('click', 'span.cross', function () {
var removedItem = $(this).parent().contents(':not(span)').text();
$(this).parent().remove();
tags = $.grep(tags, function (value) {
return value != removedItem;
});
});
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>' + "");
tags.push(this.value);
this.value = "";
}
});
});
Demo: http://jsfiddle.net/IrvinDominin/pDFnG/
Here's the updated link: http://jsfiddle.net/Wky2Z/6/
Move remove_tag outside of keypress event handle and pass a this pointer to it for quick solution:
//enter something in textbox and press enter....
var tags = [];
function remove_tag(x) {
$(x).parent('a').remove();
}
$(function () {
$("#textBox").keypress(function (e) {
if (e.which === 13) {
$(".target").append("X</span>' + "");
tags.push(this.value);
this.value = "";
}
});
});

How can I update a input using a div click event

I've got the following code in my web page, where I need to click on the input field and add values using the number pad provided! I use a script to clear the default values from the input when the focus comes to it, but I'm unable to add the values by clicking on the number pad since when I click on an element the focus comes from the input to the clicked number element. How can I resolve this issue. I tried the following code, but it doesn't show the number in the input.
var lastFocus;
$("#test").click(function(e) {
// do whatever you want here
e.preventDefault();
e.stopPropagation();
$("#results").append(e.html());
if (lastFocus) {
$("#results").append("setting focus back<br>");
setTimeout(function() {lastFocus.focus()}, 1);
}
return(false);
});
$("textarea").blur(function() {
lastFocus = this;
$("#results").append("textarea lost focus<br>");
});
Thank you.
The first thing I notice is your selector for the number buttons is wrong
$('num-button').click(function(e){
Your buttons have a class of num-button so you need a dot before the class name in the selector:
$('.num-button').click(function(e){
Secondly, your fiddle was never setting lastFocus so be sure to add this:
$('input').focus(function() {
lastFocus = this;
...
Thirdly, you add/remove the watermark when entering the field, but ot when trying to add numbers to it (that would result in "Watermark-text123" if you clicked 1, then 2 then 3).
So, encalpsulate your functionality in a function:
function addOrRemoveWatermark(elem)
{
if($(elem).val() == $(elem).data('default_val') || !$(elem).data('default_val')) {
$(elem).data('default_val', $(elem).val());
$(elem).val('');
}
}
And call that both when entering the cell, and when clicking the numbers:
$('input').focus(function() {
lastFocus = this;
addOrRemoveWatermark(this);
});
and:
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
addOrRemoveWatermark(lastFocus);
$(lastFocus).val($(lastFocus).val() + $(this).children('span').html());
});
You'll see another change above - you dont want to use append when appends an element, you want to just concatenate the string with the value of the button clicked.
Here's a working branch of your code: http://jsfiddle.net/Zrhze/
This should work:
var default_val = '';
$('input').focus(function() {
lastFocus = $(this);
if($(this).val() == $(this).data('default_val') || !$(this).data('default_val')) {
$(this).data('default_val', $(this).val());
$(this).val('');
}
});
$('input').blur(function() {
if ($(this).val() == '') $(this).val($(this).data('default_val'));
});
var lastFocus;
$('.num-button').click(function(e){
e.preventDefault();
e.stopPropagation();
var text = $(e.target).text();
if (!isNaN(parseInt(text))) {
lastFocus.val(lastFocus.val() + text);
}
});
Live demo
Add the following function:
$('.num-button').live( 'click', 'span', function() {
$currObj.focus();
$currObj.val( $currObj.val() + $(this).text().trim() );
});
Also, add the following variable to global scope:
$currObj = '';
Here is the working link: http://jsfiddle.net/pN3eT/7/
EDIT
Based on comment, you wouldn't be needing the var lastFocus and subsequent code.
The updated fiddle lies here http://jsfiddle.net/pN3eT/28/

Categories

Resources