I am trying to set a value on an input when button is pressed, the problem is that it's throwing an error:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
Here's my code which looks pretty simple and all that:
document.getElementById("icon-removal-btn").onclick = function(e){
e.preventDefault()
let label = document.getElementById("icon-label");
let input = document.getElementById("icon-input");
label.innerHTML = 'Choose File';
input.value = 'deleted';
}
I even tried typing into the console document.getElementById("icon-input").value = "deleted" but it still didn't work. What is going on? Am I doing something wrong here?
document.getElementById("icon-removal-btn").onclick = function(e){
e.preventDefault()
let label = document.getElementById("icon-label");
let input = document.getElementById("icon-input");
label.innerHTML = 'Choose File';
input.value = 'deleted';
}
<div class="form-row">
<div class="form-group col">
<div class="form-control-lg input-group mt-1">
<div class="input-group-prepend">
<span class="input-group-text">Upload Icon</span>
</div>
<div class="custom-file">
<button class="icon-removal-button" id="icon-removal-btn">Delete</button>
<input type="file" name="icon" id="icon-input" value="{{$card->icon}}" class="custom-file-input" id="inputGroupFile01">
<label class="custom-file-label" id="icon-label" for="inputGroupFile01">{{$card->icon}}</label>
</div>
</div>
</div>
</div>
From the HTML Standard (emphasis mine):
input .
value[ = value ]Returns the current value of the form control.
Can be set, to change the value.
Throws an "
InvalidStateError"DOMExceptionif it is set to any value other than the empty string when the control is a file upload control.
So you can't change the value of a <input type="file"> to anything other than "".
You are trying the set the value of the <input type="file"> to a string. This can't be done since type="file" only accepts file's as valid input.
Please read more about type="file" at MDN.
Removing the types fixes it (temporary)
document.getElementById("icon-removal-btn").onclick = function(e){
e.preventDefault()
let label = document.getElementById("icon-label");
let input = document.getElementById("icon-input");
label.innerHTML = 'Choose File';
input.value = 'deleted';
}
<div class="form-row">
<div class="form-group col">
<div class="form-control-lg input-group mt-1">
<div class="input-group-prepend">
<span class="input-group-text">Upload Icon</span>
</div>
<div class="custom-file">
<button class="icon-removal-button" id="icon-removal-btn">Delete</button>
<input name="icon" id="icon-input" value="{{$card->icon}}" class="custom-file-input" id="inputGroupFile01">
<label class="custom-file-label" id="icon-label" for="inputGroupFile01">{{$card->icon}}</label>
</div>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With