1

I'm using jquery function attr() to fetch a input element' custom attribute. However this function returns undefined in Chrome. I tried to print this element and the result is:

[prevObject: o.fn.init[1], context: document, selector: "input[name="money",uid="1"]", jquery: "2.1.0", constructor: function…]

Following are my js codes:

$('.panel').each(function(index, element) {
    var uid = $(this).attr('uid');
    console.log($(this));
    var moneyMinusBtn = $(this).find('.btn-money-minus')[0];
    var moneyPlusBtn = $(this).find('.btn-money-plus')[0];
    var moneyInput = $(this).find('input[name="money"]')[0];
    console.log($('input[name="money",uid="'+uid+'"]').attr('uid'));
}

HTML code:

 <input type="number" class="form-control" name="money" value="<?php echo $node['money'] ?>" uid="1" />
M.chaudhry
  • 651
  • 1
  • 6
  • 13
Cosmo
  • 836
  • 1
  • 12
  • 27
  • 1
    Can you make a fiddle demonstrating the problem? I'm not sure why it's not working, but you shouldn't use custom attributes in the first place, you should use `data-XXX` attributes. – Barmar Apr 19 '14 at 11:48
  • a) there's no `uid` attribute in HTML b) your `input[name="money",uid="1"]` selector is invalid c) the collection is therefore probably empty – Bergi Apr 19 '14 at 11:50

2 Answers2

5

The problem is in the way you're chaining the attribute selectors. This will work:

$('input[name="money"][uid="'+uid+'"]').attr('uid')

It might also be a good idea to use data-* attributes.

Thomas
  • 8,426
  • 1
  • 25
  • 49
1

You need to check the rendered HTML to make sure that PHP wrote right values, but anyway, I think you cannot require two attributes in the way you showed:

$('input[name="money",uid="'+uid+'"]')

Try changing it into:

$('input[name="money"][uid="'+uid+'"]')

Or even (might be faster selector, otherwise the same):

$('input').filter('[name="money"][uid="'+uid+'"]')

Note there is no space or separator of any kind between [name="money"] and [uid="'+uid+'"].

See comments for performance discussion.

Meligy
  • 35,654
  • 11
  • 85
  • 109
  • Judging from a quick performance test I'd say that the filter method will be slower: http://jsperf.com/attribute-selector-or-filter – Thomas Apr 19 '14 at 12:09
  • Interesting. it used to be agreed that selecting by tag name is much faster ( highly voted example http://stackoverflow.com/questions/46214/good-ways-to-improve-jquery-selector-performance ), so, I made it first since jQuery (Sizzel) evaluates right to left. I guess the reason it's faster is that `uid` matches a single element directly, and the browser has `querySelectorAll` will have attribute selector optimized already. This won't be the case in a browser that doesn't if you care about old IE for example. – Meligy Apr 19 '14 at 18:29
  • Either Way, I have modified the answer to point to the comments instead. – Meligy Apr 19 '14 at 18:30