How can I input data in HTML using for example <input>
and then interpretet it? What I mean is, I want to input age for exaplme and treat it as variable in order to built the function of age in the script later.

- 221
- 1
- 11
-
Use javascript onChange callback on the input and get the value of the input – fiza khan Sep 08 '18 at 10:47
-
you can not ask this type of questions in stackoverflow, you have to search about your problem, try solutions for it and if you have problems about selected solution, you can ask about it. – Arash Khajelou Sep 08 '18 at 10:51
-
Many questions on StackOverflow could have been researched. It's often a matter of complexity. If you're new to coding and you don't have any idea then you're likely drawn to this site because it pops up when you google anything coding related. I think if the OP learned something then that's fantastic. – Chris Sharp Sep 08 '18 at 12:02
4 Answers
You just need to get the <input>
value with javascript.
For example:
<input type="text" id="age" />
And in javascript:
var x = document.getElementById("age");
var age = x.value;
Now you can treat the age as a variable

- 53,704
- 14
- 91
- 128

- 147
- 2
- 14
If you don't want to use jQuery then you can use JavaScript's getElementById
function. An example:
HTML:
<input id="someInputField" type="text" name="someInput">
JavaScript:
var inputValue = document.getElementById("someInputField").value;
You can also get the value by name using the getElementByName
method.
See the docs for more:
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

- 2,005
- 1
- 18
- 32
First, you would need to select it from the DOM.
const inputField = document.querySelector('#my-input');
then you can view the current value in it with inputField.value

- 308
- 3
- 12
as far as I understand, your concern is using the HTML elements such as labels and spans for user input. while you can always style form elements to look the way you want, but to achieve this you can use HTML's contenteditable
attribute:
<span contenteditable="true" id="input">This is an editable paragraph.</span>
on the JavaScript end, you can use jquery to easily detect the onChange events and call a function to act upon:
$('#input').on('change', function(){
alert($(this).val() );
// or any other operation you'd want to perform
});

- 735
- 1
- 11
- 34
-
Elements with `contenteditable` don't dispatch `change` events. Also, the question did not ask for a jQuery answer. – connexo Sep 08 '18 at 11:37