0

From my understanding .attr() and .val() are the same except .attr() returns the initial value/ the value in the markup, where as the .val() returns the current value. I did a little experiment though and that brought up more questions then answers. I know there is a duplicate but it didn't seem to fully answer my question

    var attrib=$('#overlay').attr('style');
    //returned  the initial value "display: none;"
    //then I changed the value with
     var test= $('#overlay').attr('style', 'display: block');
    // returned "display: block;"
    //I then pulled back up the value with .attr()
    var test2= $('#overlay').attr('style');
    /* returned "display: block;", 
    it returned the current value not the one in the markup */

So what exactly is the difference?

Brandon
  • 1,099
  • 1
  • 9
  • 14

1 Answers1

2

.val() is used to get the value associated with any html tag and attr() is used to fetch the attributes like id, class, disabled etc. val() works for textbox, text, hidden but attr works for p div table, text, textarea and so on..

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59