简体   繁体   中英

Replace all occurrences of “<”, “>” inside value attribute

I have the requirement to replace all occurrences of "<" and ">" characters that are found inside the value attribute. I want to replace "<" and ">" characters with ""

This is my sample html:

<form name="form1">
<input type="text" value="<first set><second set><third set>" />
<input type="text" value="<fourth set><fifth set><sixth set>" />
</form>

I tried using javascript replace method but no luck.

You could use this pure JavaScript function:

 function removeLessGreaterThan(html) { // Use the DOM API to change the value attribute values: var span = document.createElement('span'); span.innerHTML = html; var inputs = span.querySelectorAll('input[type=text]'); for (var i = 0; i < inputs.length; i++) { inputs[i].setAttribute('value', inputs[i].value.replace(/[<>]/g, '')); } return span.innerHTML; } // Sample data: var html = '<form name="form1"> <input type="text" value="Here is a >test<." /> <input type="text" value="And another >test<." /> </form>'; html = removeLessGreaterThan(html); console.log(html);

const FORM_NAME = "form1";

var fields = document.getElementsByName(FORM_NAME)[0].getElementsByTagName("input");

for(var i = 0; i < fields.length; i++) {
    fields[i].value = fields[i].value.replace(/[<>]/g, "");
}

I think you are expecting this way. Please go through the code.

 function ReplaceMyValues() { var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i += 1) { if(inputs[i].type=="text") { var currentValue=inputs[i].value.replace(/[<>]/g, ""); inputs[i].value = currentValue; } } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <form name="form1"> <input type="text" value="<first set><second set><third set>" /> <input type="text" value="<fourth set><fifth set><sixth set>" /> <input id="Test" type="button" value="Replace" onclick="ReplaceMyValues();"></input> </form>

你可以使用 jquery

$(".yourInput").val($(".yourInput").val().replace('<', '').replace('>', ''))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM