I am using the following code to count the number of required input (textboxes) on an HTML5 form, which works fine.
var inputTags = document.getElementsByTagName('input');
reqinputCount = 0;
for (var i=0, length = inputTags.length; i<length; i++) {
if (inputTags[i].validity.valid == false ) {
reqinputCount++;
}
}
Now my problem is that I also have a textarea on the form and want to include that as well.
Can you please help me out.
Thanking in advance.
Since you're already relying on a feature only present in the newest versions of browsers, I'm assuming it's safe to assume you don't mind another such feature being used:
var inputTags = document.querySelector("input,textarea");
Related
I have a website I am working on that takes input from the user and calculates a results. All of the forms are html text input forms where they enter in certain number.
I want to use the input event to check for when the user enters a new value in one of these 6 text forms. The example in the book I am using, JavaScript and JQuery: Interactive Front-End Web Development, suggest to use the getElementById method with the dom event handler to do this:
For example:
function doWhatIwantToDo()
{
//Do something
}
var el = document.getElementById('username');
el.oninput = doWhatIwantToDo;
This is great and I could set up 6 unique ids for each text form, which I will need to do anyway in order to change their inner html in my javascript code, but is there someway I can check for input by using a class name?
I tried using getElementsByClassName but it is tripping me up because it returns an array of objects.
I want to avoid any jquery solutions right now because I am trying to learn vanilla javascript only right now.
Edit/Results:
I like "acbabis" and "mohamedrias" answers but the book implies that using Event Listeners is a newer method and not supported by all browsers. So for now, I would like to stick with the Traditional Dom Event Handlers that it talks about.
"dandavis" answer to just do it in a loop made me realize that perhaps binding an element to an event handler, in a loop, SHOULD actually work and that perhaps I was making a mistake in my loop.
I checked and stupidly I wasn't using array notation to loop through each object in the returned array which is why nothing was happening. Here is my final code that works:
var test = document.getElementsByClassName("test");
for (var i=0; i < test.length; i++)
{
console.log( test[i] );
test[i].onclick = testiness;
}
function testiness ()
{
alert("Success!");
}
var inputElements = document.querySelectorAll('.className');
for(var i = 0, len = inputElements.length ; i < len ; i++) {
inputElements[i].addEventListener('input', doSomethingFunction);
}
querySelectorAll returns you a static NodeList. You need to iterate and attach the event.
Instead of using getElementsByClassName which returns a live HTMLCollection, working with querySelectorAll would be preferrable.
I would document.querySelectorAll for this.
var inputs = document.querySelectorAll('input');
for(var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('input', doWhatIWantToDo);
}
This will find all input elements on the page and add the handler to each one. If you want to use a class, just add it to the desired input tags, and replace document.querySelectorAll('input') with document.querySelectorAll('input.classname').
I'm working on a project where I have to select multiple input tags by NAME from multiple forms.
I selected the forms using getElementsByTagName('forms') (which returns a HTML Collection as far as I understand). When I try to apply the getElementsByName('example') i get the undefined TypeError. After doing some reading I've found out that HTML Collection does not have that method. My question is what method should I use to select the input fields by name in this case?
(Note: I can't use jQuery on this project.)
Please let me know if I need to clarify anything.
Cheers!
Edit: Here's a code i'm working on. One of the constraints in this project is that I don't know how many forms there will be on the website, or how many input boxes those forms will have. (FieldObj is an object that contains the names of input fields)
var formsList = document.getElementsByTagName('form');
var form;
for (form in formsList) {
var currentForm = formsList[form];
for (field in fieldObj) {
if (formsList.getElementsByName(field)) {...}
}
}
It seems fieldObj variable in your code is undefined. I would loop forms in this way:
var formsList = document.getElementsByTagName('form');
for (var i=0; i < formsList.length; i++) {
var form = formsList[i];
for (field in form) {
var value = form[field].value;
}
}
I'm trying to design a site (possibly to make into a Chrome extension) that will allow me to mark which characters have done which events in an online game I play. I'd love it if I had the option to save the values of the checkboxes between visits (and ideally, character names as well), but I'm not great at coding. Also, I'd strongly prefer it if this information could be saved/cleared/reloaded on command, and not otherwise.
The page in question, please pardon me if my code isn't efficient or attractive. I actually prefer to work with it a bit more bunched up, but I tidied it for your benefits.
There had been a suggestion here that I was trying to work with:
var i, checkboxes = document.querySelectorAll('input[type=checkbox]');
function save() {
for (i = 0; i < checkboxes.length; i++) {
localStorage.setItem(checkboxes[i].value, checkboxes[i].checked);
}
}
function load_() {
for (i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = localStorage.getItem(checkboxes[i].value) === 'true' ? true:false;
}
}
But while it works fine in the test, it won't work when I put it into my document (you'll see the var i at the top still, the rest of the code I'd put above the reset function).
Help?
This line:
var i, checkboxes = document.querySelectorAll('input[type=checkbox]');
is in the head of your document and runs immediately. None of the checkboxes exist at the time that it runs.
I'd suggest putting that script at the end of your body element or placing it in a window.onload = function() {}.
If you inspect the DOM structure in the working jsFiddle link you posted, you'll see it places the script at the end of the body element.
I have about 20 pages of forms and I need all the inputs on every page to be converted to uppercase. I'm wondering if it would be possible to build a JavaScript function that I could just copy/paste onto every page without having to do it individually on each input on every page.
Maybe using getElementsByTagName() and addEventLister() and toUpperCase().
Would something like this work?
PS. using CSS only works until the browser send the information back to the server, so that's out.
Something like this should get you started:
var inputElements = document.querySelectorAll('input, select, textarea');
for (var i = 0, l = inputElements.length; i < l; i++) {
if (inputElements[i].tagName == 'SELECT') {
inputElements[i].options[inputElements[i].selectedIndex].value = inputElements[i].options[inputElements[i].selectedIndex].value.toUpperCase();
} else {
inputElements[i].value = inputElements[i].value.toUpperCase();
}
}
Although you should really reconsider this and just do it serverside.
Demo: http://jsfiddle.net/ZgrqA/
I have two tables on my html page with exact same data but there may be few difference which need to be highlighted.
I and using the below Javascript but seems innerHTML does not work as expected-
function CompareTables()
{
var table1 = document.getElementById("table1")
var table2 = document.getElementById("table2")
for(var i=1; i < table1.rows.length; i++)
{
for(var j=1; j < table2.rows.length; j++){
var tab1Val = table1.rows[i].cells[0].innerHTML;
var tab2Val = table2.rows[j].cells[0].innerHTML;
alert(tab1Val.toUpperCase()+"----"+tab2Val.toUpperCase());
var changes =RowExists(table2,tab1Val);
if(!changes[0])
{
table1.rows[i].style.backgroundColor = "red";
instHasChange = true;
}
}
function RowExists(table,columnValue)
{
var hasColumnOrChange = new Array(2);
hasColumnOrChange[0] = false;
for(var i=1; i < table.rows.length; i++)
{
if(table.rows[i].cells[0].innerHTML == columnValue) /*** why these two does not match**/
{
hasColumnOrChange[0] = true;
}
return hasColumnOrChange;
}
}
Please suggest what wrong here.
(table.rows[i].cells[0].innerHTML == columnValue) never returns true even if all values same.
most browsers have bugs with innerHTML and it is not a recommended property to use. different browsers will do different things, usually messing with whitespace, adding/removing quotes, and/or changing the order of attributes.
long story short, never rely on innerHTML.
In it's place, I would recommend using some of the DOM traversal functions, such as .firstChild and .nodeValue. Notice that these are sensitive of white space, and will have to be tweaked if you have anything else in your TD than just text.
http://jsfiddle.net/tdN5L/
if (table.rows[i].cells[0].firstChild.nodeValue === columnValue)
Another option, as pointed out by Micah's solution, is using a library such as jQuery, which will let you ignore most of these browser issues and DOM manipulation pain. I would not recommend bringing in the overhead of jQuery just for this issue, though.
related:
Firefox innerHTML Bug?
innerHTML bug IE8
innerHTML removes attribute quotes in Internet Explorer
Try and use Jquery's method .text
Depending on the browser(Firefox and Chrome's) innerHTML does not work
JQuery takes care of that issue for you.