Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

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

Status
Not open for further replies.

breaststroke

Programmer
Apr 10, 2011
39
ES
Hello,

I would like to know, please, if there is any reason why the following is not working (using the jQuery click function):
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:
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):

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:
 
it might be possible that this will work. but sfaik the ID attribute CANNOT contain square brackets (
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(){
    ....
  });
};
 
for readers, generally - in HTML5 the id attribute can now contain any character other than a space.
 
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:
for( var i=0; i<6;i++){
  $("#button[" + i + "]").click (function(){
    ....
  });
};
I have changed something, following the line of your first example:
Code:
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:

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:
for(var i=0;i<6;i++){
$("[id='button["+i+"]']").click(function(){

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

when I write:

JavaScript:
alert(span);

afterwards, I get nothing.

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

Code:
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:
 
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.
 
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
 
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:

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:

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:
$('.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:
 
without using additional attributes (but it would be fine/better to do so)
See this fiddle for example:
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>
 
$('.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
 
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
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:
 
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
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top