And jquery $('#color').chang...">

AddAttr not working in jquery?

I have an example code:

<input type="text" name="color" id="color" value="" /> 

And jquery

 $('#color').change(function(){ $('#color').addAttr('value', 'test'); }); 

When I change the value in the text field, the result is value="" and an error in firebug $("#color").addAttr is not a function

How to fix it?

+14
jquery
source share
3 answers

It is called .attr() , not .addAttr() .

You should also replace your inner $('#color') with $(this) to indicate that you are controlling the same input that changes:

 $('#color').change(function(){ $(this).attr('value', 'test'); }); 
+36
source share

You are not sure that removeAttr() and you think addAttr() exists, which is wrong.

I believe you need the .attr() function - currently .prop() .

+8
source share

You can also do:

 $('#color').change(function(){ $(this).val('test'); }); 
+5
source share

All Articles