Given:
let mystr = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";
Given:
let mystr = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";
I'd like to remove the text in the value param "Luis Tiant"
using JS.
To be clear: I want to change value="Luis Tiant"
to value=""
in the string itself. This is a string not yet a DOM element. After I remove the value then I'll add it to the DOM.
-
document.getElementById("item_Name").value = "";
– PajLe Commented May 22, 2020 at 13:54 - 1 Does this answer your question? How to remove/change an input value using javascript – Flori Bruci Commented May 22, 2020 at 13:55
- thank you for the reply. This won't work. I apologized for not be more clear. mystr is a string and I want to change value="Luis Tiant" to value="" in the string – Carlos Vasquez Commented May 22, 2020 at 13:58
- @CarlosVasquez I've updated my answer below to meet your new requirements. – pretzelhammer Commented May 22, 2020 at 14:12
4 Answers
Reset to default 1Get the input
element and set its value
to ''
(empty string).
Example below clears the input value after 2 seconds, so you can see it in action:
setTimeout(() => {
document.querySelector('input').value = '';
}, 2000);
<input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="Luis Tiant">
Update
Question above has been clarified. If you'd like to replace the value
attribute in the string itself you can acplish that using regex and the replace
method like so:
let string = "<input class=\"text-box single-line\" id=\"item_Name\" name=\"item.Name\" type=\"text\" value=\"Luis Tiant\">";
console.log(string);
let newString = string.replace(/value=\".*\"/, "value=\"\"");
console.log(newString);
By initializing the ID
you can do this as well.
document.getElementById("item_Name").value = "Your new Value Here";
Instead of setting a variable equal to a string of html, then using string manipulation to change the element attributes, I'd suggest using the Document.createElement() method and related APIs to programmatically create the html element. Then you'll have access to methods like Element.removeAttribute()
let mystr = "<input class="text-box single-line" id="item_Name" name="item.Name" type="text" value="Luis Tiant">"
var res = mystr.match(/value=\".*\"/g);
var str = mystr.replace(res, 'value=""');