Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readonly with jquery

i'm trying to add readonly to all the inputs and then on the click remove the readonly to make it works for typing. the readonly set for all inputs part works but the remove on click doesn't work please help.

my code :

<script language="javascript">
$(document).ready(function()
{
$('#secureFields :input').attr('readonly', true);

    $('.readonly').click(
    function()
    {
        if ($('.readonly').attr("readonly") == true)
        {
            $('.readonly').val('');
            $('.readonly').removeAttr("readonly");
        }           
    }); 
});
</script>

html is like this :

 <table class='table' id='secureFields'  >
        <tr>
            <td width=200>First Name:</td>
            <td><input readonly='readonly'  type='text'  name='firstname' size=30 class='required'/></td>
        </tr>
        <tr>
like image 511
Abude Avatar asked Jun 13 '12 07:06

Abude


People also ask

What is readonly in jQuery?

Use jQuery methods to add the readonly attribute to the form input field. jQuery attr() Method: This method set/return attributes and values of the selected elements. If this method is used to return the attribute value, it returns the value of the first selected element.

How do I make a field read only in jQuery?

To make a textarea and input type read only, use the attr() method .

How do I set readonly?

The readonly attribute of <input> element is used to specify that the input field is read-only. If an input is readonly, then it's content cannot be changed but can be copied and highlighted. It is a boolean attribute. Example: This example using <input> readonly attribute to set the read-only value.

How do you add a readonly attribute?

Use setAttribute() Method to add the readonly attribute to the form input field using JavaScript. setAttribute() Method: This method adds the defined attribute to an element, and gives it the defined value.


2 Answers

Do you mean:

$("input").click(function() {
  if ( $(this).is('[readonly]') ) {
     $(this).removeAttr("readonly");
  } 
});

See: jsFiddle

like image 64
Sudhir Bastakoti Avatar answered Sep 23 '22 19:09

Sudhir Bastakoti


<html>

 <table class='table' id='secureFields'>
    <tr>
        <td width=200>First Name:</td>
        <td><input type='text'  name='firstname' size=30 class='required'/></td>
    </tr>
</table>

   <button id="btnEnableInputs" type="button">Enable!</button>     

</html>

$(document).ready(function() {

$("#secureFields :input").each(function() {
   $(this).attr("readonly", true);
});

$("#btnEnableInputs").click(function() {
     $("#secureFields :input").each(function() {
          $(this).attr("readonly", false);
     });
 });
});

http://jsfiddle.net/hfK8f/

like image 20
Darren Avatar answered Sep 22 '22 19:09

Darren