Jesse
Jesse

Reputation: 309

How do I copy input from one textbox to another via checkbox using jQuery?

I'm cleaning up a simple form that has a Start Date textbox and an End Date textbox. I want to add a checkbox in between these fields that the user can check if the End Date is the same as the Start Date, so when they check it, the Start Date input value (e.g., 04/01/09) will automagically appear in the End Date textbox, so they don't have to type in the same date twice. Does that make sense?

BTW, I'm using the sexy jquery datepicker UI, and it's sweet, but I just can't figure out the above problem.

I know there's a simple solution (event handler?) but I'm stumped.

Upvotes: 8

Views: 16989

Answers (2)

Tom Schaefer
Tom Schaefer

Reputation: 897

Simple hack to solve your problem.

<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(){
            $("input#checker").bind("click",function(o){
                if($("input#checker:checked").length){
                    $("#enddate").val($("#startdate").val());
                }else{
                    $("#enddate").val("");
                }
            });
        }
    );
    </script>
</body>
</html>

Upvotes: 4

Ali
Ali

Reputation: 267077

Try this code:

$("#checkboxId").click(copyDate);

function copyDate()
{
   var start=$("#startDate").val();
   if (this.checked==true)
     $("#endDate").val(start);
}

Replace the 'id's with your own field ids.

Upvotes: 13

Related Questions