Javascript validation doesn't work because of documents.getElementsById() - javascript

I'm having trouble with this code,if I add the line I have commented out, the form seems to go to the page I've linked in action without undergoing validation.But if i don't include it, the validation works fine and the alert box displays the message.I don't understand the reason why it doesn't work.
function validateform(){
var flag=0;
var uname=document.forms["f1"]["uname"].value;
var pass=document.forms["f1"]["pass"].value;
var fname=document.forms["f1"]["fname"].value;
var lname=document.forms["f1"]["lname"].value;
var phone=document.forms["f1"]["phone"].value;
var email=document.forms["f1"]["email"].value;
var err="";
if(uname==""||uname==null) {
err+="Username cannot be left blank\n";
//document.getElementsById("uname").style.backgroundColor="red";
flag=1;
}
if(pass==""||pass==null){
err+="Password cannot be left blank\n";
flag=1;
}
if(email==""||email==null){
err+="Email cannot be left blank\n";
flag=1;
}
if(flag==0){
return true;
}else{
alert(err);
return false;
}
}

You've made a typo.
It is document.getElementById('id') and not document.getElementsById
It gets a single element as ids are unique and meant for a single element.
It is also named getElementById due to the fact that there can't be duplicate ids.

An id is a unique identifier. There can be only one element of a given id. Therefore the method to get elements by their id is not plural. getElementById, not getElementsById.

getElementsByName and 2. getElementById.
because multiple HTML elements with same name are allowed
because ID is unique and cannot be assigned to multiple HTML Elements.
thats why: getElementsById and getElementByName are wrong

please try this correct the function name document.getElementById its not elements
document.getElementById("uname").style.bacgroundColor="red";

I think you want getElementById not getElementsById (not the S in elementS). Depending on the browser you are using and what you have turned on getElementsById will fail gracefully and never let you know about it or it will display an error.

Related

After click show element in console

I need a help. I have a button in html with class "rekapitulace". And i want to do if a user click on that button, it will show a item in text input with class "jmeno". I wrote this but it isnt correct. Any solutions?
function rekapitulaceButton() {
var rekapitulaceButton = document.getElementsByClassName('rekapitulace')
rekapitulaceButton.addEventListener('click', precistUdaje)
}
function precistUdaje() {
var jmeno = document.getElementsByClassName('jmeno')
localStorage.setItem('local-jmeno', jmeno)
console.log(localStorage.getItem('local-jmeno'))
}
getElementsByClassName() returns all elements of provided class name, not just a single element. Notice how the name of that method contains plural elements word.
To get the first element, you can do:
const rekapitulaceButton = document.getElementsByClassName('rekapitulace')[0];
Another possibility is document.querySelector(), which always returns one element (first match) or null:
const rekapitulaceButton = document.querySelector('.rekapitulace');
document.getElementsByClassName('rekapitulace') return a nodelist array so if you need return an one node elment using id instead of class
document.getElementById('rekapitulace')
Note that you may be misusing localStorage for your debugging. The second argument of .set should be a string.
As mentioned already, you should really try to use IDs instead of classes for targeting the right input, and document.getElementsByClassName returns multiple elements and not just one element.

Get First Next element with classname Plain Javascript

I am trying to Get First Child with classname Plain Javascript.
I am trying to write my own form validation and trying the error message i appended and remove it. As well as dont append if error message is already there.
If you help me with just the first part getting child with class name that whould be great.
function display_error(selector, message) {
selector.insertAdjacentHTML('afterend', "<h1 class='js-error' >" + message + "</h1>");
}
function validateForm() {
// Validate Name Field
// Check if name has les than 3
var elem = document.getElementById("name")
if (elem.value.length < 3) {
display_error(elem, "Less than 3")
return false;
} else {
// here is the error
error_label = elem.querySelector('.js-error');
error_label.textContent = "more than 3"
}
}
here is a fiddle
https://jsfiddle.net/efh941cc/3/
The beautiful thing about document.querySelector() is that you can use CSS selectors rather than the, often clunky, DOM API.
CSS provides a very simple selector called first-child which does exactly what you need.
// Find the first element that uses the .test class that is a child of another element.
var firstTest = document.querySelector(".test:first-child");
// Now that you've scanned and found the element and stored a reference to it
// in a variable, you can access any aspect of the element.
console.log(firstTest.textContent);
firstTest.innerHTML = "<span>Now, I have completely different content than before!</span>";
// Now, we can get a reference to other elements that are relative to the last
// one we found.
var firstTestError = document.querySelector(".test:first-child + .error");
firstTestError.style.backgroundColor = "aqua";
firstTestError.innerHTML = "<span>Required</span>";
<div>
<span class="test">one</span><span class="error"></span>
<div class="test">two</div>
<div class="test">three</div>
</div>
In modern JavaScript, to get the first child with a class name, you can use the following:
document.querySelector('element.class:first-child')
Here, you supply the actual element, and the actual class name.
document.querySelector is available in all modern browsers, and will take any string which matches a CSS selector. It even works in IE8, though the :first-child pseudo class is not available there.
const GetFirstChild = document.querySelector(' .PlainJavascript');

getElementbyId is not a function

I have a simple piece of JavaScript that changes the color of a button, but I keep getting he error that getting the button is not a function, even though the same function (with the same capitalisation and case) works just a couple of lines above.
if (this.ButtonColor != "") {
var button = document.getElementbyId('modal-close');
button.style.backgroundColor = this.ButtonColor;
}
The function is document.getElementById(), not document.getElementbyId()
It is simply a typo, the function you are looking for is getElementById.
By with a capital B instead of by.
here is a reference to that method.
Instead of using this.ButtonColor did you try
var button = document.getElementById("modal-close");
button.style.backgroundColor = "the color you want rather than using "

Set a check box with specific name as well as id as checked using javaScript

In my HTML file, I want to set a check box with specific name as well as id as= checked. How can I acheive this..?
eg:
<input type="checkbox" name="myName_1" id="1" value="my Value 1"> my Value 1
I know document.getElementById('id').checked = true;, but this only checks id. I need to check for id and name simultaneously using JavaScript. Pls help.
Edit:
More specific:
if(document.getElementById(1) && document.getElementById(1).type == "checkbox" ){
document.getElementById(1).checked = true;
}
Note: I have other elements that have same id, but different name, as well as same name, but different id. But no two have both in common.
Well, as i said IDs are always unique in the DOM. So having elements with the same ID is not valid.
You can however select by the name attribute with getElementsByName as this selection supports multiple element. It will just create a array that you can acces through the index value. So you can just loop through all the element and check them one by one:
var elem = document.getElementsByName('myName_1');
for(var i = 0; i < elem.length; i++)
{
elem[i].checked = true;
}
jsFiddle
Having id of HTML elements, starting with a number is incorrect. Rename your id and make it unique. Also value of id of 1 evaluates to true by javascript engine.
However if your HTML document is HTML5 compliant then id starting with a number is not problem.
You could do something like this, not ideal, but would solve the problem.
var names = document.getElementsByName(nameToFind);
names.forEach(funciton(item) {
if (item.id == idToFind)
item.checked = true;
});
As mentioned by several comments, it is not valid to have more than one element with the same id. If there are more than one of the same id, the behavior is unreliable.
If you have groupings of elements that are similar, a common convention with many developers is to give them a common class. This could/would replace your use of name. You can then search on elements within a certain class that have a specific id. (Which may be redundant, depending on your use.)
Searching by class is done with document.getElementsByClassName("myClass"), which returns an array of elements, similar to getElementsByName. Once you have this array, you can then loop through to determine if your id is within that class group[see note below] and apply effects as necessary. (e.g. elementArray[i].checked = true)
Note - It would be much more efficient to search for the id then determine the class, in my opinion.

getElementById problem

I call the following function with a mouseover event but it's not working. My id's are all correct & I have properly linked all my external scripts.
function new2() {
var prevWin = document.GetElementById("recentlyaddedtip");
prevWin.style.visibility = "visible";
}
recentlyaddedtip is set as hidden in the stylesheet (and it properly changes to visible when I change it manually.)
JavaScript is case sensitive.
Try:
document.getElementById('recentlyaddedtip');
Notice the small 'g'.
You shouldn't uppercase the G in GetElementById, it should be getElementById().
JavaScript is case sensitive ;-)
var prevWin = document.getElementById("recentlyaddedtip");
getElementById is a case sensitive function name.
GetElementById should be getElementById (note the case)
Well, I don't see your mouseover function so I don't know if that's spelled right, but try:
var prevWin = document.getElementById("recentlyaddedtip");
with a lowercase g.

Categories

Resources