Habib Rehman Habib Rehman - 2 months ago 10
HTML Question

On selecting checkbox i need to get values from input and insert values in input field

I'm trying to get values form fields on checking the check box, basically what i'm trying to do is when ever user clicks the check box it should take data from input fields and copies that to the next fields.

here is my code:



jQuery(document).ready(function(){

jQuery('#check_1').change(function() {
if(jQuery(this).is(":checked")) {

var address = jQuery('#address').attr('value');
var address_2 = jQuery('#address2').attr('value');

alert('Copy selection');
alert(address);
alert(address_2);

$('#cpy_1').val(address);
$('#cpy_2').val(address_2);


}
});

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='address' id="address"/>
<input type='text' name='address2' id='address2' />

<br>
<br>
<hr>
<br>
<h4>Data copied</h4>

<input type='checkbox' name='check_1' id="check_1"/>Copy above fields
<input type='text' name='cpy_1' id='1cpy_1'/>

<input type='text' name='cpy_2' id='cpy_2'/>





but i'm getting undefined by getting input text's value. Please tell me what's wrong there ?

Answer

Change like this :

$(document).ready(function() {
    
    $('#check_1').change(function() {
        
        if($(this).is(":checked")) {
            
            var address    = jQuery('#address').val();
            var address_2  = jQuery('#address2').val();
            
            $("#1cpy_1").val(address);
            $("#cpy_2").val(address_2);

        }
        
    })
    
})
  <input type='text' name='address' id="address"/>
<input type='text' name='address2' id='address2' />

<br>
<br>
<hr>
<br>
<h4>Data copied</h4>

<input type='checkbox' name='check_1' id="check_1"/>Copy above fields
<input type='text' name='cpy_1' id='1cpy_1'/>

<input type='text' name='cpy_2' id='cpy_2'/>
        
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>