1

I have three buttons. The idea is to change text on button id #11 and #12 when #1 is clicked.

$(document).ready(function() {
    var dict = {#1: ['#11', '#12']}

    $('button').click(function () {
        var k = dict['#'+$(this).attr('id')]

        for (c in k){
            var m = k[c]
            $(m).button('it works')
        }
    })
});

Now the problem is: if I call alert(m), I get the correct result, but it just doesn't work with $(m).button('it works'). Any idea why?

chazsolo
  • 7,873
  • 1
  • 20
  • 44
Testing man
  • 677
  • 1
  • 12
  • 28
  • 2
    What do you want `$(m).button('it works')` to do? Button is not a jQuery function. – dave Jan 10 '17 at 18:56
  • 1
    as far as my childhood could remember, .button is not a standard prototype. You probably wanted `.text` instead. Also, you are using a for...in with an **array**, which is not really whay you want (for..in is suitable for **object**, despite it **will work**). Here is a working fiddle for you case anyway: https://jsfiddle.net/gLnfo2h8/ – briosheje Jan 10 '17 at 18:59

3 Answers3

4

Sample HTML related to your code:

<button id="1">
  Ohay
</button>

<button id="11">
  hehe
</button>

<button id="12">
  haha
</button>

Correct javascript:

$(document).ready(function() {
  var dict = {'#1': ['#11', '#12']}

  $('button').click(function () {
      var k = dict['#'+$(this).attr('id')]
      for (c = 0; c < k.length; c++){
          var m = k[c]
          $(m).text('it works')
      }
  })
});

the .button prototype, as far as I know, is not a standard jQuery prototype, hence I probably suspect you wanted to use .text instead.

Besides, please be aware that you should change your for..in cycle with a regular for instead (because you are looping an array, not an object), despite it will work in that specific case check this for reference: why shouldn't I use for..in with arrays

Working fiddle:

https://jsfiddle.net/gLnfo2h8/

Community
  • 1
  • 1
briosheje
  • 7,356
  • 2
  • 32
  • 54
3

Use $(m).text('it works'), .button() is not a jQuery function

JB06
  • 1,881
  • 14
  • 28
1

If m is a button target then all you need is to set it's value

jQuery has no function called button. the right solution would be:
$(m).text('some text')

if the button is actually an <input type='button' so you might need to do the following instead:

$(m).val('some text')

Solution would be like that:

$(document).ready(function() {
var dict = {#1: ['#11', '#12']}

$('button').click(function () {
    var k = dict['#'+$(this).attr('id')]

    for (c in k){
        var m = k[c]
        $(m).val('it works')
    }
})
});
Ramy M. Mousa
  • 5,727
  • 3
  • 34
  • 45