Mahesh
Mahesh

Reputation: 19

Unable to reset an input Text field using Vanilla Javascript

I am trying to reset an input field using Java Script and it does not work in the way I intend to. I am trying to undestand why it works in a certain way and not in another way. Could you please explain why and provide any pointers if possible. Thank you.

Input text field I am trying to reset:

<input type="text" id="textInput" class="inp">

I defined a button like this:

<button id="resetButton">Reset</button>

I created an event listener on the reset button and used it like below.

var rButton=document.getElementById("resetButton");

rButton.addEventListener("click", function() {
    var inputTextValue=document.getElementById("textInput").value;
    inputTextValue="";
});

This is the JS code I am getting the value from the input text:

 var inputTextValue=document.getElementById("textInput").value;

And to reset the value, I am just assigning it to empty string:

inputTextValue="";

This piece of code doesn't work but when I try to get the reference of the input text like this -

var inputText=document.getElementById("textInput");

and try to reset the value like this, it works -

inputText.value="";

So, I am trying to understand, what is the difference in both ways and what am I doing wrong.

Upvotes: 1

Views: 789

Answers (3)

Mert Aşan
Mert Aşan

Reputation: 436

This way you can reset or select.

$(document).on("click", "#resetButton", function() {
    var textInputValue = $("#textInput").val(); // get value
    $("#textInput").val(""); // or reset value
});

or

var input = document.getElementById("textInput");
var resetButton = document.getElementById("resetButton");

resetButton.addEventListener("click", function() {
    input.val(); // get value
    input.val(""); // or reset value
});

Edit: I haven't seen the Javascript tag. Sorry. :)

Upvotes: 1

user10243107
user10243107

Reputation:

You are copying the current value of your input field into the inputTextValue string and then you replace that copy with an empty string. That means you are not actually altering your input field.

Try

document.getElementById("textInput").value = "";

or

 var input = document.getElementById("textInput");
 input.value = "";

instead.

Upvotes: 2

tymeJV
tymeJV

Reputation: 104785

When you assign the value property to a variable, that's exactly what you're doing. You're simply assigning the value, not creating a reference - either set the entire element to the variable and update the value property, or just update the value property at once:

document.getElementById("textInput").value = "";

Or:

var input = document.getElementById("textInput");
input.value = "";

Upvotes: 4

Related Questions