I am trying to make the following:
On click of each image (thumbnail) source should be writen into specified input.
I have done that sort of... Not working quite fine just yet!
It doesn't add correct source, just first source all the time, no matter what image is clicked.
It doesn't remove added source if clicked again on same/different image.
// Piece of jQuery script:
var imgSource = $('#textures li').find('img').attr('src');
$('ul#textures li img').on('click', function() {
$('input#imgPath').val($('input#imgPath').val() + imgSource);
});
Fiddle for better understanding:
JS Fiddle link
P.S. Explanation of your answer will be appreciated!
attr only returns a attribute of the first matched element, you can use this keyword which refers to the clicked element.
$('ul#textures li img').on('click', function() {
$('#imgPath').val(this.src)
});
http://jsfiddle.net/Uz6rc/
use: $(this) - that mean the attribute of the click element
$('ul#textures li img').on('click', function() {
$('input#imgPath').val($('input#imgPath').val() + $(this).attr('src'));
});
Take a look: http://jsfiddle.net/e3HzQ/
From the jQuery docs:
The .attr() method gets the attribute value for only the first element
in the matched set.
Your imgSource variable is declared outside of the event handler, so it doesn't vary its value according to the clicked image - it just maintains the value from the first image.
Also, the previous value isn't removed because you are appending the value to what is already there.
Here you go:
$('ul#textures li img').on('click', function() {
var imgSource = $('#textures li').find('img').attr('src');
$('input#imgPath').val($(this).attr("src"));
});
DEMO
The reason it was not working for you is because you have defined
var imgSource = $('#textures li').find('img').attr('src');
outside of on function. And then further you were everytime setting the same value inside the text box using:
$('input#imgPath').val($('input#imgPath').val() + imgSource);
I modified this line to get the img src by using this operator.
Related
I'm trying to apply a border to a dynamically generated element using $.on('click') and $.addClass(), but the class doesn't seem to be applied on the first click event. Otherwise, it works fine. What am I doing wrong?
$(document.body).on('click', '.card', function() {
var currentSelection = $(this)
var currentSelectionIndex = $(currentSelection).index()
$(currentSelection).addClass("selected")
if (currentSelectionIndex !== previousSelectionIndex) {
p = $("#searchResponse").children().get(previousSelectionIndex)
$(p).removeClass("selected")
}
previousSelectionIndex = currentSelectionIndex;
});
Solution: Assigning previousSelectionIndex a value a the beginning of my script and it fixed the issue.
I'm not entirely clear on your question given the information provided.
However, if I understand the problem correctly you have a container element with the id="searchResponse" that has many children each with the class="card" and you're essentially trying to add class="selected" to a particular card when it is clicked ensuring that only one card at a time can be 'selected'. If this is the case..
Select only one card at a time:
$('#searchResponse').on('click', '.card', function(){
$('.card.selected').removeClass('selected');
$(this).toggleClass('selected');
});
If you need to select and unselect multiple then try this:
$('#searchResponse').on('click', '.card', function(){
$(this).toggleClass('selected';)
});
Working Codepen
I want to use jQuery to add an image that is on a div to another div, but when I do it the image disappears from the original div. I would like the image to be copied and not moved. Here is the current code.
$( ".rectangle" ).click(function() {
$('.bigRectangle').css('display','block');
$(".notBig").css('opacity',0.2);
var x = $(this).find('img');
$('.bigRectangle').append(x);
});
This is because a DOM node can only have one parent. Appending it to another element will move it to being a child of the other element. Use the .clone method to clone the img element before appending it.
$('.bigRectangle').append(x.clone());
All you would need to do is perform this:
var x = $(this).find('img').clone();
I would recommend you check out the function clone "https://api.jquery.com/clone/"
In your code you are essentially moving the image, when you assign the image in the variable "x" it holds the dom element in that variable. It is a reference. Matter of fact you are holding all images in the document.
Hope this helps, please let me know.
Mr Alexander
Below is my code..
var content = $("XXXX");
content.find("a").each(function() {
var value = $(this).attr('href');
$(this).attr('href', encodeURI(value));
alert(value);
});
However, it keep showing error.
How can I make this code work which I want to encode the url.
Instead of content.find('a') use content.filter('a'). Because right now you're content is an array of only one element (ie. <a>), so there is no more <a> within that <a> and .find('a') fails here.
So .filter() is safe to use.
Demo
No need to use JQuery.find here as content variable has only anchor tag and you want to apply encodeURI for your URL.
For that requirement below code is well enough.
$(content).each(function(){
var value = $(this).attr('href');
$(this).attr('href', encodeURI(value));
alert($(this).attr('href'));
}
);
Hope it helps you.
maybe you should add an ID (if you want to use this for more than one element then create a specific class for the elements and link via $(".classname")) to your link and then use a normal query like this
var yourLink = $("#yourID");
yourLink.attr('href', encodeURI(value));
and make sure that your value has something in it. Also if .attr(...) has still no effect please try .prop("href", encodeURI(value))
I'm building a recipe saving application where I have a form that looks like this http://jsfiddle.net/LHPbh/.
As you can see, I have a set of form elements contained in an <li>. You can click Add Ingredient and have more li's added to the field.
My problem is:
The first li is the only one that deletes. If you click Add Ingredient, and then try and delete that one, nothing works?
Is there a way to not have the first li have a delete by it, but all subsequent li's have a delete link on the side? (Just because there should always be at least one ingredient?)
When you call clone(), it isn't duplicating the events. You need to call clone(true) in order for it to do this, as explained in the documentation.
You did not put an event listener on the cloned elements. Also, you should not give the "delete"-link its own id, as those need to be unique.
To make the first ingredient have no delete button, just don't include one in your markup but only dynamically create and append them to the cloned elements:
var deleteButton = $("<a class='float-left'>Delete</a>").click(deleteThis);
$('ul#listadd > li:first')
.clone()
.attr('name', 'ingredient' + newNum)
.append(deleteButton)
.appendTo('ul#listadd');
function deleteThis() {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
}
Demo at jsfiddle.net
http://jsfiddle.net/LHPbh/2/
$('.deleteThis').live("click", function () {
var li = $(this).closest('li')
li.fadeOut('slow', function() { li.remove(); });
});
It is answer to the 1. point. The problem was, that the eventhandler binding did not happen in newly created elements, because this code runs only on the load of the page. This can be solved by using .live(). And an other problem was, that id-s must be unique. So instead id, here you can use class .deleteThis.
http://jsfiddle.net/LHPbh/19/
This has added answer to the 2. point:
if ($("#listadd li").length == 1) {
return;
}
If the list only contains 1 li element the rest of the callback will not run.
You are adding items that are added to the DOM dynamically, thus jQuery can't access them :)
In this case you can use the following code:
$(document).on('click', '.selector', function(e) {
//code here
});
Secondly, you were loading a quite old version of jQuery.
Thirdly, you were trying to select an element with an ID that already existed, and ID's can only exist one time. I've changed it to a class in the updated example.
Lastly, you were defining the class of the link twice like this:
<a class='float-left' id="deletethis" href='#' class="deletethis">Delete</a>
That also gave a problem, so I changed it to correct markup like this:
<a class='float-left deletethis' href='#'>Delete</a>
Good luck :) I've updated your jsFiddle here:
http://jsfiddle.net/q4pf6/
I'm new to javascript and JQuery, and I'm working in a small project with JSP.
I create a grid dynamically with JSP and I added some buttons wich class is "select" and in the alt attribute I set the current row index. That works perfectly, I'm trying to set the onclick dynamically. This is my code
$('.select').click(function (){
alert($('.select').attr('alt'));
}
I want to each button to show its own index, but that code shows just the first index in each button. I've searched how to do it, but nothing comes out.
Is there a chance to do what I want?
change this line as:
alert($(this).attr('alt'));
When jQuery calls your event handler it sets this to be the DOM element in question, so try this:
$('.select').click(function (){
alert($(this).attr('alt'));
});
If you need to access DOM element properties you can then get them directly, e.g.:
alert( this.id );
this.value = "test";
If you need to use jQuery methods on the element you need to pass it to the jQuery function first, e.g.:
$(this).hide();
$(this).css("color","red").slideDown();
$('.select').click(function (){
alert($(this).attr('alt'));
});
Change
alert($('.select').attr('alt'));
by
alert($(this).attr('alt'));
Now you select the attr alt of the button lauch the event.
Not sure if that's what you're looking for but...
$('.select').click(function() {
$('.select').each(function() {
$(this).attr('value', $(this).attr('alt'));
});
});
This'll have every button "show" the value stored within their alt attribute when you click one button.
By the way, if you're using 1 button per row, you'd probably better go with index().