22 Votes

JavaScript: Set and read Input Value without jQuery using pure JavaScript

Question by Guest | Last update on 2021-11-17 | Created on 2016-09-20

Is there actually any possibility available to change or retrieve the value of an HTML input field with pure JavaScript?

Up to now, I have always used jQuery for that and accordingly, this was my procedure to get and set values from fields:

<input type="text" id="fieldId" value="xyz">
$("#fieldId").val("abc");        // set value using jQuery
var wert = $("#fieldId").val();  // get value using jQuery

Of course, this requires including the whole jQuery library into my website. And in one of my recent projects I would like to go without that because this would be the only function I need from the entire jQuery library.

So, is there any plain JavaScript solution coming without jQuery I could use for this purpose?

ReplyPositiveNegative
2Best Answer2 Votes

Yes, you can do that using pure JavaScript without any problems.

To get the field, you can use the function document.getElementById() to which we have to pass the ID of our element. The rest can be done using .value:

document.getElementById('fieldId').value = "abc";
var v = document.getElementById('fieldId').value;

Accordingly, the first line sets the value of the field with the ID "fieldId" to "abc", the second line reads out the value in order to store it in the variable "v".
Last update on 2021-11-17 | Created on 2016-09-21

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.