Difference b/w attr() and prop() in Jquery.


Sometimes we confused, which function should we use between prop(); and attr(); function.
we can understand it by the following example==>


HTML==>
<div class="container">
    <div id="div1"> </div>
    <div id="div2"> </div>
    <div id="div3"> </div>
     <div id="div4"> </div>
    </br>
    <input type="text"  id="textId" name="input1" readonly="readonly"  autocomplete="autocomplete"  autofocus  />
  </div>



JQuery==>
<script type="text/javascript">
    $(document).ready(function(){

      $("#div1").html($("#textId").attr("name")+'</br>');
      $("#div2").html($("#textId").prop('readonly')+'</br>')   
      $("#div3").html($("#textId").attr('readonly')+'</br>');
      $("#div4").html($("#textId").prop('autofocus')+'</br>')

    });

</script>

If I run the above Jquery  code then following result will opt out.

   input1  <=====   $("#div1").html($("#textId").attr("name")+'</br>');
   true <=====      $("#div2").html($("#textId").prop('readonly')+'</br>') 
   readonly <=====    $("#div3").html($("#textId").attr('readonly')+'</br>');
   true <=====     $("#div4").html($("#textId").prop('autofocus')+'</br>')


The Prop() method returns a Boolean value for checked, selected, disabled, readOnly and so on while attr returns a defined string. So, you can directly use .prop("checked") in an if condition.


For complete code reference  and Demo, download file from the below link provided.

click here to Dowload



Comments

Popular posts from this blog

datatable with both top and bottom scroll bar.

Display Loader and disable page while waiting for ajax request

Remove GIT integration from VSCode