Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery button Array

I am writing a piece of code which will show button label of all jquery buttons having class="Short"

I am using the following code:-

$('.Short').button();
var all_short_btns = $(".Short");
for(i=0; i< all_short_btns.length; i++){
   alert(all_short_btns[i].button( "option", "label" ));
}

Html is:

<button class="Short">Label1</button>
<button class="Short">Label2</button>
<button class="Short">Label3</button>
<button class="Short">Label4</button>
<button class="Short">Label5</button>
<button class="Short">Label6</button>

I am getting error:

Uncaught TypeError: Object # has no method 'button'

My Question is how to get label for each button element ?

Thanks in advance.

like image 902
Kuntal Basu Avatar asked May 10 '26 10:05

Kuntal Basu


2 Answers

You were using the wrong method, use .eq(i) to get the specific item and then get the text by calling .html().

jsFiddle

var all_short_btns = $(".Short");
for(i=0; i< all_short_btns.length; i++){
    alert(all_short_btns.eq(i).html());
}

Alternatively you could use $.each() but it's quite a bit slower than the native for loop.

var all_short_btns = $(".Short");
$.each(all_short_buttons, function (i, item) {
    alert(item.html());
});

Update

Since the OP was using jQuery UI .html() would print out the <span> that is automatically generated and wraps the content. The error is occurring because you are using [i] which gets the raw JavaScript object when we need the jQuery object. .eq() gets the jQuery object at that index.

jsFiddle

all_short_btns.eq(i).button("option", "label")
like image 148
Daniel Imms Avatar answered May 12 '26 23:05

Daniel Imms


This may help you:

$(".short").each(function(){
    alert($(this).text());
})


$(".short").each(function(){
    alert($(this).html());
})
like image 28
Sri Tirupathi Raju Avatar answered May 13 '26 00:05

Sri Tirupathi Raju