Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning value of one text box to another

Have looked at the answers to similar questions to this, but for the life of me, I can't figure out what I'm doing wrong.

I have a two text boxes and a button. When text is added to the first textbox and the button pressed, I want to apply the first textbox's value/text to the second textbox:

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
        $("#button").click(function() {
            var contents = $("#textbox").val();
            $("#container").val(contents);
        });
    </script>
</head>
<body>
    <input type="text" id="textbox" /> <input type="submit" id="button" value="Press This" />
    <br />
    <input type="text" id="container" />
</body>
</html>
like image 231
dbr Avatar asked Aug 11 '11 11:08

dbr


3 Answers

You're not waiting for the DOM to become ready. You should write something like:

$(document).ready(function() {
    $("#button").click(function() {
        var contents = $("#textbox").val();
        $("#container").val(contents);
    });
});
like image 52
Frédéric Hamidi Avatar answered Sep 19 '22 01:09

Frédéric Hamidi


Your code looks good. Just add it to the $(document).ready(...) event handler like this:

$(document).ready(function() {
    $("#button").click(function() {
        var contents = $("#textbox").val();
        $("#container").val(contents);
    });
});

You could also simplify your code a bit:

$(document).ready(function() {
    $("#button").click(function() {
        $("#container").val($("#textbox").val());
    });
});

Take a look at the .ready() docs.

like image 30
James Hill Avatar answered Sep 22 '22 01:09

James Hill


You should wait for all elements with document.ready event, and you can simplify your jquery:

$(document).ready(function() {
    $("#button").click(function() {
        $("#container").val($("#textbox").val());
    });
});
like image 36
VMAtm Avatar answered Sep 18 '22 01:09

VMAtm