I'm making a simple swap button which doesn't seem to work.
HTML
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<a onclick="paid(123);" class="no" id="123"></a>
<a onclick="paid(124);" class="yes" id="124"></a>
<a onclick="paid(125);" class="no" id="125"></a>
</body>
</html>
JAVASCRIPT
<script type="text/javascript">
function paid(currentId) {
if (document.getElementById(currentId).hasClass("no")) {
document.getElementById(currentId).removeClass( 'no' );
document.getElementById(currentId).addClass( 'yes' );
}
else if (document.getElementById(currentId).hasClass("yes")) {
document.getElementById(currentId).removeClass( 'yes' );
document.getElementById(currentId).addClass( 'no' );
}
}
</script>
Am I missing something obvious here? :)
Instead of creating function
paid()
, you can use jQuery like this:This will bind click event to Anchor tag and toggle Classes.
You're not using jQuery to select those elements, so they don't have the
hasClass
,removeClass
andaddClass
methods. They are just DOM elements. Use this instead:Additionally, you should not use
onclick
attributes. You should use the jQuery syntax instead:Finally, (trying to be nice here!) you should read a good jQuery tutorial as it seems you haven't fully grasped the techniques required to use the library.
A pure javascript solution will be like this:
HTML
jQuery
Fiddle