最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CoffeeScript: how to addClass unless - Stack Overflow

programmeradmin4浏览0评论

Trying to add a class to all input elements unless that input element's type == 'submit'

$('input, textarea') ->
  unless $(@).getAttribute('type').val == "submit"
    $(@).addClass('form-control')

My Javascript debugging kit isn't very developed...so forced to decipher cryptic errors:

[Error] TypeError: '[object Object]' is not a function (evaluating '$('input, textarea')')
    ready (disk_files.js, line 37)
    dispatch (jquery.js, line 5096)
    handle (jquery.js, line 4767)
    dispatchEvent
    triggerEvent (turbolinks.js, line 199)
    onload (turbolinks.js, line 45)

Trying to add a class to all input elements unless that input element's type == 'submit'

$('input, textarea') ->
  unless $(@).getAttribute('type').val == "submit"
    $(@).addClass('form-control')

My Javascript debugging kit isn't very developed...so forced to decipher cryptic errors:

[Error] TypeError: '[object Object]' is not a function (evaluating '$('input, textarea')')
    ready (disk_files.js, line 37)
    dispatch (jquery.js, line 5096)
    handle (jquery.js, line 4767)
    dispatchEvent
    triggerEvent (turbolinks.js, line 199)
    onload (turbolinks.js, line 45)
Share edited Aug 30, 2013 at 20:17 asawyer 17.8k8 gold badges62 silver badges92 bronze badges asked Aug 30, 2013 at 19:44 MeltemiMeltemi 38.4k52 gold badges201 silver badges298 bronze badges 7
  • 1 The coffeescript syntax is fine, I'd imagine the problem is whatever getAttribute is doing is not what you expect. I suggest consulting the documentation. Edit - If this is jQuery make sure the library is loading properly. – asawyer Commented Aug 30, 2013 at 19:48
  • 1 Is this jQuery or something with a similar syntax? $(select)(function) is wrong if it is jQuery. – asawyer Commented Aug 30, 2013 at 19:51
  • 1 The error is ing from the $('input, textarea') -> line which means your calling the returned jQuery object and passing it a function which is not correct. Also, anytime you are checking attributes of an element use .attr(name) and depending on version, .prop(name) for properties of DOM classes. – Brandon Buck Commented Aug 30, 2013 at 19:57
  • Very helpful ments; I find it educational to see the many different ways to acplish the same thing! – Meltemi Commented Aug 30, 2013 at 19:58
  • @Meltemi In the future be sure to use the jQuery tag when the question is using the library, so we don't have to guess. – asawyer Commented Aug 30, 2013 at 20:17
 |  Show 2 more ments

3 Answers 3

Reset to default 6
$('input[type!=submit], textarea').addClass('form-control')

You can do this with a css-style selector:

$('input:not([type="submit"]), textarea').addClass('form-control')

This should work:

$input = $('input, textarea')
$input.addClass('form-control') unless $input.attr('type') == 'submit'
发布评论

评论列表(0)

  1. 暂无评论