clear input boxes on button click with javascript - javascript

I've a program which creates text input boxes dynamically. I want to clear the contents of the boxes on the click of clear button.
var elems = document.getElementsByClassName(CLId);
var myLength = elems.length;
var total = 0;
for (var i = 0; i < myLength; ++i) {
if(elems[i].value != null && elems[i].value > 0){
var el = elems[i];
}
}
I use this to get the values of the boxes, but don't know how to make them empty....

use getElementsByTagName (the class version is not cross-browser yet)
and set the value to "", for the elements with the desired class.
var cname, elems = document.getElementsByTagName("input");
for ( var i = elems.length; i--; ) {
cname = elems[i].className;
if ( cname && cname.indexOf(CLId) > -1 ) {
// empty the input box
elems[i].value = "";
}
}
(or you can use a reset input box for the entire form)

if it is in a form, you can simply use the <input type="reset" value="clear"/> tag (HTML). Otherwise you will want:
var elems = document.getElementsByTagName("input");
var l = elems.length;
for (var i = 0; i < l; ++i){
elems[i].value="";
}

You could try setting the value:
el.value = '';

The value of elems[i] in your loop is going to be a string, so you can test its length or its equivalent to the empty string (""). You can also set its value to "" to clear it.
elems[i].value = ""

Related

How scan all <span> tags of a page and get or set a content?

I have this following code that scans all <input> tags of a page and then you are able to set you to get a value to this tag.
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
input[i].value = "123";
}
Now, how can I do the same with a <span> tag, which I already know does not have a property called value?
Your question was somewhat confusing, but I'll give my best answer:
Just take your code for the inputs, and change a few key componenents:
var span = document.getElementsByTagName('span');//Replace "input" with "span"
for (var i = 0; i < span.length; i++) {//Again, replacing "input" with "span"
var textInsideTheSpan = span[i].textContent;//Reading text inside span
span[i].textContent = "Your text here";//Writing text to the span
}
The key here is in the .textContent, a property of the javascript Node object, which can be read or written to, depending on your application. Everything else simply replaced "input" with "span".
Just use following:
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
var text = spans[i].innerHTML;
if (text.length == 0) {
spans[i].innerHTML = i; //Some text
}
}
You can use Node.textContent to set the text inside span:
var input = document.getElementsByTagName('span');
for (var i = 0; i < input.length; i++) {
input[i].textContent = "123";
}
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>

How to change the parameters of getElementById in a loop

I am working on a form, and I would like to reset the lines individually without using reset.
How to vary the values ​​of the attribute passed as parameter of the method getElementById in JavaScript using a loop?
Here is an example of my source code below:
<script>
var element = document.getElementById('#re');
element.addEventListener('click', function() {
document.getElementById("#id1").value = "";
document.getElementById("#id2").value = "";
document.getElementById("#id3").value = "";
});
</script>
Assuming your IDs have the format shown in your example:
for (var i = 1; i <= 3; i++) {
document.getElementById("id" + i).value = "";
}
If that's not the case but you know the ID of every element you can put all IDs in an array and use that:
var elementIds = ["id1", "id2", "id3"];
elementIds.forEach(function(id) {
document.getElementById(id).value = "";
});
Another solution is to give all the elements you want to reset a specific class and target that:
var elements = document.getElementsByClassName("resetable-element");
[].slice.call(elements).forEach(function(element) {
element.value = "";
});
Instead of using ids, you can loop through your inputs for example:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
For your simple example, you could loop through the values 1 - 3 (I assume the # in the ID is a typo?):
for(var i = 1; i <= 3; i++) {
document.getElementById('id' + i).value = '';
}
If you can identify the elements by something else, such as a class name, you might prefer to iterate over that:
var elements = document.querySelectorAll('.field');
Array.prototype.slice.call(elements).forEach(function(element) {
element.value = '';
});

onchange event not tracking properly

I have a form that I want to track any changes. Right now I have it set so when the user exits the page, an alert box displays saying how many changes were made to the form. However, it keeps registering 0. I've tested with adding an alert to the inputChanges function telling me a change has occurred and the alert fires, but the count still registers as 0 when I exit the page...
Here's my script:
window.onload = function() {
var totalChanges = "";
var inputHandles = 0;
var selectHandles = 0;
var textAreaHandles = 0;
window.onbeforeunload = function(){
alert("Total Form Changes:" + totalChanges);
}//onbeforeunload
var totalChanges = inputHandles + selectHandles + textAreaHandles;
function inputChanges() {
inputHandles++;
alert("Change");
}
var inputs = document.getElementsByTagName("input");
for (i = 0; i < inputs.length; i++){
inputs[i].onchange = inputChanges;
}
function selectChanges(){
selectHandles++;
}
var selects = document.getElementsByTagName("select");
for (i = 0; i < selects.length; i++){
selects[i].onselect = selectChanges;
}
function textAreaChanges(){
textAreaHandles++;
}
var textAreas = document.getElementsByTagName("textarea");
for (i = 0; i < textAreas.length; i++){
textAreas[i].onchange = textAreaChanges;
}
}//Onload
You declare totalChanges here:
var totalChanges = "";
...and then re-declare it here:
var totalChanges = inputHandles + selectHandles + textAreaHandles;
...at which point the things you're adding up are all 0.
You need to do that calculation at the point where you need the value:
window.onbeforeunload = function(){
totalChanges = inputHandles + selectHandles + textAreaHandles;
alert("Total Form Changes:" + totalChanges);
}
Or set totalChanges = 0 initially and then increment it every time the other variables change, but that's clunkier.
Note also that you're not tallying the number of fields that now have values different to their starting values, you're tallying the number of individual edits. So if the user changes a field twice with the second change being back to the original value your code will track that as two changes (when logically it's kind of zero changes).
Since the user can change values back to what they were, I suggest you compare all input.value with input.defaultValue and check select.options[select.selectedIndex]defaultSelected
also you might want to move the } and the alert to after the sum of total changes
something like this
window.onload = function() {
var totalChanges = 0;
window.onbeforeunload = function(){
var inputs = document.getElementsByTagName("input"); // ditto for "textarea"
for (var i = 0; i < inputs.length; i++){
totaChanges += inputs[i].value != inputs[i].defaultValue;
}
var selects = document.getElementsByTagName("select");
for (var i = 0; i < selects.length; i++){
totalChanges += !selects[i].defaultSelected;
}
alert("Total Form Changes:" + totalChanges);
}//onbeforeunload
}

Loop though all input boxes and clear them

How can I, using javascript, loop through all input boxes on a page and clear the data inside of them (making them all blank)?
Try this code:
​$('input').val('');
It's looping over all input elements and it's setting their value to the empty string.
Here is a demo: http://jsfiddle.net/maqVn/1/
And of course if you don't have jQuery:
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i += 1) {
inputs[i].value = '';
}​​​​
Since I prefer the functional style, you can use:
Array.prototype.slice.call(
document.getElementsByTagName('input'))
.forEach(function (el) {
el.value = '';
});
[].forEach.call(document.getElementsByTagName('input'), function(e){
e.value = '';
});
Edit: If you want to grab textareas and other elements, you can use querySelectorAll:
[].forEach.call(
document.querySelectorAll('input, textarea'),
function(e) { e.value = ''; }
);
var inputs = document.getElementsByTagName("input"),
clearTypes = { "text" : 1, "password" : 1, "email" : 1 }, // etc. you fill this in
i = inputs.length,
input;
while (i) {
if (clearTypes[(input = inputs[--i]).type]) {
input.value = "";
}
}
Just to register an alternative without JavaScript, the HTML element <input type="reset" /> clear all fields of the form. In some scenarios it may be enough.
Without jquery:
var list = document.getElementsByTagName('input');
for(var i = 0; i < list.length; i++) {
if(list[i].type == 'text' || list[i].type == 'password')
list[i].value = '';
}
You are able to do something like tha following:
<script>
e = document.getElementsByTagName('input');
for (i = 0; i < e.length; i++){
if (e[i].type != 'text') continue;
e[i].value = '';
}
</script>
Edited: added exclude for input which their types are not text!

How to determine which checkboxes are checked in an HTML form?

I have 11 checkboxes in my HTML form and already have a section in my onclick function to determine how many of them were checked, but I would like to be able to tell which of the checkboxes were checked, and possibly just add whichever checkboxes were checked to an arraylist by id/value etc.
EDIT: (Fixed code..?)
var formobj = document.forms[0];
var ingNum = 0;
checked = [];
for (var j = 0; j < formobj.elements.length; j++) {
if (formobj.elements[j].type == "checkbox" && formobj.elements[j].checked) {
ingNum++;
checked.push(formobj.elements[j].value);
}
}
If you want to convert the ones checked to an array of their value attributes (if id attribute, swap value with id), you could use...
var inputs = document.getElementById('your-form').getElementsByTagName('input'),
checked = [];
for (var i = 0, length = inputs.length; i < length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checked.push(inputs[i].value);
}
}
That will work on any of the older IEs you may care about.
If you have the luxury of only supporting newer browsers, you could use...
var checked = [].slice.call(document
.querySelectorAll('#your-form input[type="checkbox"]'))
.filter(function(checkbox) {
return checkbox.checked;
})
.map(function(checkbox) {
return checkbox.value;
});
If you were using a library such as jQuery, it's even simpler...
var checked = $('#your-form :checkbox:checked')
.map(function() {
return this.value;
})
.get();
var checkedBoxes = [];
$("input:checked").each(function() {
checkedBoxes.push($(this));
});
Actually, I think you could just do this:
var checkedBoxes = $("input:checked");
but I'm not 100% sure if that works.

Categories