jQuery selector: addressing a submit button by ID

2019-08-12 18:36发布

问题:

Given a submit button:

<input type="submit" value="Sign Up" name="AddToCart" size="2" id="AddToCart" />

why wouldn't this code disable the button:

$('#AddToCart').attr(disabled, 'disabled');

mny thx

回答1:

The attribute name passed to .attr() needs to be in quotes, like this:

$('#AddToCart').attr('disabled', 'disabled');
//or without quotes, as an object:
$('#AddToCart').attr({ disabled: 'disabled' });

Also make sure this is running in a document.ready event handler, or somewhere else after the element is ready, e.g.:

$(function() {
  $('#AddToCart').attr('disabled', 'disabled');
});