lifestylebyatom
lifestylebyatom

Reputation: 77

When I check on checkbox how to copy value text1 to text2?

this is my html code

<input type="text" name="txt1" id="txt1" placeholder="txt1" class="form-control">
<p><input type="checkbox" name="checkbox" id="checkbox" class="checkbox">copy address</p>
<input type="text" name="txt2" id="txt2" placeholder="txt2" class="form-control">

is this script

$(".checkbox").change(function() {
var txt1filed = $(this).parent();
var txt1 = $(this).val();
var txt2filed = $('#txt2').parent();
var txt2 = $('#txt2').val();    
  if(this.checked) {
    $('#txt2').val($(this).val())
  }
  else {

  }        
});

how to edit this code. If I need to copy value text1 to text2 and disable it. when uncheck delete value text2

Upvotes: 1

Views: 1778

Answers (3)

You can try this

$(".checkbox").on("change",function(){

 if (this.checked ) {
            $("#txt2").val($("#txt1").val());
            $("#txt2").attr("disabled", "disabled");
        } else {
            $("#txt2").removeAttr("disabled");
            $('#txt2').attr("value", "");
            $("#txt2").attr("placeholder", "txt2")  ;
        }    

});

Upvotes: 0

askemottelson
askemottelson

Reputation: 159

<!DOCTYPE html>
<html>
  <head>
      <script src="jquery.min.js"></script>
      <script type="text/javascript">

        jQuery(window).load(function() {

          $("#checkbox").change(function() {
            var txt1 = $("#txt1").val();
            var txt2 = $("#txt2").val();

            if(this.checked) {
              $('#txt2').val(txt1);
              $('#txt2').attr("disabled","disabled");
            }
            else {
              $('#txt2').val('');
            }        
          });

        });

      </script>

  </head>
  <body>

    <input type="text" name="txt1" id="txt1" placeholder="txt1" class="form-control">

    <p>
     <input type="checkbox" name="checkbox" id="checkbox" class="checkbox">copy address
    </p>

    <input type="text" name="txt2" id="txt2" placeholder="txt2" class="form-control">

  </body>

</html>

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

$(".checkbox").change(function() {
  if(this.checked) {
      $('#txt2').val($('#txt1').val()).prop('disabled', true);
  }
  else {
      $('#txt2').val('').prop('disabled', false);
  }        
});

here's the working jsFiddle

Upvotes: 3

Related Questions