dynamically adding summernote editor not working - javascript

I'm trying to adding summernote editor dynamically whenever clicking on add button.
It doesn't working while adding through of dynamically.
Here is my code.
$(document).ready(function() {
var maxField = 20; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div class="row"><div class="col-md-6"><div class="form-group"><label for="profile_img_dynamic">Heading Image</label><div class="custom-file"><input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required><label class="custom-file-label" for="customFile">Choose file</label></div></div></div><div class="col-md-6"><div class="form-group"><label for="title_name_dynamic">Heading Title</label><input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name"></div></div><div class="col-md-10"><!-- /.card-header --><div class="card-body pad"><div class="mb-3"><label for="description">Descriptions</label><textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here"style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea></div></div></div>Remove Me</i></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').empty(); //Remove field html
x--; //Decrement field counter
});
});
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.7.0/summernote.js"></script>
<div class="field_wrapper">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="profile_img_dynamic">Heading Image</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="title_name_dynamic">Heading Title</label>
<input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name">
</div>
</div>
<div class="col-md-10">
<!-- /.card-header -->
<div class="card-body pad">
<div class="mb-3">
<label for="description">Descriptions</label>
<textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here"
style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
</div>
</div>
<div class=""></div>
<div class="col-md-2">
<div class="form-group">
<label for="add">Add More</label><br>
ADD</i>
</div>
</div>
</div>
</div>
As you can see, summer editor not does not displaying there is only simple textarea are displaying instead of editor.

You can add $(wrapper).find('.textarea').summernote() after $(wrapper).append(fieldHTML);
$(wrapper).append(fieldHTML); //Add field html
$(wrapper).find('.textarea').summernote()
Demo
$(document).ready(function() {
var maxField = 20; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div class="row"><div class="col-md-6"><div class="form-group"><label for="profile_img_dynamic">Heading Image</label><div class="custom-file"><input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required><label class="custom-file-label" for="customFile">Choose file</label></div></div></div><div class="col-md-6"><div class="form-group"><label for="title_name_dynamic">Heading Title</label><input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name"></div></div><div class="col-md-10"><!-- /.card-header --><div class="card-body pad"><div class="mb-3"><label for="description">Descriptions</label><textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here"style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea></div></div></div>Remove Me</i></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(document).ready(function() {
$('.textarea').summernote();
});
//Once add button is clicked
$(addButton).click(function() {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
$(wrapper).find('.textarea').summernote()
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').empty(); //Remove field html
x--; //Decrement field counter
});
});
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote#0.8.18/dist/summernote.min.js"></script>
<div class="field_wrapper">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="profile_img_dynamic">Heading Image</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="profile_img_dynamic" name="profile_img_dynamic[]" required>
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="title_name_dynamic">Heading Title</label>
<input type="text" name="title_name_dynamic[]" class="form-control" id="title_name_dynamic" placeholder="Enter name">
</div>
</div>
<div class="col-md-10">
<!-- /.card-header -->
<div class="card-body pad">
<div class="mb-3">
<label for="description">Descriptions</label>
<textarea class="textarea" name="info_name_dynamic[]" id="info_name_dynamic" rows="3" placeholder="Place some text here" style="width: 100%; height: 200px; font-size: 14px; line-height: 18px; border: 1px solid #dddddd; padding: 10px;"></textarea>
</div>
</div>
</div>
<div class=""></div>
<div class="col-md-2">
<div class="form-group">
<label for="add">Add More</label><br>
ADD</i>
</div>
</div>
</div>
</div>

Related

Function changing id only once. [Javascript]

What I am trying to do: I am adding new entries whenever I submit a form and that entry should have an animation (fadeIn effect). I am adding new entries whenever I submit a form. Every entry is being added using javascript template literal in which I am adding using divisions with classes and ids. Every entry has an Id and when I use that ID to add animation, all entries get the animation as they have same ids (I know IDs should not be same that is why I am trying to change it).
What I am trying to do: I am trying to change ID of previously added entry or div.
Program is changing ID only once.
My javascript code:
var enrolledStudents = [];
let form = document.getElementById("student-enrollment-form");
const getStudentDetails = (event) => {
event.preventDefault();
// This is the important part, test if form is valid
if (form.checkValidity() === false){
// This is the magic function that displays the validation errors to the user
form.reportValidity();
return;
}
var skillsList = [];
var name = document.getElementById("name-input").value;
var email = document.getElementById("email-input").value;
var website = document.getElementById("website-input").value;
var imgLink = document.getElementById("imglink-input").value;
var gender = document.querySelector('input[name="genderRadio"]:checked').value;
var skills = document.querySelectorAll('input[type="checkbox"]');
skills.forEach(item => {
if (item.checked){
skillsList.push(item.value);
}
})
var student = {
'name': name,
'email': email,
'website': website,
'imageLink' : imgLink,
'gender': gender,
'skills': skillsList,
}
enrolledStudents.push(student)
console.log(enrolledStudents);
const studentList = document.getElementById('student-list');
studentList.innerHTML = `${
enrolledStudents.map(student => {
var passport = student.imgLink;
return `
<div class="row" id="student-id-details" style="border: 2px solid black; border-top: none; height: 120px;">
<div class="col" style="padding-top: 10px; padding-bottom: 5px; height: 100px;">
<h6 class="card-title">${student.name}</h6>
<p class="card-text">${student.gender}<br />${student.email}<br />${student.website}<br />${student.skills}</p>
</div>
</div>
`;
}).join("")
}`
const studentImages = document.getElementById("student-images");
console.log(enrolledStudents)
studentImages.innerHTML = `${
enrolledStudents.map(student => {
return `
<div class="row" id="student-id-image" style="border: 2px solid black; border-top: none; border-left: none; height: 120px">
<div class="col" style="padding-top: 10px; padding-bottom: 6px; height: 120px; align-items: centre;">
<img src=${student.imageLink}></img>
</div>
</div>
`
}).join("")
}`
setTimeout(changeIds, 3000);
}
const changeIds = () => {
var oldId = document.getElementById("student-id-details");
oldId.id = "no-animation";
console.log(document.querySelectorAll("#student-id-details"));
console.log(document.querySelectorAll("#no-animation"));
}
I cannot use any library or framework for doing this task.
In changeIds function, I am changing the ID. When I keep adding new entries there is only 1 node in no-animation NodeList (the first entry) and after that no ID change is taking effect.
What can be the problem here?
My html code for reference -
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Student Enrollment</title>
<link href="style.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<nav class="navbar text-center" style="background-color: #59CE8F;">
<div class="container-fluid text-center">
<span class="navbar-brand mb-0 h1 text-center" style="color: white;">Student Enrollment Form</span>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col" style="height: 35px;"></div>
</div>
<div class="row">
<div class="col" style="border-right: 3px solid #59CE8F;">
<form id="student-enrollment-form">
<div class="row mb-3">
<label for="name-input" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="name-input"/>
</div>
</div>
<div class="row mb-3">
<label for="email-input" class="col-sm-2 col-form-label">E-Mail</label>
<div class="col-sm-5">
<input type="email" class="form-control" id="email-input" required/>
</div>
</div>
<div class="row mb-3">
<label for="website-input" class="col-sm-2 col-form-label">Website</label>
<div class="col-sm-5">
<input type="url" class="form-control" id="website-input" required/>
</div>
</div>
<div class="row mb-3">
<label for="imglink-input" class="col-sm-2 col-form-label">Img Link</label>
<div class="col-sm-5">
<input type="url" class="form-control" id="imglink-input" required/>
</div>
</div>
<fieldset class="row mb-3">
<legend class="col-form-label col-sm-2 pt-0">Gender</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="genderRadio" id="gridRadios1" value="male" id="male-input" checked>
<label class="form-check-label" for="gridRadios1">
Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="genderRadio" id="gridRadios2" value="female" id="female-input">
<label class="form-check-label" for="gridRadios2">
Female
</label>
</div>
</div>
</fieldset>
<div class="row mb-3">
<label for="skills" class="col-sm-2 col-form-control">Skills</label>
<div class="col-sm-2">
<input class="form-check-input" type="checkbox" id="java-gridCheck" value="Java">
<label class="form-check-label" for="gridCheck">
JAVA
</label>
</div>
<div class="col-sm-2">
<input class="form-check-input" type="checkbox" id="html-gridCheck" value="HTML">
<label class="form-check-label" for="gridCheck">
HTML
</label>
</div>
<div class="col-sm-2">
<input class="form-check-input" type="checkbox" id="css-gridCheck" value="CSS">
<label class="form-check-label" for="gridCheck">
CSS
</label>
</div>
</div>
<div class="row mb-3">
<div class="col-4">
<button type="button" class="btn btn-primary" onclick="getStudentDetails(event)">Enroll Student</button>
</div>
<div class="col-2" style="margin-left: -30px;">
<button type="clear" class="btn btn-danger">Clear</button>
</div>
</div>
</div>
</form>
<div class="col" id="student-ids">
<h3 id="right-col-header">Enrolled Students</h3>
<div class="row mb-4"></div>
<div class="row">
<div class="col-2"></div>
<div class="col-5" style="text-align: left;">
<div class="row" style="border: 2px solid black;">
<div class="col">
Description
</div>
</div>
<div class="student-list-division" id="student-list">
</div>
</div>
<div class="col-3" style="align-items: centre;">
<div class="row" style="border: 2px solid black; border-left: none;">
<div class="col">
Image
</div>
</div>
<div class="student-list-images" id="student-images">
</div>
</div>
<div class="col-2"></div>
</div>
</div>
</div>
</div>
<script src="script_js.js"></script>
</body>
</html>
My css code for animation -
#right-col-header{
text-align: center;
}
ul{
padding-left: 0;
list-style-type: none;
}
p{
font-size: 13px;
}
img{
height: 6em;
width: 6em;
}
#student-ids{
height: 90%;
overflow-x: auto;
}
#student-id-image{
animation: fadeIn 2s;
-webkit-animation: fadeIn 2s;
}
#keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
#student-id-details{
animation: fadeIn 2s;
-webkit-animation: fadeIn 2s;
}
I would appreciate different solutions for achieving animations in new entries only too.
You have to apply fade-in-animation class to new entry, current logic apply animation class to all list.
I just update your code with minor changes, i hope it'll help you out. Thank You
var enrolledStudents = [];
let form = document.getElementById("student-enrollment-form");
const getStudentDetails = (event) => {
event.preventDefault();
// This is the important part, test if form is valid
if (form.checkValidity() === false){
// This is the magic function that displays the validation errors to the user
form.reportValidity();
return;
}
var skillsList = [];
var name = document.getElementById("name-input").value;
var email = document.getElementById("email-input").value;
var website = document.getElementById("website-input").value;
var imgLink = document.getElementById("imglink-input").value;
var gender = document.querySelector('input[name="genderRadio"]:checked').value;
var skills = document.querySelectorAll('input[type="checkbox"]');
skills.forEach(item => {
if (item.checked){
skillsList.push(item.value);
}
})
var student = {
'name': name,
'email': email,
'website': website,
'imageLink' : imgLink,
'gender': gender,
'skills': skillsList,
}
enrolledStudents.push(student)
console.log(enrolledStudents);
const studentList = document.getElementById('student-list');
studentList.innerHTML = `${
enrolledStudents.map((student, index) => {
var passport = student.imgLink;
return `
<div class="row ${enrolledStudents.length === (index + 1) ? 'fade-in-animation' : ''}" style="border: 2px solid black; border-top: none; height: 120px;">
<div class="col" style="padding-top: 10px; padding-bottom: 5px; height: 100px;">
<h6 class="card-title">${student.name}</h6>
<p class="card-text">${student.gender}<br />${student.email}<br />${student.website}<br />${student.skills} ${index}</p>
</div>
</div>
`;
}).join("")
}`
const studentImages = document.getElementById("student-images");
console.log(enrolledStudents)
studentImages.innerHTML = `${
enrolledStudents.map((student, index) => {
return `
<div class="row ${enrolledStudents.length === (index + 1) ? 'fade-in-animation' : ''}" style="border: 2px solid black; border-top: none; border-left: none; height: 120px">
<div class="col" style="padding-top: 10px; padding-bottom: 6px; height: 120px; align-items: centre;">
<img src=${student.imageLink}></img>
</div>
</div>
`
}).join("")
}`
}
#right-col-header{
text-align: center;
}
ul{
padding-left: 0;
list-style-type: none;
}
p{
font-size: 13px;
}
img{
height: 6em;
width: 6em;
}
#student-ids{
height: 90%;
overflow-x: auto;
}
#keyframes fadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
.fade-in-animation{
animation: fadeIn 2s;
-webkit-animation: fadeIn 2s;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Student Enrollment</title>
<link href="style.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<nav class="navbar text-center" style="background-color: #59CE8F;">
<div class="container-fluid text-center">
<span class="navbar-brand mb-0 h1 text-center" style="color: white;">Student Enrollment Form</span>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col" style="height: 35px;"></div>
</div>
<div class="row">
<div class="col" style="border-right: 3px solid #59CE8F;">
<form id="student-enrollment-form">
<div class="row mb-3">
<label for="name-input" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="name-input"/>
</div>
</div>
<div class="row mb-3">
<label for="email-input" class="col-sm-2 col-form-label">E-Mail</label>
<div class="col-sm-5">
<input type="email" class="form-control" id="email-input" required/>
</div>
</div>
<div class="row mb-3">
<label for="website-input" class="col-sm-2 col-form-label">Website</label>
<div class="col-sm-5">
<input type="url" class="form-control" id="website-input" required/>
</div>
</div>
<div class="row mb-3">
<label for="imglink-input" class="col-sm-2 col-form-label">Img Link</label>
<div class="col-sm-5">
<input type="url" class="form-control" id="imglink-input" required/>
</div>
</div>
<fieldset class="row mb-3">
<legend class="col-form-label col-sm-2 pt-0">Gender</legend>
<div class="col-sm-10">
<div class="form-check">
<input class="form-check-input" type="radio" name="genderRadio" id="gridRadios1" value="male" id="male-input" checked>
<label class="form-check-label" for="gridRadios1">
Male
</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="genderRadio" id="gridRadios2" value="female" id="female-input">
<label class="form-check-label" for="gridRadios2">
Female
</label>
</div>
</div>
</fieldset>
<div class="row mb-3">
<label for="skills" class="col-sm-2 col-form-control">Skills</label>
<div class="col-sm-2">
<input class="form-check-input" type="checkbox" id="java-gridCheck" value="Java">
<label class="form-check-label" for="gridCheck">
JAVA
</label>
</div>
<div class="col-sm-2">
<input class="form-check-input" type="checkbox" id="html-gridCheck" value="HTML">
<label class="form-check-label" for="gridCheck">
HTML
</label>
</div>
<div class="col-sm-2">
<input class="form-check-input" type="checkbox" id="css-gridCheck" value="CSS">
<label class="form-check-label" for="gridCheck">
CSS
</label>
</div>
</div>
<div class="row mb-3">
<div class="col-4">
<button type="button" class="btn btn-primary" onclick="getStudentDetails(event)">Enroll Student</button>
</div>
<div class="col-2" style="margin-left: -30px;">
<button type="clear" class="btn btn-danger">Clear</button>
</div>
</div>
</div>
</form>
<div class="col" id="student-ids">
<h3 id="right-col-header">Enrolled Students</h3>
<div class="row mb-4"></div>
<div class="row">
<div class="col-2"></div>
<div class="col-5" style="text-align: left;">
<div class="row" style="border: 2px solid black;">
<div class="col">
Description
</div>
</div>
<div class="student-list-division" id="student-list">
</div>
</div>
<div class="col-3" style="align-items: centre;">
<div class="row" style="border: 2px solid black; border-left: none;">
<div class="col">
Image
</div>
</div>
<div class="student-list-images" id="student-images">
</div>
</div>
<div class="col-2"></div>
</div>
</div>
</div>
</div>
</body>
</html>

changing input value of one field when another is typed not working for multiple fields

i have a website where i have a form, the form has 3 fields which can be addedd multiple times on click, my code is like below:
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $("#niy");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Service Type</label><input type="text" class="form-control" id="client_type" required name="service[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Price</label><input type="text" class="form-control" id="client_type" required name="price[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="client_type">Total</label><input type="text" class="form-control" id="total" required name="total[]"></div></div>'); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
$('input[name="price[]"]').change(function() {
$('input[name="total[]"]').val($(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row container1">
<div class="col-lg-4 col-sm-6">
<!-- Form -->
<div class="mb-4">
<label for="client_type">Service Type</label>
<input type="text" class="form-control" id="client_type" required name="service[]">
</div>
</div>
<div class="col-lg-4 col-sm-6">
<!-- Form -->
<div class="mb-4">
<label for="client_type">Price</label>
<input type="text" class="form-control" id="client_type" required name="price[]">
</div>
</div>
<div class="col-lg-4 col-sm-6">
<!-- Form -->
<div class="mb-4">
<label for="client_type">Total</label>
<input type="text" class="form-control" id="client_type" required name="total[]">
</div>
</div>
</div>
<a id="niy" class="btn btn-warning" style="color:white">Add New Service Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</a>
i want the total field to show the value from its respective price field, however here only first row does that, can anyone please tell me how to fix this, thanks in advance
The main issue in your code is because you only bind the change event which updates the value of the fields when the page first loads. This ignores all the fields which are added dynamically. To fix this use delegated event handlers - exactly as you are for the .delete button.
That being said, it's worth noting that there's several other issues which need to be addressed:
Don't repeat the same id attribute value in the DOM. They need to be unique. Also, don't use id at all in content which can be repeated dynamically. Use class attributes instead.
Don't use inline styling with the style attribute. It's bad practice to put one type of code in another, eg. CSS in your HTML, or HTML in your JS. In this case use an external stylesheet.
Similarly, don't put HTML in your JS. Clone existing content instead of dumping a lot of HTML in the JS. In your original, if you changed the HTML template, then you'd need to also remember to update the JS file too. Using cloning avoids this problem.
Don't double-wrap your jQuery objects. Eg. add_button is already a jQuery object, you don't need to use $(add_button). It's worth prefixing variable names that hold jQuery objects with $ for this reason.
Don't use global variables where possible. They're bad practice for a variety of reasons, not least of which is that they lead to more length and harder to maintain code. A better approach in this case is to retrieve the number of elements already existing in the DOM and compare that to the known limit.
With all that said, here's a working demo:
jQuery($ => {
var max_fields = 10;
var $container = $(".container");
var $add_button = $("#niy");
$add_button.on('click', e => {
e.preventDefault();
if ($('.row').length >= max_fields) {
alert('You Reached the limits');
return;
}
let $newContent = $('.row:first').clone().appendTo($container);
$newContent.find(':input').val('');
});
$container.on("click", ".delete", e => {
e.preventDefault();
$(e.target).closest('.row').remove();
})
$container.on('change', '.price', e => {
$(e.target).closest('.row').find('.total').val(e.target.value);
});
});
body {
background-color: #CCC;
}
#niy {
color: white;
}
#niy span {
font-size: 16px;
font-weight: bold;
}
label {
width: 100px;
display: inline-block;
}
.row:first-child .delete {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-lg-4 col-sm-6">
<div class="mb-4">
<label for="client_type">Service Type</label>
<input type="text" class="form-control service" required name="service[]">
</div>
</div>
<div class="col-lg-4 col-sm-6">
<div class="mb-4">
<label for="client_type">Price</label>
<input type="text" class="form-control price" required name="price[]">
</div>
</div>
<div class="col-lg-4 col-sm-6">
<div class="mb-4">
<label for="client_type">Total</label>
<input type="text" class="form-control total" required name="total[]">
</div>
</div>
Delete
</div>
</div>
<a id="niy" class="btn btn-warning">
Add New Service Field
<span>+ </span>
</a>
try below snippet once, you will find runtime oninput updating totals. That imrpoves user experience.
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $("#niy");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields)
{
x++;
$(wrapper).append('<div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="service_type'+x+'">Service Type</label><input type="text" class="form-control service_type" data-id="'+x+'" id="service_type'+x+'" required name="service[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="price_type'+x+'">Price</label><input type="text" class="form-control price_type" data-id="'+x+'" id="price_type'+x+'" required name="price[]"></div></div><div class="col-lg-4 col-sm-6"><div class="mb-4"><label for="total_type'+x+'">Total</label><input type="text" class="form-control" data-id="'+x+'" id="total_type'+x+'" readonly name="total[]"></div></div>');
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
$(document).on('input', '.service_type, .price_type', function(){
var id = $(this).attr('data-id');
if(id > 0)
{
var service_type = parseFloat($('#service_type'+id).val()) || 0;
var price_type = parseFloat($('#price_type'+id).val()) || 0;
var total_type = service_type + price_type;
$('#total_type'+id).val(total_type.toFixed(2));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row container1">
<div class="col-lg-4 col-sm-6">
<!-- Form -->
<div class="mb-4">
<label for="service_type1">Service Type</label>
<input type="text" class="form-control service_type" id="service_type1" data-id="1" required name="service[]">
</div>
</div>
<div class="col-lg-4 col-sm-6">
<!-- Form -->
<div class="mb-4">
<label for="price_type1">Price</label>
<input type="text" class="form-control price_type" id="price_type1" data-id="1" required name="price[]">
</div>
</div>
<div class="col-lg-4 col-sm-6">
<!-- Form -->
<div class="mb-4">
<label for="total_type1">Total</label>
<input type="text" class="form-control" id="total_type1" data-id="1" readonly name="total[]">
</div>
</div>
</div>
<a id="niy" class="btn btn-warning">Add New Service Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</a>

How to enable invisible ReCAPTCHA on checkbox onclick

I am struggling with an recaptcha issue on my local. I am trying to build a register form. All examples about recaptcha are about buttons. What I want is to pop-up recaptcha modal to user when he/she clicks on checkbox which says ' I have read and accept terms and conditions.' When he/she solves recaptcha then checkbox would be checked. Here what I am trying
It did not work, after that I tried this onClick method did not work because it writes Script Error on console.
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function controlFunction() {
grecaptcha.render()
}
</script>
</head>
<body>
<div id='checkbox-form' action="?" method="POST">
<input onclick="controlFunction()" type="checkbox" class="g-recaptcha" data-sitekey="MY_LOCAL_KEY" data-callback='onClick' id="termsConditions" class="termsOkay">
<label for="termsConditions" generated="true">I have read and accepted <a target="_blank" href="/sales-terms-and-conditions/">Terms and Conditions</a> </label>
<br/>
</div>
</body>
</html>
I know code is a mess because I tried so many different thing and this is what I got. I am really confused. All I want is if user checks the checkbox let captcha popup. When solved, checkbox is checked. How can I do it? I tried to use handleChange but could not make it either.
Here is my whole code:
<?php
// Google reCaptcha secret key
$secretKey = "REMOVEDCONTENTBYME";
$statusMsg = '';
if(isset($_POST['submit'])){
if(isset($_POST['captcha-response']) && !empty($_POST['captcha-response'])){
// Get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['captcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//Contact form submission code goes here ...
$statusMsg = 'Your contact request have submitted successfully.';
}else{
$statusMsg = 'Robot verification failed, please try again.';
}
}else{
$statusMsg = 'Robot verification failed, please try again.';
}
}
?>
<?php $businessTypes = [
'Full Service',
'Quick Service',
'Bars and Clubs',
]; ?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="https://gmpg.org/xfn/11">
<link rel="stylesheet" href="https://use.typekit.net/fom8rbw.css">
<link rel="stylesheet" href="/wp-content/themes/thegem/css/main.css">
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback" async defer></script>
<script>
var onloadCallback = function() {
grecaptcha.execute();
};
function setResponse(response) {
document.getElementById('captcha-response').value = response;
}
</script>
<?php wp_head(); ?>
<style>
html, body, .site-content {
padding: 0 !important;
margin: 0 !important;
background-color:#fff;
}
.textwidget a {
font-family: 'proxima-nova',sans-serif !important;
}
.d-none {
display: none !important;
}
.section{
background-color: #ffffff;
}
.demo-form input, .demo-form select, .demo-form textarea {
border: 1px solid #e31d93;
}
.demo-form input {
text-indent: 12px;
}
.form-control {
display: block;
width: 100%;
height: calc(1.5em + 1.3rem + 2px);
font-size: 1.6rem;
font-weight: 400;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .40rem;
}
.row-m-t{
margin-top : 0px
}
</style>
<div id="page" class="site">
<div id="content" class="site-content">
<div id="primary" class="content-area demo-form">
<main id="main" class="site-main">
<div class="section blog-content">
<div class="container">
<div class="text-center"><h1 style="padding-bottom: 10rem;">Request FOrm</h1></div>
<div class="row justify-content-md-center">
<div class="col-md-6">
<form class="demo-form" method="post" onsubmit="return false" style=" position: relative; bottom: 35px; ">
<div class="row">
<div class="col-md-6 border-danger form-group">
<input type="text" class="form-control validate" data-validate="validateText" name="firstName" placeholder="First name" style=" background-color: #fff;">
</div>
<div class="col-md-6 form-group">
<input type="text" class="form-control validate" data-validate="validateText" name="lastName" placeholder="Last name"style=" background-color: #fff;">
</div>
</div>
<div class="row row-m-t">
<div class="col-md-6 form-group">
<input type="text" class="form-control validate" data-validate="validateText" name="companyName" placeholder="Group name"style=" background-color: #fff;">
</div>
<div class="col-md-6 form-group">
<input type="text" class="form-control validate" data-validate="validatePhone" name="phoneNumber" placeholder="Phone number"style=" background-color: #fff;">
</div>
</div>
<div class="row row-m-t">
<div class="col-md-12 form-group">
<input type="text" class="form-control validate" data-validate="validateEmail" name="emailAddress" placeholder="email"style=" background-color: #fff;">
</div>
</div>
<div class="row row-m-t">
<div class="col-md-12 form-group">
<select name="businessType" id="businessType" class="form-control validate" data-validate="validateText">
<option value=""><?php _e('Select Your Business Type...', 'myfirm'); ?></option>
<?php foreach ($businessTypes as $type): ?>
<option><?php _e($type, 'myfirm'); ?></option>
<?php endforeach ;?>
</select>
</div>
</div>
<div class="row radio">
<div class="col-md-6">
<p style="font-size:13px;"><?php _e('Validate by', 'myfirm'); ?>:</p>
</div>
</div>
<div class="row radio" style="font-size:13px;">
<div class="col-md-8">
<div class="custom-control custom-radio custom-control-inline col-md-6">
<input type="radio" id="validateByPhone" checked value="phoneNumber" name="validateBy" class="custom-control-input">
<label style="font-size:12px; transform: scale(1.2);
position: relative;
left: 1rem;" class="custom-control-label" for="validateByPhone"><?php _e('Phone Number', 'myfirm'); ?></label>
</div>
<div class="custom-control custom-radio custom-control-inline col-md-6">
<input type="radio" id="validateByEmailAddess" value="emailAddress" name="validateBy" class="custom-control-input">
<label style="font-size:12px; transform: scale(1.2);
position: relative;
left: 1rem; top:5px;" class="custom-control-label" for="validateByEmailAddess"><?php _e('Email Address', 'myfirm'); ?></label>
</div>
</div>
</div>
<br>
<div class="row radio">
<div class="col-md-12" style="position: relative;right: 13px;">
<div class="custom-radio custom-control-inline col-md-12">
<div class="g-recaptcha" data-sitekey="REMOVEDCONTENTBYME" data-badge="inline" data-size="invisible" data-callback="setResponse"></div>
<input type="hidden" id="captcha-response" name="captcha-response" />
<input type="checkbox" id="captcha-response" class="termsOkay" style=" background-color: #fff;">
<label for="captcha-response" class="error" generated="true" style="position: relative;bottom: 5px;"> I have read and accepted <a target="_blank" href="/sales-terms-and-conditions/">Terms and Conditions</a> </label>
</div>
</div>
</div>
<div class="verification-code d-none">
<div class="col">
<label for="verification-code"><?php _e('A verification code has been sent to your phone number!', 'myfirm') ?></label>
<input type="text" class="form-control" name="code" placeholder="<?php _e('Verification code', 'myfirm');?>">
</div>
</div>
<div class="row row-m-t">
<div class="col">
<button class="btn btn-myfirm send-verification-code" disabled="disabled" style="width: 100% !important;height: 125% !important;font-size: 15px;"><?php _e('Request a Demo', 'myfirm'); ?></button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</main>
</div>
</main>
</div>
</div>
</div>
</body>
<script>
function admSelectCheck(obj)
{
var nameSelect = obj.value;
console.log(nameSelect);
if(nameSelect){
admOptionValue = 'United States of America|+1';
if(admOptionValue == nameSelect){
document.getElementById("admDivCheck").style.display = "block";
}
else{
document.getElementById("admDivCheck").style.display = "none";
}
}
else{
document.getElementById("admDivCheck").style.display = "block";
}
}
</script>
<script>
jQuery(function() {
jQuery('input.termsOkay').change(function() {
if (!jQuery('input.termsOkay').is(':checked')) {
jQuery('.send-verification-code').prop('disabled', true)
} else{
jQuery('.send-verification-code').prop('disabled', false)
}
})
})
</script>
</html>
The part I am trying to make it work
<div class="row radio">
<div class="col-md-12" style="position: relative;right: 13px;">
<div class="custom-radio custom-control-inline col-md-12">
<div class="g-recaptcha" data-sitekey="REMOVEDCONTENTBYME" data-badge="inline" data-size="invisible" data-callback="setResponse"></div>
<input type="hidden" id="captcha-response" name="captcha-response" />
<input type="checkbox" id="captcha-response" class="termsOkay" style=" background-color: #fff;">
<label for="captcha-response" class="error" generated="true" style="position: relative;bottom: 5px;"> I have read and accepted <a target="_blank" href="/sales-terms-and-conditions/">Terms and Conditions</a> </label>
</div>
</div>
</div>

How to add 2 new input from 1 button?

Hi i have my code here where now i would like 1 button click to add a input box to contact Name and contact No
Example of image when user click on the add more field
Currently what i have is 2 different input fields where i have hidden the button for the contact No:
Originally i am allow to press on the 2 button to display a newinput but now i would like that 1 button input appear for each new input for contact name and contact no how can i combine it?
Here my code snippet for the code
// Script on create a new input box 1 for Contact: Name
const $container1 = $('#contactContainername')
$(".remove1").eq(0).hide()
$container1.on('click', ".no", function(e) {
const add1 = $(this).is(".add1")
const $input1 = $container1.find(".contactname");
const len1 = $input1.length;
if (add1) {
const $newInput1 = $input1.eq(0).clone(true)
$newInput1.find("[name=contactname]")
.attr("id", `new_${$input1.length}`)
.val("");
$container1.append($newInput1);
$newInput1.find(".add1").remove()
$newInput1.find(".remove1").show()
// $newPhone.find(".add").hide(len>0)
} else {
$(this).closest(".contactname").remove()
}
})
// Script on create a new input box 2 for Contact: No
const $container = $('#contactContainer')
$(".remove").eq(0).hide()
$container.on('click', ".ar", function(e) {
const add = $(this).is(".add");
const $input = $container.find(".contact");
const len = $input.length;
if (add) {
const $newInput = $input.eq(0).clone(true)
$newInput.find("[name=contact]")
.attr("id", `new_${$input.length}`)
.val("");
$container.append($newInput);
$newInput.find(".add").remove()
$newInput.find(".remove").show()
// $newPhone.find(".add").hide(len>0)
} else {
$(this).closest(".contact").remove()
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input type="button" class="no add1" value="Add More Field" style="cursor: pointer;">
<span class="no remove1"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact No:</label>
<div class="col-4" id="contactContainer">
<div class="flex contact" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontact" name="contact" type="text" class="form-control" placeholder="9343****" pattern="\b\d{8}\b" required>
<input type="button" class="ar add" value="Add More Field" style="cursor: pointer;" hidden>
<!-- <span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus" ></i></label></span> -->
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>
I've just changed your code,I've added onclick event to add more field button
function addMoreField() {
const $contactContainername = $('#contactContainername');
const $contactContainerNo = $('#contactContainer');
const $contactNameinput = $contactContainername.find(".contactname");
const $contactNoInput = $contactContainerNo.find(".contact");
const $newContactNameinput = $contactNameinput.eq(0).clone(true);
$newContactNameinput.find("[name=contactname]")
.attr("id", `contactNameInput_${$contactNameinput.length}`)
.val("");
$newContactNameinput.attr("id", `contactName_${$contactNameinput.length}`);
const removeButton = $newContactNameinput.find(".removeButton");
removeButton.attr("onclick", `removeField(${$contactNameinput.length})`);
removeButton.show();
const $newContactNoinput = $contactNoInput.eq(0).clone(true);
$newContactNoinput.attr("id", `contactNo_${$contactNameinput.length}`);
$newContactNoinput.find("[name=contact]")
.attr("id", `contactNoInput_${$contactNoInput.length}`)
.val("");
$contactContainername.append($newContactNameinput);
$contactContainerNo.append($newContactNoinput);
}
function removeField(id) {
if (id === 0) return;
const $contactContainername = $('#contactContainername');
const $contactContainerNo = $('#contactContainer');
const $contactNameinput = $contactContainername.find(`#contactName_${id}`);
const $contactNoinput = $contactContainerNo.find(`#contactNo_${id}`);
$contactNameinput.remove();
$contactNoinput.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" onclick='addMoreField()' class="no add1" value="Add More Field" style="cursor: pointer;">
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact Name:</label>
<div class="col-4" id="contactContainername">
<div id="contactName_0" class="flex contactname" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontactname" name="contactname" type="text" class="form-control" placeholder="Name" required>
<input class="removeButton" type="button" onclick='removeField(0)' value="Remove" style="cursor: pointer;display:none">
</div>
</div>
</div>
<div class="form-group row">
<label for="contact" class="col-2 col-form-label">Contact No:</label>
<div class="col-4" id="contactContainer">
<div id="contactNo_0" class="flex contact" style="margin-bottom:10px;">
<input style="margin-right: 10px; width: 200px;" id="validationcontact" name="contact" type="text" class="form-control" placeholder="9343****" pattern="\b\d{8}\b" required>
<input type="button" class="ar add" value="Add More Field" style="cursor: pointer;" hidden>
<!-- <span class="ar add"><label style="cursor: pointer; padding-top: 5px;"><i data-feather="plus" ></i></label></span> -->
<span class="ar remove"><label style="cursor: pointer; padding-top: 5px;"><i style="width: 20px; height: 20px; color: lightseagreen;"data-feather="x"></i></label></span>
</div>
</div>
</div>

How to change the font color of both label and input onfocus of an inputbox and change it back on blur

I have attached a plunker link for what ive did
http://plnkr.co/edit/JlARpFiVEFryAhgxgWJm?p=preview
input[attribute=flag]:focus {
color: red;
}
input[attribute=flag]{
color: green;
}
<form name="Form" class="form-horizontal " style="padding-left:9%;">
<div class="form-group">
<div class="col-sm-11 ">
<label for="inputEmail" class="control-label" >Email</label><br>
<input type="email" attribute=flag class="form-control inputBorderStyle box" id="usernameLogin" name="username" required="">
</div>
</div>
<div class="form-group">
<div class="col-sm-11 "><br>
<label for="inputPassword" class="control-label">Password</label><br>
<input type="password" attribute=flag class="form-control inputBorderStyle box" id="usernamePassword" name="password" required="">
</div>
</div>
<div class="form-group last">
<div class="col-sm-11"><br>
<button type="submit" id="loginButton" class="btn btn-myprimary">LOG IN</button>
</div>
</div>
</form>
Onfocus of input i want to change the color of both label and input.
Right now im able to chnage the color of input but how to change label color onfocus and change it back to other color on blur.If anyone has idea please suggest.
Thanks in advance
Try with focusin and focusout effect.
Jsfiddle
$(document).ready(function() {
$("input").on("focusin", function() {
$(this).siblings("label").css("color","red");
$(this).css("color","red");
});
$("input").on("focusout", function() {
$(this).siblings("label").css("color","green");
$(this).css("color","green");
})
})
Try this code:
$(function(){
$('input[type=email], input[type=password]').focus(function(){
$(this).closest('div').find('label').css({color:'red'})
});
$('input[type=email], input[type=password]').blur(function(){
$(this).closest('div').find('label').css({color:'#000'})
});
});
/* Styles go here */
.inputBorderStyle{
border:0;
box-shadow:none !important;
border-bottom:1px solid black;
border-radius:0px;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
input[attribute=flag]:focus {
color: red;
}
input[attribute=flag]{
color: green;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script src="script.js"></script>
</head>
<body>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form name="Form" class="form-horizontal " style="padding-left:9%;">
<div class="form-group">
<div class="col-sm-11 ">
<label for="inputEmail" class="control-label" >Email</label><br>
<input type="email" attribute=flag class="form-control inputBorderStyle box" id="usernameLogin" name="username" required="">
</div>
</div>
<div class="form-group">
<div class="col-sm-11 "><br>
<label for="inputPassword" class="control-label">Password</label><br>
<input type="password" attribute=flag class="form-control inputBorderStyle box" id="usernamePassword" name="password" required="">
</div>
</div>
<div class="form-group last">
<div class="col-sm-11"><br>
<button type="submit" id="loginButton" class="btn btn-myprimary">LOG IN</button>
</div>
</div>
</form>
</body>
</html>
</body>
</html>
The focus and blurevents allow you to bind corresponding events when an HTML element receives focus and is out of focus.
You can add onfocus and onblur event on the inputs (without jQuery)
var userField = document.getElementById("usernameLogin");
userField.addEventListener("focus",function(){
this.parent.getElementsByTagName("label")[0].style.color = 'red';
});
userField.addEventListener("blur",function(){
this.parent.getElementsByTagName("label")[0].style.color = 'green';
});
Use jquery, to attach event focus to the input and the label after that add class to input and to the the label and detach the class on blur
$("input").on("focus",function(){
$(this).addClass("focusclass")
$(this).closest(".col-md-11").first().addClass("Labelfocusclass")
}
$("input").on("blur",function(){
$(this).removeClass("focusclass")
$(this).closest(".col-md-11").first().removeClass("Labelfocusclass")
}
JavaScript Solution:
Use onfocus and onblur events like this:
function changeColor(obj) {
document.getElementById(obj).style.color = "red";
}
function removeColor(obj) {
document.getElementById(obj).style.color = "black";
}
/* Styles go here */
.inputBorderStyle {
border: 0;
box-shadow: none !important;
border-bottom: 1px solid black;
border-radius: 0px;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
input[attribute=flag]:focus {
color: red;
}
input[attribute=flag] {
color: green;
}
<form name="Form" class="form-horizontal " style="padding-left:9%;">
<div class="form-group">
<div class="col-sm-11 "><br>
<label for="inputEmail" class="control-label" id="email">Email</label><br>
<input type="email" attribute=flag class="form-control inputBorderStyle box" id="usernameLogin" name="username" required="" onfocus="changeColor('email')" onblur="removeColor('email')">
</div>
</div>
<div class="form-group">
<div class="col-sm-11 "><br>
<label for="inputPassword" class="control-label" id="password">Password</label><br>
<input type="password" attribute=flag class="form-control inputBorderStyle box" id="usernamePassword" name="password" required="" onfocus="changeColor('password')" onblur="removeColor('password')">
</div>
</div>
<div class="form-group last">
<div class="col-sm-11"><br>
<button type="submit" id="loginButton" class="btn btn-myprimary">LOG IN</button>
</div>
</div>
</form>
check my fiddle mate and let me know i have done this using jquery
https://jsfiddle.net/estvwpvz/5/
var divs = document.getElementsByClassName('inputBorderStyle');
for(var i = 0; i < divs.length; i++)
{
document.getElementsByClassName('inputBorderStyle')[i].addEventListener("focusin", myFunction);
document.getElementsByClassName('inputBorderStyle')[i].addEventListener("focusout", myFunctionout);
}
function myFunction() {
this.style.color= "red";
this.parentElement.getElementsByTagName("label")[0].style.color = 'red';
}
function myFunctionout() {
this.style.color= "white";
this.parentElement.getElementsByTagName("label")[0].style.color = 'black';
}

Categories