Assigning the value of one text field to another

I looked at the answers to such questions, but for life I can’t understand what I am doing wrong.

I have two text fields and a button. When the text is added to the first text field and the button is pressed, I want to apply the first text field / text to the second text field:

<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> 
+6
source share
3 answers

You do not expect the DOM to become ready . You should write something like:

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

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

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

You can also simplify your code a bit:

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

See .ready () docs .

+4
source

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

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

Source: https://habr.com/ru/post/894820/


All Articles