Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear Experts,

i need a javascript to add an attribute in a class...

Here is the below Html code of HTML SELECT..


HTML
<select id="ddl_State" name="validation-select" class="select validate[required]">

<option value="">Please select</option>
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third options</option>
</select>



I need a javascript code for add an attribute in this class.. Eg :

HTML
<select id="ddl_State" name="validation-select" class="select validate[required] Disabled">


Here i have added "Disabled" in the class attribute.....

How can i add this using javascript, without delete the existing class attributes....

Thanks and Regards,

Dileep
Posted

Using Javascript, you can do it using setAttribute()[^] method.
JavaScript
var elem = document.getElementById("ddl_State");
elem.setAttribute("class", "select validate[required] Disabled");


Using jQuery, it's pretty simple:
JavaScript
$("#ddl_State").attr("class", "select validate[required] Disabled");

[Edit]
.prop()[^] is recommended way and supported in newer versions of jQuery. So below code is better:
JavaScript
$("#ddl_State").prop("class", "select validate[required] Disabled");
 
Share this answer
 
v2
Comments
dilzz 4-Apr-13 5:55am    
These code are working fine.. i can see the change when i check in the inspect Element.. But this drop downlist will not be disabled.... :( when i hard coded this , then it become disabled.. but when i use the above code then it didn't disabled......

please advice me...

Thanks
Ankur\m/ 4-Apr-13 6:00am    
Add this line to your javascript code and it should be fine:
$("#ddl_State").attr("disabled", "disabled");
using jQuery
JavaScript
var existingClass= $('#ddl_State').prop('class');
$('#ddl_State').prop('class',existingClass + ' Disabled');
 
Share this answer
 
Comments
dilzz 4-Apr-13 5:55am    
These code are working fine.. i can see the change when i check in the inspect Element.. But this drop downlist will not be disabled.... :( when i hard coded this , then it become disabled.. but when i use the above code then it didn't disabled......

please advice me...

Thanks
vijay__p 4-Apr-13 6:05am    
If you want to disable dropdown then disabled value should not be inside class attribute. It should be added as separate attribute. try below code to disable dropdown.

$('#ddl_State').prop('disabled','disabled');

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900