I have an element with an array id id="x[]" that vary depending on the number of elements that I have on a database. It's basically a x button to delete a certain table row in the database.
<div align="center" id="x[]" class="x">
<img src="x 2.png" alt=""></div>
Problem is, I don't know how to pass this id into the jQuery selector. I want to change the form action to delete the row and create an hidden input to get the paramater I need from another field with an array id id="codsinmov[]" with the same index as x[]. What I have so far is:
$(document).ready(function(){
for(var i=0; i<x.length; i++) {
$('#x[i]').click(function(){
var $hiddenInput = $('<input/>',{type:'hidden',id:codsinmovesse, name:codsinmovesse});
$hiddenInput.val($('#codsinmov[i]').val());
$hiddenInput.appendTo('#tabelaeditavel');
$('#form').get(0).setAttribute('action', 'deletemoviment.php');
$('#form').submit();
});
}
});
But it doesn't work.. So, any ideas? Sorry, I'm a beginner at jQuery. Thank you very much!
you can use
$("div[id^='x['").click(function(){
// write code here })
So this will execute on click of those ids of div which start from x.
So as per my understanding You need not to use for loop here rather use 'this' keyword and do what you want.
I hope it will help you.
If you want to add an eventListener to ALL elements you can simply do it like that
var $myButtons = $('.buttons');
That way the whole list of Elements are stored behind the variable $myButtons.
Now you can proceed as following:
$myButtons.on("click", function(event){
console.log(this); // this will print out the clicked element
});
This way every element with the class .buttons is clickable and accessable.
If you want to dynamically select a single element with jquery depending on some value you have to exclude your [i] from the string
for example like that $('element:nth-child('+[i]+')');
Related
I've got an FAQ page I'm building. Next to the question, there is a plus sign to expand the content. On click, I've added the class active, but there are many questions, and I don't want to repeat the same jQuery snippet for each question. I've figured out how to find the parent ID but I'm having trouble storing it in an variable to reuse in the jQuery script.
What I want to be able to do:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$('element .expand').toggleClass('active')
})
Is there a way to do this? I get undefined when I do this:
$('.expand').click(function(){
console.log(element)
});
You can use the find() function to locate children of a selected element:
var element = $(this).parent().parent().attr('id')
$('.expand').click(function(){
$("#" + element).find('.expand').toggleClass('active')
});
However, looking at your code, it seems like you just want to toggle the "active" class of the clicked element. If that is the case, you can do this much more simply without a variable at all:
$('.expand').click(function(){
$(this).toggleClass('active')
});
I currently have about a dozen html buttons on a page, all with a unique value attribute assigned to them.
Firstly, I want to be able to get the values of these buttons and assign them into an array. Here is my code:
var myArray = [];
$("#buttonID").each(function(){
myArray.push($(this).attr("value"));
});
This works, however only takes the value from the first button, and then ignores the rest, despite them all have the same ID. Have I done something wrong with my .each() ?
Once I have solved that, I would like to then modify the above to only add values of those buttons with ".active" classes on them. i.e a user has selected them.
Your selector represents an ID hence the #this why it picks only one because ID's are supposed to be unique, you need to pick them by class name like .className after assigning this class name to all of your buttons
have a loonk at this http://www.w3schools.com/jquery/jquery_ref_selectors.asp
Let's say you decided to use a common class for your buttons instead of an ID. Example:
<button class="my-class".......
There's a wonderful jQuery method that would put the values of all the button's with this class in an array like so:
var myArray = $('.my-class').map(function() {
return this.value;
})
.get();
I'm new to jQuery and am trying to create jQuery UI buttons dynamically and them to a list. I can create one list item but no more are appended after it. What am I doing wrong?
$('#buttonList').append('<li><button>'+ username + '</button>')
.button()
.data('type', userType)
.click(function(e) { alert($(this).data('type')); })
.append('<button>Edit</button></li>');
<div>
<ul id="buttonList">
</ul>
</div>
This only creates one list item with two buttons (although the second button seems to be encased in the first one, but I can probably figure that issue out). How do I get it to create multiple list items with their own unique 'data' values (i.e. I can't do a find() on a particular button class and give it data values as all buttons would then have the same data)?
I suggest to exchange the position of what you are appending and where you are appending to. This way, you retain the appended object, and should be able to work with it as a standard jQuery selector. From your code i commented out the .button() and the .append() lines, because i'm not sure what you want to do with them. Should you need help adding those lines, just drop a comment to my answer ;)
Oh, i almost forgot: i use var i to simulate different contents for username and userType data.
A JSFiddle for you is here: http://jsfiddle.net/cRjh9/1/
Example code (html part):
<div>
<p id="addButton">add button</p>
<ul id="buttonList">
</ul>
</div>
Example code (js part):
var i = 0;
$('#addButton').on('click', function()
{
$('<li><button class="itemButton">'+ 'username' + i + '</button></li>').appendTo('#buttonList')
//.button()
.find('.itemButton')
.data('type', 'userType'+i)
.click(function(e) { alert($(this).data('type'));
})
//.append('<button>Edit</button></li>')
;
i++;
});
You need complete tags when you wrap any html in a method argument. You can't treat the DOM like a text editor and append a start tag, append some more tags and then append the end tag.
Anything insterted into the DOM has to be complete and valid html.
You are also not understanding the context of what is returned from append(). It is not the element(s) within the arguments it is the element collection you are appending to. You are calling button() on the whole <UL>.
I suggest you get a better understanding of jQuery before trying to chain so many methods together
Just a very simplistic approach that you can modify - FIDDLE.
I haven't added the data attributes, nor the click function (I'm not really sure I like the
inline "click" functions - I generally do them in jQuery and try to figure out how to make
the code efficient. Probably not very rational, but I'm often so).
JS
var names = ['Washington', 'Adams', 'Jefferson', 'Lincoln', 'Roosevelt'];
for( r=0; r < names.length; r++ )
{
$('#buttonList').append('<li><button>'+ names[r] + '</button></li>');
}
$('#buttonList').append('<li><button>Edit</button></li>');
So I know that using "a:first" will get the first link of a page. Lets assume we have the following:
<div class="masterclass">
Link 1
Link 2
</div>
<div class="masterclass">
Link 1
Link 2
</div>
Naturally I can use the following code to get the first "a" of the class "masterclass"
$('.masterclass a:first').click(function() {
alert('yayfirstlink');
});
However I do not understand how to get the first link of every "masterclass"
You need to use find() here because your selector will find all the anchor elements with in .masterclass then filter only the very first one. But when you use .find(), it will find all the .masterclass elements first then will find the first anchor element in each of them.
$('.masterclass').find('a:first').click(function() {
alert('yayfirstlink');
});
or if you are sure that the target element will be the first child of its parent then you can use :first-child
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
Try this,
var oFirstAnchor = $(".masterclass a:first-child");
$(".masterclass a:first-child") is what you are looking for.
so:
$('.masterclass a:first-child').click(function() {
alert('yayfirstlink');
});
This is how u loop through each of the masterclass and get the first link of it.
i don't know what you want to do with it though so i can only provide this
$(document).ready(function(){
var fields = $('.masterclass a:first-child');
$.each(fields, function(index, val){
alert(index);
});
});
this alerts the current links array index
http://jsfiddle.net/kBd82/6/
I would recommend using the first of type selector for this.
$('.masterclass a:first-of-type')
This way it will always select the first anchor tag in each masterclass div even if you put other things in the div later.
http://api.jquery.com/first-of-type-selector/
I dont know Javascript at all, so sorry for asking a question like this...
This is what I have:
$(document).ready(function(){$("#more0").click(function(){$("#update0").slideToggle("normal");});});
$(document).ready(function(){$("#more1").click(function(){$("#update1").slideToggle("normal");});});
$(document).ready(function(){$("#more2").click(function(){$("#update2").slideToggle("normal");});});
$(document).ready(function(){$("#more3").click(function(){$("#update3").slideToggle("normal");});});
$(document).ready(function(){$("#more4").click(function(){$("#update4").slideToggle("normal");});});
$(document).ready(function(){$("#more5").click(function(){$("#update5").slideToggle("normal");});});
$(document).ready(function(){$("#more6").click(function(){$("#update6").slideToggle("normal");});});
$(document).ready(function(){$("#more7").click(function(){$("#update7").slideToggle("normal");});});
$(document).ready(function(){$("#more8").click(function(){$("#update8").slideToggle("normal");});});
$(document).ready(function(){$("#more9").click(function(){$("#update9").slideToggle("normal");});});
$(document).ready(function(){$("#more10").click(function(){$("#update10").slideToggle("normal");});});
And So On.. Until #more30 and #update30...
So... Right now, my pages has 30 lines :)
Is there a way to do it less complicated?
Thanks!
Use attribute selector ^= . The [attribute^=value] selector is used to select elements whose attribute value begins with a specified value.
$(document).ready(function(){
$("[id^='more']").click(function(){
$("#update" + $(this).attr('id').slice(4)).slideToggle("normal");
});
});
Try to use attribute starts with selector to select all the elements having id starts with more , then extract the numerical value from it using the regular expression and concatenate it with update to form the required element's id and proceed,
$(document).ready(function(){
$("[id^='more']").click(function(){
var index = $(this).attr('id').match(/\d+/)[0];
$("#update" + index).slideToggle("normal");
});
});
use attribute start with selector
$(document).ready(function(){
$("[id^='more']").click(function(){
$("[id^='update']").slideToggle("normal");
});
});
//select all elements that contain 'more' in their id attribute.
$('[id^=more]').click(function(){
//get the actual full id of the clicked element.
var thisId = $(this).attr("id");
//get the last 2 characters (the number) from the clicked elem id
var elemNo= thisId.substr(thisId.length-2);
//check if last two chars are actually a number
if(parseInt(elemNo))
{
var updateId = "#update"+elemNo;//combine the "#update" id name with number e.g.5
}
else
{
//if not, then take only the last char
elemNo= thisId.substr(thisId.length-1);
var updateId = "#update"+elemNo;
}
//now use the generate id for the slide element and apply toggle.
$(updateId).slideToggle("normal");
});
Well first of all, you could replace the multiple ready event handler registrations with just one, e.g
$(document).ready(
$("#more0").click(function(){$("#update0").slideToggle("normal");});
//...
);
Then, since your buttons/links has pretty much the same functionality, I would recommend merging these into a single click event handler registration as such:
$(document).ready(
$(".generic-js-hook-class").click(function(){
var toggleContainer = $(this).data('toggleContainer');
$(toggleContainer).slideToggle("normal");
});
);
The above solution uses HTML Data Attributes to store information on which element to toggle and requires you to change the corresponding HTML like so:
<div class=".generic-js-hook-class" data-toggle-container="#relatedContainer">Click me</div>
<div id="relatedContainer>Toggle me</div>
I would recommend you to use Custom Data Attributes (data-*). Here You can store which element to toggle in the data attributes which can be fetched and used latter.
JavaScript, In event-handler you can use .data() to fetch those values.
$(document).ready(function () {
$(".more").click(function () {
$($(this).data('slide')).slideToggle("normal");
});
});
HTML
<div class="more" data-slide="#update1">more1</div>
<div class="more" data-slide="#update2">more2</div>
<div id="update1">update1</div>
<div id="update2">update2</div>
DEMO