jQuery add class to fieldset if input is have error class - javascript

How can I add "error" class to the fieldset(s) too if their input's are have "error" class?
I'm trying to achieve this as the following, but it's adding the "error" class to every fieldsets no matter if the input is have the "error" class or not.
$('#submit').click(function(e) {
e.preventDefault();
$('input').each(function() {
if($(this).hasClass("error")){
$("fieldset").addClass("error");
}
});
});
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="form-holder">
<fieldset>
<legend>First name</legend>
<input type="text" class="form-control" name="firstname" placeholder="First name" required>
</fieldset>
</div>
<div class="form-holder">
<fieldset>
<legend>Last name</legend>
<input type="text" class="form-control error" name="lastname" placeholder="Last name" required>
</fieldset>
</div>
<div class="form-holder">
<fieldset>
<legend>Email</legend>
<input type="email" class="form-control error" name="email" placeholder="Email" required>
</fieldset>
</div>
<input type="submit" id="submit" value="Send">

The code is doing what you are telling it to. When you say $("fieldset").addClass("error"); it means to add the error class to all fieldset elements.
What you need to do is find the fieldset that is the parent of the input which has the error class. In your example this would be:
$('#submit').click(function(e) {
e.preventDefault();
$('input').each(function() {
if($(this).hasClass("error")){
$(this).closest("fieldset").addClass("error");
}
});
});
The closest() method will travel up the DOM looking for the first element which matches the selector. So it should find the closest fieldset parent to the input.

Try targeting the parent fieldset explicitly by using the parent selector. (And also cache the jQuery'd this var.)
$('#submit').click(function(e) {
e.preventDefault();
$('input').each(function() {
var $this = $(this);
if ($this.hasClass("error")) {
$this.parent("fieldset").addClass("error");
}
});
});
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="form-holder">
<fieldset>
<legend>First name</legend>
<input type="text" class="form-control" name="firstname" placeholder="First name" required>
</fieldset>
</div>
<div class="form-holder">
<fieldset>
<legend>Last name</legend>
<input type="text" class="form-control error" name="lastname" placeholder="Last name" required>
</fieldset>
</div>
<div class="form-holder">
<fieldset>
<legend>Email</legend>
<input type="email" class="form-control error" name="email" placeholder="Email" required>
</fieldset>
</div>
<input type="submit" id="submit" value="Send">

Related

jQuery: Adding html elements dynamically using jquery

I want to add some html elements dynamically using jQuery inside a form tag but it is not working .
$(document).ready(function() {
var requirements = 0;
var container = $(document.createElement('div').addClass('form-group'));
$('#add-req').click(function() {
if (requirements <= 15) {
requirements = requirements + 1;
$(container).append('<input type="text" name="name" class="form-control" placeholder="Requirement" title="Enter next requirement" required="">');
$('#requirement-div').after(container);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register-form pt-md-4" id="requirement-div">
<form action="#" method="post">
<div class="styled-input form-group">
<input type="text" class="form-control" placeholder="Your Name" name="Course name" required="">
</div>
<div class="styled-input">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Requirement" title="Please enter requirement" required="">
</div>
<input type="button" value="add Requirements" id="add-req">
<input type="submit" value="Submit">
</div>
</form>
</div>
when I click add requirement button it should create another div tag and input element inside form element.
Just replace the code $(document.createElement('div').addClass('form-group')); to $(document.createElement('div')).addClass('form-group');
Try the following
We can directly Insert a html element to the targer Element as follow
$(document).ready(function(){
var requirements=0;
$('#add-req').click(function(){
if(requirements<=15){
requirements=requirements+1;
$('#requirement-div').after('<div class="form-group"><input type="text" name="name" class="form-control" placeholder="Requirement" title="Enter next requirement" required=""></div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register-form pt-md-4" id="requirement-div">
<form action="#" method="post" >
<div class="styled-input form-group">
<input type="text" class="form-control" placeholder="Your Name" name="Course name" required="">
</div>
<div class="styled-input">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Requirement" title="Please enter requirement" required="">
</div>
<input type="button" value="add Requirements" id="add-req">
<input type="submit" value="Submit">
</div>
</form>
</div>
you mixing between JS and JQuery, where document.createElemet('div') is a JS function while addClass is a JQuery function.
$(document).ready(function(){
var requirements = 0;
var container=$('<div>').addClass('form-group');
$('#add-req').click(function(){
if(requirements<=15){
requirements=requirements+1;
container.append('<input type="text" name="name" class="form-control" placeholder="Requirement" title="Enter next requirement" required="">');
$(this).before(container);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="register-form pt-md-4" id="requirement-div">
<form action="#" method="post" >
<div class="styled-input form-group">
<input type="text" class="form-control" placeholder="Your Name" name="Course name" required="">
</div>
<div class="styled-input">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Requirement" title="Please enter requirement" required="">
</div>
<input type="button" value="add Requirements" id="add-req">
<input type="submit" value="Submit">
</div>
</form>
</div>
Replace the Below Code
<script>
$(document).ready(function(){
var requirements=0;
var container=$(document.createElement('div')).addClass('form-group');
$('#add-req').click(function(){
if(requirements<=15){
requirements=requirements+1;
$(container).append('<input type="text" name="name" class="form-control" placeholder="Requirement" title="Enter next requirement" required="">');
$('#requirement-div').after(container);
}
});
});
</script>
I wrote a script here (Adding html elements dynamically using jquery) that you can test
<form action="#" method="post">
<div class="form-group">
<input type="text" class="form-control test" placeholder="Your Name" name="Course name" required="">
</div>
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Requirement" title="Please enter requirement" required="">
</div>
<div class="styled-input">
<input type="button" class="btn btn-primary" value="Add Requirements" id="add-req">
<input type="submit" class="btn btn-primary" value="Submit">
</div>
</form>
JQuery Code
$(function() {
var requirements=0;
$('#add-req').click(function(e){
e.preventDefault();
$('.test').val('Okay');
if(requirements <= 15) {
$('.styled-input').prepend('<div class="form-group"><input type="text" name="name" class="form-control" placeholder="Requirement" title="Enter next requirement" required=""></div>');
requirements++;
} else {
alert('Max requirement has been reached');
}
});
});

Generating form fields using jquery

I have a pretty basic form that allow user to post simple classified ads. It looks like this:
<form action="">
<fieldset>
<h3>Personal Informations</h3>
<input type="text" placeholder="Your Name">
<input type="text" placeholder="Your Address">
</fieldset>
<fieldset>
<h3>Car Informations</h3>
<input type="text" placeholder="Manufacturer">
<input type="text" placeholder="Model">
<input type="text" placeholder="Year">
Add More Ads
</fieldset>
</form>
I would like to allow the visitor to post more ads then one via "Add More Ads" button/link which would generate same 3 fields as much times as visitor needs ads.
What would be the simplest solution to do this? Any help/guide would be great!
Thanks!
P.S Also it would be great if the user could also remove the fields if he doesnt need them
Try this.
$('#addMOre').on('click',function(){
var self = $('.apendable').first().clone().insertAfter(".apendable:last");
$('.apendable:last input').val('');
self.append('<button class="close-info">close</button>');
$('.close-info').on('click', function(){
$(this).parent().remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<fieldset>
<h3>Personal Informations</h3>
<input type="text" placeholder="Your Name">
<input type="text" placeholder="Your Address">
</fieldset>
<fieldset id="info">
<h3>Car Informations</h3>
<div class="apendable">
<input type="text" placeholder="Manufacturer">
<input type="text" placeholder="Model">
<input type="text" placeholder="Year">
</div>
Add More Ads
</fieldset>
</form>
You can set inputs in <div class="row"> then copy first row class.
$("#addAdsFiels").click(function(){
var clone = $(this).siblings(".row:first").clone();
$(clone).find("input").val("");
$(this).before(clone);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<fieldset>
<h3>Personal Informations</h3>
<input type="text" placeholder="Your Name">
<input type="text" placeholder="Your Address">
</fieldset>
<fieldset>
<h3>Car Informations</h3>
<div class="row">
<input type="text" placeholder="Manufacturer">
<input type="text" placeholder="Model">
<input type="text" placeholder="Year">
</div>
Add More Ads
</fieldset>
</form>

preventDefault doesn't work [duplicate]

This question already has answers here:
JS & jQuery can't detect html elements, and say's they are undefined
(4 answers)
Closed 7 years ago.
I have a problem with preventDefault function. It doesn't work. Here is my JS file:
(function() {
var app = {
initialize : function () {
this.setUpListeners();
},
setUpListeners: function () {
$('form').on('submit', app.submitForm);
},
submitForm: function(e){
e.preventDefault();
}
}
app.initialize();
}());
My HTML code has 2 confirm button. Second step is hidden and should be display, when first step will be done. But I can't at least add preventDefault for first step.
Here is my HTML:
<form id="login">
<!-- #first_step -->
<div id="first_step">
<h1>Registration Form</h1>
<fieldset id="inputs">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" id="username" class="form-control" placeholder="Create a username" required="">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" placeholder="Create a password" required="">
</div>
<div class="form-group">
<label for="cpassword">Password</label>
<input type="password" name="password" id="cpassword" class="form-control" placeholder="Confirm your password">
</div>
</fieldset>
<fieldset id="actions">
<div class="form-group">
<input type="submit" class="submit" name="submit_first" id="submit_first" value="Next">
</div>
</fieldset>
</div>
<!-- #second_step -->
<div id="second_step">
<h1>Registration Form</h1>
<fieldset id="inputs">
<label>Name</label>
<input type="text" name="name" id="firstname" class="form-control" placeholder="Enter your name" autofocus="" required="">
<label>Surname</label>
<input type="text" name="surname" id="lastname" class="form-control" placeholder="Enter your last name" required="">
<label>Email</label>
<input type="email" name="email" id="email" class="form-control" placeholder="Enter your email" required="">
</fieldset>
<fieldset id="actions">
<input class="submit" type="submit" name="submit_second" id="submit_second" value="Next">
</fieldset>
</div>
</form>
I'm sorry. I'm just a beginner in js and will be very thankful if someone help me
$(function() {
var app = {
initialize : function () {
this.setUpListeners();
},
setUpListeners: function () {
$('form').on('submit', app.submitForm);
},
submitForm: function(e){
e.preventDefault();
}
}
app.initialize();
});

Javascript failing to validate form

I am having trouble pinpointing why my javascript code is failing to validate the form on the bottom. Any help is appreciated. I'm new and learning when in comes to javascript.
Here's the javascript:
<script type="text/javascript" language="javascript">
function validate(){
//Initialize array
var field = new Array;
var field = [document.getElementById('first_name'),document.getElementById('last_name'),document.getElementById('address'),document.getElementById('eadress'),document.getElementById('city'),document.getElementById('state'),document.getElementById('telephone'),document.getElementById('comments')];
//Error tracker
var error = 0;
//Validation Loop
for (i=0;i<field.length;i++)
{
if (field[i].value == "")
{
error++;
}
}
//If no errors are present, submit
if (error == 0)
{
document.contact-form.submit();
}
//Else, display alert
else {
alert("One or more fields are empty.");
return false;
}
}
Here's the form:
<div id="registration">
<form action="" method="post" onsubmit="return validate();" id="contact-form">
<h2>Contact Us
</h2>
<div>
<label for="first_name">First Name:</label>
<input id="first_name" name="first_name" type="text" class="required" />
</div>
<div>
<label for="last_name">Last Name:</label>
<input id="last_name" name="last_name" type="text" class="required" />
</div>
<div>
<label for="address">Address:</label>
<input id="address" name="address" type="text" />
</div>
<div>
<label for="city">City:</label>
<input id="city" name="city" type="text" />
</div>
<div >
<label for="state">State:</label>
<input id="state" name="state" type="text" />
</div>
<div >
<label for="zip">Zip:</label>
<input id="zip" name="zip" type="text" />
</div>
<div>
<label for="eaddress">Email address:</label>
<input id="eaddress" name="eaddress" type="text" class="required"/>
</div>
<div>
<label for="telephone">Telephone:</label>
<input id="telephone" name="telephone" type="text" />
</div>
<div>
<label>Comments:</label>
<textarea rows="4" cols="4" name="comments" id="comments" ></textarea>
</div>
<div>
<label></label>
<input id="submit" type="submit" value="Submit" />
<input id="reset" type="reset" value="Reset" />
</div>
</form>
I just corrected your code. it seems that in the array you are asking for eadress and the field is eaddress with 2 d's
In the script, you misspelt eaddress as eadress :)
You misspelled one of the fields ids in your array definition document.getElementById('eadress') is eaddress in HTML id attribute

Make form run a javascript function?

How can I make my form run a function when submit is clicked?
<form id="commentForm" name="comment">
<fieldset>
<label for="name">Name <span>(required)</span></label>
<input type="text" class="text" id="name" value="" />
<label for="email">Email <span>(will not be published) (required)</span></label>
<input type="text" class="text" id="email" value="" />
<label for="website">Website</label>
<input type="text" class="text" id="website" value="" />
<label for="message">Message <span>(required)</span></label>
<textarea id="message" class="textarea" rows="10"></textarea>
<input type="submit" name="submit" class="submit" id="submit_btn" value="Submit Comment" action="JavaScript: ajax_add_comment();">
</fieldset>
...
I am trying running the following function:
function ajax_add_comment () {
alert ("testing");
}
Use onclick attribute instead of action.
You could use jQuery, and use the .submit() function.
You can give the form an id and then attach the submit function to it.
Example:
<form id="execute"....
</form>
<script type="javascript">
$("#execute").submit(function(){
alert("i've submitted this form");
});
</script>
make sure you have included the jquery js file.
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
You can use the onsubmit event to execute JavaScript code when the form is submitted. For example:
<script>
function ajax_add_comment () {
alert ("testing");
}
</script>
<form id="commentForm" name="comment">
<fieldset>
<label for="name">Name <span>(required)</span></label>
<input type="text" class="text" id="name" value="" />
<label for="email">Email <span>(will not be published) (required)</span></label>
<input type="text" class="text" id="email" value="" />
<label for="website">Website</label>
<input type="text" class="text" id="website" value="" />
<label for="message">Message <span>(required)</span></label>
<textarea id="message" class="textarea" rows="10"></textarea>
<input type="submit" name="submit" class="submit" id="submit_btn" value="Submit Comment" onsubmit="ajax_add_comment();">
</fieldset>
Thank you!

Categories