Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addAttr not working in jquery?

Tags:

jquery

I have a sample code :

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

And jquery

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

When I change value in textbox is result value="" and error in firebug $("#color").addAttr is not a function

How to fix it ?

like image 295
Hai Truong IT Avatar asked May 02 '12 04:05

Hai Truong IT


3 Answers

It's called .attr(), not .addAttr().

You should also replace your inner $('#color') with $(this) to indicate that you're manipulating the same input that's being changed:

$('#color').change(function(){
    $(this).attr('value', 'test');
});
like image 83
BoltClock Avatar answered Nov 14 '22 20:11

BoltClock


You are confused about removeAttr() and you think that addAttr() exists, that's wrong.

The function you want is .attr() - nowadays .prop(), I believe.

like image 17
Oscar Jara Avatar answered Nov 14 '22 21:11

Oscar Jara


You could also do:

$('#color').change(function(){
    $(this).val('test');
});
like image 5
Sudhir Bastakoti Avatar answered Nov 14 '22 22:11

Sudhir Bastakoti