Scroll

Add button to clear input "text" and "textarea" fields via JavaScript

Add button to clear input "text" and "textarea" fields via JavaScript

Follow
Summary This article demonstrates how to add a "clear input" button next to your open-ended text fields
Applies to askiadesign ; web screens
Written for  Survey scripters ; web designers
Keywords design ; web ; screens ; script ; javascript ; button ; clear ; input ; text

 

See attached 5.4.9 example QEX.

 

Below is some JavaScript code you can insert into a label on the same screen as your open-ended variable(s).

Using this script, it will insert a button with the label text of "Clear", right under your <input type="text"> or <textarea> fields (depending which one you're using on that screen).

<script>
document.addEventListener("DOMContentLoaded", function(event) {
var inputs = document.querySelectorAll('input[type=text]');
var textareas = document.querySelectorAll('textarea');

// Add a button for each input text
for (var i = 0; i < inputs.length; i++) {
var btn = document.createElement("DIV");
var text = document.createTextNode("Clear");
btn.appendChild(text);
btn.className = "clearbutton";
btn.onclick = function () {
this.previousElementSibling.value = '';
};
inputs[i].parentNode.insertBefore(btn, inputs[i].nextSibling);
}

// Add a button for each textarea
for (var j = 0; j < textareas.length; j++) {
var btn = document.createElement("DIV");
var text = document.createTextNode("Clear");
btn.appendChild(text);
btn.className = "clearbutton";
btn.onclick = function () {
this.previousElementSibling.value = '';
};
textareas[j].parentNode.insertBefore(btn, textareas[j].nextSibling);
}

});
</script>

This button is also styled by adding custom CSS into the "Options > Internet Options > CSS" tab:

.clearbutton {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}

 

Whatever text you want to use in the button can be changed in the JavaScript code. Also, how the button is styled can be changed with the CSS.

In my example, it should look and act like the below GIF:

AddClearTextButton.gif

 

Note: if you have multiple open-ended variables merged onto the same screen, each input box will have its own "Clear" button generated below it.

 

Please reach out to support@askia.com if you have any questions.

Have more questions? Submit a request

Comments