Input field to variable JavaScript | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Input field to variable JavaScript

I'm new to JavaScript and would like to have an input field and a button. When the button is pressed, the value inside the input field would be assinged to a variable. I would also like to be able to do something with the variable afterwards (mentioning this so that I won't get an 'undefined variable' error if it hasnt been given a value yet. If the explanation is unclear, here is how I'd do it in php: <form method='POST'> <input type='text' name='inputfield'> <input type='submit' name='variable' value='Run'> <?php if(isset($_POST["variable"])) { $mytext = $_POST["inputfield"]; echo "<p>$mytext</p>"; } ?>

31st Aug 2019, 3:45 PM
MarkusS
MarkusS - avatar
3 Answers
+ 2
I'd do it like this: 1. add a 'click' event listener function to the button 2. assign a variable to the value of the text input in that function hope this makes sense to you :) otherwise just ask again
31st Aug 2019, 4:22 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
31st Aug 2019, 4:31 PM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 1
Sami Khan Aaron Eberhardt Thanks guys. Starting to undestand how javascript works now. And especially thanks to you Sami for the clean and understandable code.
31st Aug 2019, 4:38 PM
MarkusS
MarkusS - avatar