Anilkumar Bathula
Anilkumar Bathula

Reputation: 278

Make Copied value is not changable or editable in javascript

I have a requirement in java script

  1. When i have a value in one field that value is copied into another field.
  2. Once the same value copied in another field, a button can be clicked that makes the copied value so it cannot be changed and not even editable.

For first one i have done.

<input type='text' id='field_1'></br>
<input type='text' id='field_2'> </br>    

$(document).ready(function () {
    $('#field_1').on('change', function (e) {
       $('#field_2').val($('#field_1').val());
    });
});

JS Fiddle image

Upvotes: 1

Views: 97

Answers (2)

R.K.Saini
R.K.Saini

Reputation: 2708

You need to add readonly property to both your input fields on click of your button.

Like this :

$(document).ready(function () {
    $("#not_editable").hide();
    $('#field_1').on('change', function (e) {
       $('#field_2').val($('#field_1').val());
       if($(this).val()!='')
       {
         $("#not_editable").show();
       }
    });
    $("#not_editable").click(function(){
        $('#field_1').prop("readonly",true);
        $('#field_2').prop("readonly",true);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='field_1'></br>
<input type='text' id='field_2'> </br>    

<button id="not_editable" type="button">Mark Un-editable</button>

Upvotes: 0

Alexander Higgins
Alexander Higgins

Reputation: 6923

You can bind an click handler to your button that will unbind your first input using unbind(). It can also make the second input readonly using .prop("readonly",true); and can disable itself using 1.prop("disabled", true);`

Like this:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='field_1'></br>
<input type='text' id='field_2'> </br> 
<input type='button' id='btnReadOnly' value="Make Readonly">   

<script>
$(document).ready(function () {
    $('#field_1').change(function (e) {
       $('#field_2').val($('#field_1').val());
    });
    $('#btnReadOnly').click(function() {
         $('#field_1').unbind();
         $('#field_2').prop("readonly",true).css("background-color","#dddddd");
         
         $('#btnReadOnly').prop("disabled", true);
    });
});
</script>

Upvotes: 2

Related Questions