I want to know if the code below removes all input type='text'
values back to ""
:
var inp = document.getElementsByTagName('input');
for (var i = inp.length - 1; i >= 0; i--) {
if ('text' === inp[i].type) inp[i].value = "";
}
Then I want to know if I have an input
which is type='text'
but which class
is .num_questions
. How can I code that so that it looks for the class name and gives it a value of "1"
?
document.getElementsByClassName('num_questions');
if ('text'===inp.type) inp.value = "1";
. But what do I replace 'text' with in the if statemen - user1304948 2012-04-05 17:25
Well, i don't think your question should be downvoted, handling classNames is not easy in javascript. So here is my answer:
var inp = document.getElementsByTagName('input');
for (var i = inp.length-1; i>=0; i--) {
if ('text'===inp[i].type) {
if(inp[i].className.indexOf('num_questions') > -1){
inp[i].value = "1";
} else{
inp[i].value = "";
}
}
}
There is a property className
on the Html Dom Element.
function hasCssClass(elt,clz) {
return elt.className.match(new RegExp('(\\s+|^)'+clz+'(\\s+|$)'));
}
var inp = document.getElementsByTagName('input');
for (var i = inp.length-1; i>=0; i--) {
if ('text'===inp[i].type && hasCssClass(inp[i],'num_questions')) {
inp[i].value = "?";
}
}
EDIT - followup as requested.
Each HTML DOM Element has a className
property, which is a string, containing a list of whitespace-separated CSS classes that apply to the element. In order to determine if a class applies to a particular element, you need to search for that string, in the list.
There are a couple ways to do it. One way is to split the className string by whitespace, and then see if your desired class (needle) is equal to any of the elements in the resulting string array. This might be something like this:
function hasCssClass(elt, clz) {
var classes = elt.className.split(/\s+/);
for(i=0; i<classes.Length;i++) {
if (clz == classes[i]) return true;
}
return false;
}
Another way is to use a regex match; that's what I did, because to me it's more succint. The regex I used looks for something, followed by the classname, followed by something else. The first something is (\\s+|^)
, which in English means "one or more whitespace characters, OR, the beginning of the string." The something else is (\\s+|$)
, which in English is, "one or more whitespace characters, OR the end of the string." Therefore, the entire regex matches a string which consists of: