views:

23

answers:

3

I have to copy the text from one text box to another using checkbox through jquery I have applied jquery event in my code, it works partially correct.. code is as follows:

<html>
<head>
    <script src="js/jquery.js" ></script>
</head>
<body>
    <form>
        <input type="text" name="startdate" id="startdate" value=""/>
        <input type="text" name="enddate" id="enddate" value=""/>
        <input type="checkbox" name="checker" id="checker" />
    </form>
    <script>
    $(document).ready(function(){
            $("#startdate").change(function(o){
        if($("#checker").is(":checked")){
            $("#enddate").val($("#startdate").val());
        }

});
});
    </script>
</body>
</html>

this code works as follows, I always have checkbox checked by default hence whenever i insert the start date and then tab, the start date gets copied to enddate.

My Problem

but now if uncheck the checkbox and change the start date and then recheck the check box, the start date is not copied, Now what should be done in this situation.. please help me....

+1  A: 

Add an event for the checkbox as well:

$('#checker').bind('click', function () {
    if ($(this).attr('checked')) { 
       $("#enddate").val($("#startdate").val());
    };
});

Or maybe only if enddate does not have a value:

$('#checker').bind('change', function () {
    var endDate = $('#enddate');

    if ($(this).attr('checked') && jQuery.trim(endDate.val()) === "") { 
       endDate.val($("#startdate").val());
    };
});
Matt
Nice Idea... to use trim
OM The Eternity
+2  A: 

Something like this:

$(document).ready(function(){
    $("#startdate").change(function(o){
        if($("#checker").is(":checked")){
            $("#enddate").val($("#startdate").val());
        }
    });

    $("#checker").change(function() {
        if($(this).is(":checked")) {
            $("#enddate").val($("#startdate").val());
        }
    });
});
Tatu Ulmanen
+1  A: 

you can just .bind() a click event to your checkbox.

$('#checker').click(function(){
   if($(this).is(':checked')){
      $("#enddate").val($("#startdate").val());
   }
});
jAndy