开发者

Change class of an HTML element with Javascript

开发者 https://www.devze.com 2023-03-28 11:30 出处:网络
I need to change on the fly the class of an HTML element depending on the choice made by an user with a radio button but the problem is that I get the message

I need to change on the fly the class of an HTML element depending on the choice made by an user with a radio button but the problem is that I get the message

"Erreur : missing ) after argument list Fichier Source : website Ligne : 1, Colonne : 71 Code Source : document.getElementById('jj_conjoint').setAttribute('class','validate['required']');".

my code :

<label>Husband/Wife :</label>
    <input type="radio" name="not_single" value="yes" onclick="document.getElementById('birthdate_partner').setAttribute('class','validate['required']');">yes
    <input type="radio" name="not_single" value="no" checked="checked">no


<select name="birthdate_partner" id="birthdate_partner">
   <option value="" selected="selected">-</option>
   <option value="1987" >1987</option>
   <option value="1986" >1986</option>
   <option value="1985" >1985</option>
   <option valu开发者_开发技巧e="1984" >1984</option>
</select>


You have not quoted the ID string, so document.getElementById returns a null because the unquoted string is seen as an uninitialised variable, which will evaluate to undefined.

document.getElementById('birthdate_partner').setAttribute('class',validate['required']);


document.getElementById(birthdate_partner)

is referring to a variable called birthdate_partner. Instead, you should pass the ID as a string:

document.getElementById('birthdate_partner')

The variable birthdate_partner is never assigned to some value, so it is undefined, resulting in this being called:

document.getElementById(undefined)

which does not work.


You could use jQuery to do this:

$("[name=birthdate_partner]").removeClass(className);
$("[name=birthdate_partner]").addClass(className);
0

精彩评论

暂无评论...
验证码 换一张
取 消