INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

$("#button[i]").click(function(){, could work?

$("#button[i]").click(function(){, could work?

(OP)
Hello,

I would like to know, please, if there is any reason why the following is not working (using the jQuery click function):

CODE --> javascript

var i;

for(i=0; i<6;i++){

$("#button[i]").click(function(){
....
});
}; 
I am using a jquery API to make a post connection to a file in a third server (via the URL). I get the response (by details.response), which works fine, no problem at all with it.
The response (coming form an PHP script, in a third server, as i said) looks like:

CODE --> html

<button id="button[1]"></button><br>
<button id="button[2]"></button><br>
.... 
So, when I get the response this is shown on an html file, by doing something like this (over a div element with ID=divwithbuttons):

CODE --> javascript

$("#divwithbuttons").html(details.response); 

This part works fine, no problem. The problem is with the click function meant to work on the button elements given (and shown), due to their particular ID's (with []);
I know it is because of the [], because tested without them it works fine.
This sort of use of ID's seems to work on Javascript, for instance on an onclick event (passed as a parameter), or on the document.getElementByID, etc...but, why not on a jQuery click function?? (I could try using the onclick event as well, to do what I want to do,but for some reason related to the application I am working on, is not working. It works without the application though).

Is there any reason for that or any way to fix it?? (I have tried different ways but with no avail).
I can provide with more details if it helps.
Thanks a lot in advance!

enjoy practicing languages at: www.sharinglanguage.com

RE: $("#button[i]").click(function(){, could work?

it might be possible that this will work. but sfaik the ID attribute CANNOT contain square brackets (http://www.w3.org/TR/html4/types.html#type-name).

I know that we ignore this for the name attribute.

two solutions.

1. learn how to escape strings in javascript. most browsers will allow you to find square brackets with use of appropriate escaping.

2. use an alternative selector. easiest would be to apply a class but something like this might also work

CODE

$('button[id^="button["]').on('click',function(e){
  //e is the event.
  //$(this) is the jQuery object containing the clicked button
}); 

it is also possible that simply by correcting the syntax error some browsers will be ok

CODE

for( var i=0; i<6;i++){
  $("#button[" + i + "]").on('click',function(){
    ....
  });
}; 

RE: $("#button[i]").click(function(){, could work?

for readers, generally - in HTML5 the id attribute can now contain any character other than a space.

RE: $("#button[i]").click(function(){, could work?

(OP)
Hi,

Thank you very much for your reply and all the information.
I have to say that I had written the first script wrongly. Actually i had written it like you did:

CODE --> jquery

for( var i=0; i<6;i++){
  $("#button[" + i + "]").click (function(){
    ....
  });
}; 
I have changed something, following the line of your first example:

CODE --> jquery

for(var i=0;i<6;i++){
$("[id='button["+i+"]']").click(function(){
.... 
and it works (on any html element shown, as expected).
However, what i thought it wouldn't be a problem, now it is.
If I have another element (for instance <span>, besides <button>, which is the one I want to make use of on clicking), with another ID, I can not get its value this way:

CODE --> html

<span id='aceptamos[0]'>eeeeee</span>
<button id='button[0]'>send</button><br>
<span id='aceptamos[1]'>uuuuu</span>
<button id='button[1]'>send</button><br>
... 

CODE --> jquery

for(var i=0;i<6;i++){
$("[id='button["+i+"]']").click(function(){

var span=document.getElementById("aceptamos["+i+"]").innerHTML;
... 

when I write:

CODE --> javascript

alert(span); 

afterwards, I get nothing.

I have also tried following the button example and it doesn't work either:

CODE --> jquery

var span=document.getElementById("[id='aceptamos["+i+"]']").innerHTML; 

I also tried using class instead of id, but it is not working.
So, I get the click function to work but still I have some problems with the brackets, now on the getElementbyID method.

I tried escaping the brackets but it didnt work (maybe i haven't done it properly).

Any idea, please?

p.s I didn't follow you first example exactly, since I couldn't fully figure it out.

enjoy practicing languages at: www.sharinglanguage.com

RE: $("#button[i]").click(function(){, could work?

The value i does not exist in the subfunction. Either you have to use a JavaScript closure to pass the value in or derive the value of i from an analysis of the id of the clicked button. Of just add an attribute to each element to link them together. Ie linkid="1" etc. Then use that attribute as your selector.

RE: $("#button[i]").click(function(){, could work?

Just curious, but if you are trying to apply the same click event handler to all the buttons which is what it looks like, why don't you either use the button element or give them a class and use the built in JQuery iterator mechanism to apply the event handler?

CODE

$('button').click(function(){
....
}); 

or

CODE

<button class="button"></button><br>
<button class="button"></button><br> 

CODE

$('.button').click(function(){
....
}); 

Also rather than filling your document with these types of ID's you might want to look at the HTML5 'data' attribute which has been designed specifically for providing a mechanism of holding data about a specific element.

CODE

<button class="button" data-acept='1'></button><br>
<button class="button" data-acept='2'></button><br> 

Last point (which uses the above concept), is there a reason you are loading the JQuery framework and then using oldschool JS?

CODE

document.getElementById("aceptamos["+i+"]").innerHTML; 

Once the JQuery framework is loaded, use it EVERYWHERE - it's awesome and saves you so much time!

CODE

$('.button').click(function(){
  
    var span = $('#aceptamos['+ $(this).data('acept') +']').html();

}); 

though I'd ditch the square bracket ID's for 'aceptamos' also!

Regards,
1DMF.



"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: $("#button[i]").click(function(){, could work?

(OP)
Hello,

Thank you very much jpadie and 1DMF.
The reason why I am using brackets is to be able to get the particular value of each element (the number of them is unknown-although there is a limit- and they come from a while loop).
It didn't occur to me that I can use $(this) to be able to do so.

I have been able to manage well just getting the value of the button element but I would certainly like to be able to get the value of the span element which accompany the clicked button element.

Unfortunately your last script, IDMF, didnt work for me:

CODE --> javascript

$('.button').click(function(){
  
    var span = $('#aceptamos['+ $(this).data('acept') +']').html();

}); 


So, I have tried to do something different, using class attributes too, for the span elements:

CODE --> html

<span class='aceptamos' data-acept='1'>eeeeee</span>
<button class='button' data-acept='1'>send</button><br>
<span class='aceptamos' data-acept='2'>uuuuu</span>
<button class='button' data-acept='2'>send</button><br>
.... 
Then the first part of my code would be:

CODE --> jquery

$('.buttonsi').click(function (e) {
    e.preventDefault();
    var value = $(this).data('acept');
 
    $('.aceptamos').data('acept', value);
... 

This way, if I am not wrong (I have tested it), I would be getting the data value of the button element I click on (as you showed to me), and also setting the data value to the span element I want to get the html value from. But now, I don't know how to get such html value.

I tried doing something like:

var yeah=$('.aceptamos').html();
alert(yeah);

but it is not working. I don't know how to get the html value of that particular span element (with the same data value as the clicked button). I think I am on the good track, probably, but I am missing a step (to settle the particular span element).

Cheers!

enjoy practicing languages at: www.sharinglanguage.com

RE: $("#button[i]").click(function(){, could work?

without using additional attributes (but it would be fine/better to do so)
See this fiddle for example: http://jsfiddle.net/t5tu7duw/

CODE

<span id='aceptamos[0]'>eeeeee</span>
<button id='button[0]'>send</button><br>
<span id='aceptamos[1]'>uuuuu</span>
<button id='button[1]'>send</button><br>
<div id='result'></div>
<script>
//note no for loop
$('[id*="button["]').on('click',function(e){
 e.preventDefault();
 var id = $(this).attr('id').match(/(\d+)/);
 var spanText = $('span[id="aceptamos['+id[1]+']"]').text();
 $('#result').text(spanText);
});
</script> 

RE: $("#button[i]").click(function(){, could work?

Quote:

$('.aceptamos').html()

This is not possible when you have more than one element with the same class, remember when you use classes like this to apply something to more than one element, you get back a collection not the element itself and thus .html() is not a method applicable to collection of elements!

Also I made a faux pas and you have carried it on....

You noticed I use single quotes when writing JS, but HTML should use double, I use single in JS from a habit as I code in Perl and using double quotes causes interpolation of anything encapsulated in the quotes, which is not always the right thing to do if no interpolation is required.

CODE

<span class="aceptamos" data-acept="1">eeeeee</span>
<button class="button" data-acept="1">send</button><br>
<span class="aceptamos" data-acept="2">uuuuu</span>
<button class="button" data-acept="2">send</button><br> 

Doing this...

CODE

var value = $(this).data('acept');
$('.aceptamos').data('acept', value); 
will in effect change the value of all the span elements data attribute 'acept' with the class "aceptamos" to the value of the clicked button.

Also notice Justin's use of the 'on' method , which is considered the better way of applying click events.

This should give you what you want (not tested)

CODE

$('.button').on('click',function(e){
    e.preventDefault();
    var value = $(this).data('acept');
    alert($('span[data-acept="' + value + '"]').html());
}); 



"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: $("#button[i]").click(function(){, could work?

(OP)
Hello,

Thank you for your contributions.
jpadie, your script works like a charm.
Trying to continue with what I was doing (originated by 1DMF, which syntax is a bit

CODE --> javascript

more accessible to me, at this point) I came to do the following:


$('.button').click(function (e) {
    e.preventDefault();
    var value = $(this).data('acept');
    var hey=$('.aceptamos[data-acept*='+value+']').html();
   alert(hey) ;
   
}); 

which works.
Now, just before posting it I have seen 1DMF post, which shows pretty much the same (for sure cleaner than mine).
I see I can remove the "*" from there. I will also use the "on" method.

Thanks a lot for your help.

enjoy practicing languages at: www.sharinglanguage.com

RE: $("#button[i]").click(function(){, could work?

yeah, many ways to skin this cat, and Justin is usually spot on with his solutions.

Like you, I like the syntax in what I provided and to me is easier to read and understand.

And as you found you can either grab all the classes of 'aceptamos' with the desired attribute and value or grab all the spans as I had it.

There is no right or wrong, though if you had lots of spans but only a few with the class, your way would be better (more efficient) as it would have less items in the collection to iterate!

you could even make it a one liner...

CODE

alert($('.aceptamos[data-acept="' + $(this).data('acept') + '"]').html()); 

But sometimes one liners get hard to read and clarity / purpose of code is always best!



"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music

RE: $("#button[i]").click(function(){, could work?

(OP)
Thank you again, to both of you.

enjoy practicing languages at: www.sharinglanguage.com

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close