mplungjan
mplungjan

Reputation: 177975

Issue with .checked

I am helping someone fix their plain javascript highlight-when-checked

DEMO

If you click yes or no, you will see it breaks and makes an unchecked row highlighted.

I know I could rewrite it in jQuery, but I would REALLY like to know what makes it fail

Thanks

Upvotes: 0

Views: 152

Answers (2)

peirix
peirix

Reputation: 37751

It's because you're adding the classname every time. So if you change between yes/no 5 times, item3 will have classname radio-item myclass myclass myclass myclass myclass. So in your replace you need to make sure it's global (replacing every occurance of the search string)

edit:

This code is adding the classname without checking if it's there in the first place. Remember, you're looping all checkboxes, for every change on any of them.

if (inputArray[i].checked) {
    inputArray[i].parentNode.className += " myclass";
}    

Upvotes: 3

RobG
RobG

Reputation: 147403

Here's some library functions I wrote some time ago:

function trim(s) {
  return s.replace(/(^\s+)|(\s+$)/g,'').replace(/\s+/g,' ');
}

function hasClassName(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);

    var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)');
    return el && re.test(el.className);
}

function addClassName(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (!hasClassName(el, cName)) {
        el.className = trim(el.className + ' ' + cName);
    }
}

function removeClassName(el, cName) {

    if (typeof el == 'string') el = document.getElementById(el);

    if (hasClassName(el, cName)) {
        var re = new RegExp('(^|\\s+)' + cName + '(\\s+|$)','g');
        el.className = trim(el.className.replace(re, ''));
    }
}

Upvotes: 1

Related Questions