QuerySelectorAll identifying all but not adding effect to all - javascript

I ve created simple html form and I want to animate the input fields labels using javascript. I used querySellectorAll method to identify the objects and console logged querySelectorAll(object).length to check the value and it logged correctly. But effect only working only for first 4 input fields (.form__row) . Why is that and also in the console shows error
Cannot read property 'value' of null
const FloatLabel = (() => {
// add active class
const handleFocus = e => {
const target = e.target;
target.parentNode.classList.add('active');
};
// remove active class
const handleBlur = e => {
const target = e.target;
if (!target.value.trim()) {
target.parentNode.classList.remove('active');
target.value = '';
}
};
// register events
const bindEvents = element => {
const floatField = element.querySelector('.form__input');
floatField.addEventListener('focus', handleFocus);
floatField.addEventListener('blur', handleBlur);
};
// get DOM elements
const init = () => {
const floatContainers = document.querySelectorAll('.form__row');
console.log(floatContainers);
if (floatContainers.length) {
floatContainers.forEach((element) => {
if (element.querySelector('.form__input').value) {
element.classList.add('active');
}
bindEvents(element);
});
};
}
return {
init: init
};
})();
FloatLabel.init();
<main class="signin">
<form action="" class="form__signin">
<section class="form__section">
<span class="form__section-title">
Account information
</span>
<div class="form__container">
<div class="form__row">
<label for="uname" class="form__label">User name</label>
<input type="text" class="form__input" name="uname" id="uname" required/>
</div>
<div class="form__row">
<label for="email" class="form__label">Email</label>
<input type="email" class="form__input" name="email" id="email" required/>
</div>
<div class="form__row">
<label for="password" class="form__label">Password</label>
<input type="password" class="form__input" name="password" id="password" required/>
</div>
<div class="form__row">
<label for="confirm" class="form__label">Confirm password</label>
<input type="password" class="form__input" name="confirm" id="confirm" required/>
</div>
</div>
</section>
<section class="form__section">
<span class="form__section-title">
Personal information
</span>
<div class="form__container">
<div class="form__row">
<label for="mr" class="form__label-radio">Master</label>
<input type="radio" class="form__input-radio radio--box" name="title" id="mr" value="mr" required />
<label for="ms" class="form__label-radio">Miss</label>
<input type="radio" class="form__input-radio radio--box" name="title" id="ms" value="ms" required />
</div>
<div class="form__row">
<label for="fname" class="form__label">First name</label>
<input type="text" class="form__input" name="fname" id="fname" required/>
</div>
<div class="form__row">
<label for="lname" class="form__label">Last name</label>
<input type="text" class="form__input" name="lname" id="lname" required/>
</div>
<div class="form__row">
<label for="bdate" class="form__label-select-group">Date of birth</label>
<select name="bdate" id="bdate" class="form__input-select"></select>
<select name="bmonth" id="bmonth" class="form__input-select"></select>
<select name="byear" id="byear" class="form__input-select"></select>
</div>
<div class="form__row">
<label for="bdate" class="form__label">Country</label>
<select name="country" id="country" class="form__input-select"></select>
</div>
</div>
</section>
<section class="form__section">
<span class="form__section-title">
Contact information
</span>
<div class="form__container">
<div class="form__row">
<label for="housenonstreet" class="form__label">House no and street no</label>
<input type="text" class="form__input" name="housenonstreet" id="housenonstreet" required/>
</div>
<div class="form__row">
<label for="city" class="form__label">City</label>
<input type="text" class="form__input" name="city" id="city" required/>
</div>
<div class="form__row">
<label for="postal" class="form__label">Postal Code</label>
<input type="text" class="form__input" name="postal" id="postal" required/>
</div>
<div class="form__row">
<select name="ccode" id="ccode" class="form__input-select"></select>
<label for="" class="form__label">Mobile no</label>
<input type="text" class="form__input">
</div>
</div>
</section>
</form>
</main>

You have a form__row that doesn't have a form__input in it.
<div class="form__row">
<label for="mr" class="form__label-radio">Master</label>
<input type="radio" class="form__input-radio radio--box" name="title" id="mr" value="mr" required />
<label for="ms" class="form__label-radio">Miss</label>
<input type="radio" class="form__input-radio radio--box" name="title" id="ms" value="ms" required />
</div>
So you need to check that element.querySelector(".form__input") returns something before trying to use its value.
floatContainers.forEach((element) => {
let input = element.querySelector('.form__input');
if (!input) {
return;
}
if (input.value) {
element.classList.add('active');
}
bindEvents(element);
});
You should have a similar check in bindEvents(). Or you could just change it so that it receives the input as a parameter, rather than the DIV.

Related

document.getElementById doesnt record values i enter in the form - returns null

Ok this is the code, but somehow i am getting null values everywhere after i submit the form. please help here. When i try to enter some informations in the form, it shows that all the values are null, how can i fix this? I tried moving the script or putting it inside the html, but that didn't helped.
<form class="container jumbotron">
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="FirstName">First Name</label>
<input type="text" class="form-control" id="FirstName" name="name" required>
</div>
<div class="col-md-4 mb-3">
<label for="LastName">Last Name</label>
<input type="text" class="form-control" id="LastName" required>
</div>
<div class="col-md-2 mb-3">
<label for="Age">Age</label>
<input type="number" class="form-control" id="Age" required>
</div>
<div class="col-md-2 mb-3">
<label for="Sex">Sex</label>
<select class="custom-select" id="Sex" required>
<option selected disabled value="">Select gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="City">Address</label>
<input type="text" class="form-control" id="Address" required>
</div>
<div class="col-md-3 mb-3">
<label for="PhoneNumber">Phone Number</label>
<input type="tel" class="form-control" pattern="^\d{3}\d{3}\d{3}$" id="PhoneNumber" required>
</div>
<div class="col-md-3 mb-3">
<label for="Email">Email</label>
<input type="email" class="form-control" id="Email" name="email" required>
</div>
<div class="col-md-3 mb-3">
<label for="Email">Secondary Email</label>
<input type="email" class="form-control" id="SecondaryEmail">
</div>
</div>
<div class="form-row">
<div class="col-md-3 mb-3">
<label for="date">Birthday</label><br>
<input type="date" id="Birthday" class="form-control" name="datemax" min="1900-01-01" max="2020-01-01" required>
</div>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="" id="checkbox" required>
<label class="form-check-label" for="checkbox">
I agree to terms and conditions
</label>
</div>
</div>
<button class="btn btn-primary" type="submit" id="submit">Add new contact</button>
</form>
And this is the js file
let list1 = [];
const addlist1 = (event)=>{
event.preventDefault();
let list12 = {
id: Date.now(),
FirstName: document.getElementById('FirstName').nodeValue,
LastName: document.getElementById('LastName').nodeValue,
Age: document.getElementById('Age').nodeValue,
Sex: document.getElementById('Sex').nodeValue,
Address: document.getElementById('Address').nodeValue,
PhoneNumber: document.getElementById('PhoneNumber').nodeValue,
Email: document.getElementById('Email').nodeValue,
SecondaryEmail: document.getElementById('SecondaryEmail').nodeValue,
//Birthday: document.getElementById('Birthday').nodeValue
}
list1.push(list12);
document.forms[0].reset();
localStorage.setItem('clients', JSON.stringify(list1));
}
document.addEventListener('DOMContentLoaded' , ()=> {
document.getElementById('submit').addEventListener('click', addlist1);
});
To get the value from a form field you have to use value not nodeValue
let list12 = {
id: Date.now(),
FirstName: document.getElementById('FirstName').value,
LastName: document.getElementById('LastName').value,
Age: document.getElementById('Age').value,
Sex: document.getElementById('Sex').value,
Address: document.getElementById('Address').value,
PhoneNumber: document.getElementById('PhoneNumber').value,
Email: document.getElementById('Email').value,
SecondaryEmail: document.getElementById('SecondaryEmail').value,
//Birthday: document.getElementById('Birthday').value
}

Can't get the value of an element

I am trying to get the value of an input element. The element is in a modal and the modal data is populated with different values depending on the button I click to open the modal.
var modalBody = document.getElementsByClassName("modal-body");
for(var i = 0; i < modalbody.length; i++) {
var mac = modalBody.item(i).getElementsByTagName('div')[2].getElementById("mac-name").value;
alert(mac);
}
error: TypeError:
modalBody.item(...).getElementsByTagName(...)[2].getElementById is not
a function
I also tried with document.getElementById("mac-name").value; but that returns blank
<form method="post">
<div class="modal-body">
<div class="form-group">
<label for="station-name" class="col-form-label">ID:</label>
<input class="form-control" id="station-id" name="edit--id" required="" type="text" hidden="">
<input class="form-control" id="station-name" name="edit--name" required="" type="text">
</div>
<div class="form-group">
<label for="profile-name" class="col-form-label">Profile:</label>
<select type="text" class="form-control" id="profile-name" name="edit-profile" required="">
<option>name1</option>
<option>name2</option>
</select>
</div>
<div class="form-group">
<label for="mac-name" class="col-form-label">MAC Address:</label>
<input class="form-control" id="mac-name" name="edit-mac" required="" type="text">
</div>
</div>
</form>
Instead of using getElementsByClassName and then running the following on each element:
var mac = modalBody.item(i).getElementsByTagName('div')[2].getElementById("mac-name").value;
You can use instead use querySelectorAll and pass in .modal-body div #mac-name. This will select all elements with the id mac-name inside a div within an element with the class modal-body. You can use the results of this to then loop over each element and get each value:
var macs = document.querySelectorAll('.modal-body div #mac-name');
See example below:
var macs = document.querySelectorAll('.modal-body div #mac-name');
for (var i = 0; i < macs.length; i++) {
var mac = macs[i].value;
console.log(mac);
}
<form method="post">
<div class="modal-body">
<div class="form-group">
<label for="station-name" class="col-form-label">ID:</label>
<input class="form-control" id="station-id1" name="edit--id" required="" type="text" hidden="">
<input class="form-control" id="station-name1" name="edit--name" required="" type="text">
</div>
<div class="form-group">
<label for="profile-name" class="col-form-label">Profile:</label>
<select type="text" class="form-control" id="profile-name1" name="edit-profile" required="">
<option>name1</option>
<option>name2</option>
</select>
</div>
<div class="form-group">
<label for="mac-name" class="col-form-label">MAC Address:</label>
<input class="form-control" id="mac-name" name="edit-mac" value="Addr 1" required="" type="text">
</div>
</div>
<div class="modal-body">
<div class="form-group">
<label for="station-name" class="col-form-label">ID:</label>
<input class="form-control" id="station-id2" name="edit--id" required="" type="text" hidden="">
<input class="form-control" id="station-name2" name="edit--name" required="" type="text">
</div>
<div class="form-group">
<label for="profile-name" class="col-form-label">Profile:</label>
<select type="text" class="form-control" id="profile-name2" name="edit-profile" required="">
<option>name1</option>
<option>name2</option>
</select>
</div>
<div class="form-group">
<label for="mac-name" class="col-form-label">MAC Address:</label>
<input class="form-control" id="mac-name" name="edit-mac" value="Addr 2" required="" type="text">
</div>
</div>
</form>

Checkbox not display element when checked in meteor

I am working in meteor and am trying to display a block of code when a checkbox is checked. I am new to JS and jquery, but I have research different ways of writing the JS. This is what I came up with:
<div class="recipient">
<div class="toRecipient-container">
<label class="toRecipient">TO:</label>
<input class="toRecipient" type="text" size="45">
</div>
<br>
<div id="checkbox-container" class="checkbox-container">
<label for="newClient">New Client
<input id="newClient" class="newInfo" type="checkbox" onclick="toggle()"></label>
<label for="newBilling" style="padding-left: 20px;">New Billing
<input id="newBilling" class="newInfo" type="checkbox"></label>
</div>
</div>
<div id="billingDetails-container" class="billingDetails-container">
<div class="billingDetails">
<label>Billing Contact:</label>
<input class="billingContact" type="text" size="45">
<label>Billing Phone:</label>
<input class="billingPhone" type="text" size="45">
<div>
<label>Billing Address:</label>
<input class="billingAddress" type="text" placeholder="Street Address" size="45">
<input class="billingAddress" type="text" placeholder="City" size="45">
<input class="billingAddress" type="text" placeholder="State" size="45">
<input class="billingAddress" type="text" placeholder="Zip Code" size="45">
</div>
<label>Billing Email:</label>
<input class="billingEmail" type="text" size="45">
</div>
</div>
And my JS:
Template.InvoicePage.onCreated(function () {
this.state = new ReactiveVar();
});
Template.InvoicePage.helpers({
toggle: ()=>{
var checkBox = document.getElementById("newClient");
var displayBlock = document.getElementById("billingDetails-container");
if (checkBox.checked == true) {
displayBlock.style.display = "block";
} else {
displayBlock.style.display = "none";
}
},
});
Template.InvoicePage.events({
'change #newClient'(event, instance) {
instance.state.set('newClient', event.target.checked)
},
});
When I check the box, I get an error that 'toggle' is undefined. Should this be a template event instead of a helper? What am I missing?
I've never done anything with meteor. There is a lot of different frameworks listed on the website. I'm not sure which one you use (if any). You can't possibly use angular, react and vuejs all at the same time.
Unless I'm wrong and there is a particular reason for the whole
Template.InvoicePage.helpers({...});
simply do
function toggle() {
var checkBox = document.getElementById("newClient");
var displayBlock = document.getElementById("billingDetails-container");
if (checkBox.checked == true) {
displayBlock.style.display = "block";
} else {
displayBlock.style.display = "none";
}
}
It has nothing to do with a framework. Just vanilla javascript and html.
I believe you are trying to show the billingDetails-container when the user selects the New-Client check-box. If that is correct, the below should work
HTML
<div class="recipient">
<div class="toRecipient-container">
<label class="toRecipient">TO:</label>
<input class="toRecipient" type="text" size="45">
</div>
<br>
<div id="checkbox-container" class="checkbox-container">
<label for="newClient">New Client
<input id="newClient" class="newInfo" type="checkbox"></label>
<label for="newBilling" style="padding-left: 20px;">New Billing
<input id="newBilling" class="newInfo" type="checkbox"></label>
</div>
</div>
{{#if showBillingDetails}}
<div id="billingDetails-container" class="billingDetails-container">
<div class="billingDetails">
<label>Billing Contact:</label>
<input class="billingContact" type="text" size="45">
<label>Billing Phone:</label>
<input class="billingPhone" type="text" size="45">
<div>
<label>Billing Address:</label>
<input class="billingAddress" type="text" placeholder="Street Address" size="45">
<input class="billingAddress" type="text" placeholder="City" size="45">
<input class="billingAddress" type="text" placeholder="State" size="45">
<input class="billingAddress" type="text" placeholder="Zip Code" size="45">
</div>
<label>Billing Email:</label>
<input class="billingEmail" type="text" size="45">
</div>
</div>
{{/if}}
JS
Template.InvoicePage.events({
'change #newClient'(event, instance) {
instance.state.set({
'newClient': event.target.checked //Here, we are set the newclient property of state object based on client's selection.
});
}
});
Template.InvoicePage.helpers({
showBillingDetails() {
const state = Template.instance().state.get();
return state && state.newClient; //Here, we use the newclient property of state to decide whether or not to display the billingDetails-container
}
});

URL mapping using jquery in spring mvc

This somewhat confusing but it is my project requirement. I am using spring mvc and jquery. Now I have to post the form and expose the data to back end using ajax call of jquery for this my jquery is
home='<%=request.getContextPath()%>';
$('#userReg').submit(function(event){
var add = {}
add["type"] = $("#type").val();
add["name"] = $("#companyName").val();
add["regNumber"] = $("#regNumber").val();
add["dob"] = $("#dob").val();
add["email"] = $("#email").val();
add["password"] = $("#password").val();
add["confirmPassword"] = $("#cpassword").val();
add["line1"] = $("#line1").val();
add["line2"] = $("#line2").val();
add["state"] = $("#state").val();
add["country"] = $("#country").val();
add["zipCode"] = $("#zipCode").val();
console.log("search: ", add);
event.preventDefault();
$.ajax({
type : "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url : home+"/addCompany",
data : JSON.stringify(add),
dataType : 'json',
timeout : 100000,
success : function(data) {
console.log("SUCCESS: ", data);
alert(data)
},
error : function(e) {
console.log("ERROR: ", e);
alert(e);
},done : function(e) {
console.log("DONE");
}
});
});
and corresponding method
#RequestMapping(value="/addCompany",method=RequestMethod.POST,consumes=MediaType.APPLICATION_JSON_VALUE)
public#ResponseBody String userLogin(HttpServletRequest req,#RequestBody CompanyRegVO user){
logger.debug("signUp user:"+user);
// get reCAPTCHA request param
String gRecaptchaResponse = req.getParameter("g-recaptcha-response");
boolean isVerified= Verify.verifyGcaptchResponse(gRecaptchaResponse);
ObjectMapper mapper=new ObjectMapper();
String jsonString="";
System.out.println("signUp user:"+user);
Integer id=null;
try{
if(isVerified){
id = signupHandler.process(user);
if(id!=null){
logger.debug("ID in controller:"+id);
emailHandler.sendVerificationMail(id,user.getEmail());
System.out.println("user create successfully");
}
jsonString=mapper.writeValueAsString("User creaated successfully");
}
else
jsonString= mapper.writeValueAsString("please verify that you are not a robot");
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
try {
jsonString=mapper.writeValueAsString(e.getMessage());
} catch (JsonProcessingException e1) {
}
return jsonString;
}
return "success";
}
Now my form is mapped with this URL
#RequestMapping(value="/signUp",method=RequestMethod.GET)
public String register(Model model){
CompanyRegVO user=new CompanyRegVO();
model.addAttribute("userForm", user);
return "signUp";
}
When I submit my form I expected that my jquery code will execute will invoke my upper one method but it inovkes above get method and return me signUp page with my data as query parameter. Now if I comment mapping for "/signUp" my server is giving 404 error. since page is mapped to that URL. So any one can please tell what is remedy for this kind of situation jquery or spring??
Edit 1:
below is my form
<form class="form-horizontal" name="userReg" id="userReg">
<div class="form-group">
<label class="col-sm-2 control-label">Company Name</label>
<div class="col-sm-4">
<input name="companyName" type="text" class="form-control" id="companyName" placeholder="Name" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Registration number</label>
<div class="col-sm-4">
<input name="RegNumber" type="number" required="required" class="form-control" id="regNumber" placeholder="Registration number" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Address line 1</label>
<div class="col-sm-4">
<input name="line1" type="text" required="required" class="form-control" id="line1" placeholder="line1" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Address line 2</label>
<div class="col-sm-4">
<input name="line2" type="text" class="form-control" id="line2" placeholder="line2" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Zip code</label>
<div class="col-sm-4">
<input name="zipCode" type="number" required="required" class="form-control" id="zipCode" placeholder="zip code" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">State</label>
<div class="col-sm-4">
<input name="state" type="text" required="required" class="form-control" id="state" placeholder="State" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Country</label>
<div class="col-sm-4">
<input name="country" type="text" required="required" class="form-control" id="country" placeholder="country" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input name="email" type="email" class="form-control" id="email" placeholder="Email" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Date of Birth(dd-mm-yyyy)</label>
<div class="col-sm-4">
<input name="dob" type="text" class="form-control" id="dob" placeholder="Date of birth" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input name="password" id="password" maxlength="12" pattern="((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{8,12})" required="required" type="password" class="form-control" id="password" placeholder="password" />
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-4">
<input name="confirmPassword" id="cpassword" maxlength="12" required="required" type="password" class="form-control" id="cpassword" placeholder="confirm password" />
<span id='message'></span>
</div>
</div>
<br>
<div class="form-group">
<label class="col-sm-2 control-label">User type</label>
<div class="col-sm-4">
<select class="form-control" id="type" name="type" >
<option selected="selected">--select--</option>
<option value="user" >CEO</option>
<option value="admin">HR</option>
</select>
</div>
</div>
<br>
<div class="form-group">
<div class="g-recaptcha"
data-sitekey="my-public key"></div>
</div>
<br>
<div class="col-md-6 center-block">
<input type="submit" class="btn-lg btn-primary center-block" value="save">
</div>
</form>
When use <input type="submit" ..... /> it will submit your form according to your form action url. e.g something.html
So change the and add a click listener.
<input type="button" onclick="_submit()"/>
and your js would be
function _submit(){
// submit your form via ajax.
}
This should submit your form with your specified url.
Thanks.

AngulaJS input fields not loose focus when clicked

I am trying to create a simple angularjs form where i want to have nested object as ng-model
$scope.project = {
name:"Some Name",
location:{line1:"" , line2:"", city:"", zipcode:""}
}
http://plnkr.co/edit/RfN7qZBX3HlOtGhFOdFX?p=preview
now the problem is when i click on line2 , city,state etc focus goes back to line1
tried changing HTML and several other stuff but don't know what to do..
Tried removing bootstrap as well.
The issue is that you are misusing the <label> tag. Instead of this:
<label class="form-group">
Client Location
<div class="controls">
<input type="text" data-ng-model="project.location.line1" class="form-control" placeholder="Line 1">
<input type="text" data-ng-model="project.location.line2" class="form-control" placeholder="Line 2">
<input type="text" data-ng-model="project.location.city" class="form-control" placeholder="City">
<input type="text" data-ng-model="project.location.state" class="form-control" placeholder="State">
<input type="text" data-ng-model="project.location.zip" class="form-control" placeholder="Zip Code">
<input type="text" data-ng-model="project.location.country" class="form-control" placeholder="Country">
</div>
</label>
Try this:
<div class="form-group">
<label>Client Location</label>
<div class="controls">
<input type="text" data-ng-model="project.location.line1" class="form-control" placeholder="Line 1">
<input type="text" data-ng-model="project.location.line2" class="form-control" placeholder="Line 2">
<input type="text" data-ng-model="project.location.city" class="form-control" placeholder="City">
<input type="text" data-ng-model="project.location.state" class="form-control" placeholder="State">
<input type="text" data-ng-model="project.location.zip" class="form-control" placeholder="Zip Code">
<input type="text" data-ng-model="project.location.country" class="form-control" placeholder="Country">
</div>
</div>
The first label should be changed as well. Instead of this:
<label class="form-group">Name
<div class="controls">
<input type="text" data-ng-model="project.name" class="form-control" placeholder="Name">
</div>
</label>
Try this:
<div class="form-group">
<label>Name</label>
<div class="controls">
<input type="text" data-ng-model="project.name" class="form-control" placeholder="Name">
</div>
</div>
Or this:
<div class="form-group">
<label>
Name
<input type="text" data-ng-model="project.name" class="form-control" placeholder="Name">
</label>
</div>

Categories

Resources