views:

93

answers:

3

Hello everyone! This is my first message here so I hope that newbies also get help :) My problem is following: let's start with code first.... javascript:

$(document).ready(function(){
    if ($("input#datum2").val() == "")
    {
        $().click(function(){
            $("input#datum2").val($("input#datum1").val());
        });
    }    
});

html:

<form >
        <input id="datum1" type="text" />
        <input id="datum2" type="text" />
</form>

What I want this script to do is that first checks if input field datum2 is empty. If yes, than copy value from input#datum1. This action is suppose to happen each time user clicks (anywhere on page?)... When user types something in datum1 and clicks somewhere than this value is copied to datum2. The problem is when user edits datum1 or datum2, than this value is again copied to datum2. Obviously this condition

if ($("input#datum2").val() == "")

works only once. I'm new to javascript and jquery so I would appreciate for any help. Thanks in advance!

Cheers, Ile

A: 

I see the way round are the order of the click event and "if ($("#datum2",..."

HTML:

<form id="myform">
        <input id="datum1" type="text" />
        <input id="datum2" type="text" />
</form>

Javascript:

$(document).ready(function(){
    $().click(function(){
       if ($("#datum2", $("#myform")).val() == "") {
            $("#datum2", $("#myform").val($("#datum1", $("#myform")).val());
        }    
    });
});
andres descalzo
+2  A: 

Sounds like you'll need to bind to a different event. Blur occurs when an input loses focus, which sounds like what you're after.

$(function() {
  var $datum2 = $('#datum2');

  $('#datum1').blur(function() {
    if(!$datum2.val())
      $datum2.val($(this).val());
  });
});

Couple of things:

1) $(function() { ... is a nice shortcut to $(document).ready

2) In JavaScript, an empty string evals to false, so its a nice shortcut.

Ben
this was fast... thanks a lot to you Ben and to you Andres ;)
ile
I've just implemented this together with datepicker and there's new "bug". Datepicker works in way that user clicks on input field and chooses a date by mouse click and not by typing it. After clicking to datum2 field still nothing happens. When i click again on datum1 and again on datum2 just then the value is copied. Solution for this? Something instead of blur?
ile
A: 
$(document).ready(function(){   
  var $datum2 = $('#datum2');

  $('#datum2').hover(function() {
    if(!$datum2.val())
      $datum2.val($('#datum1').val());
  });
});
ile
this is the working code?
jimyshock
yep... not working to you?
ile