How can I concatenate jquery strings in a function? - javascript

So I have a function that validates form inputs and I noticed I had many questions so I wanted to automate it instead of typing it manually. So I created a for loop that goes from 1 to 25 and it works. But I want to add the i to 'q' so I won't have to type 'q1', 'q2', 'q3'... But I just can't add them together.
Here's my code:
$(function () {
for (var i = 1; i <= 25; i++) {
console.log(i);
$('#form_validation').validate({
rules: {
'checkbox': {
required: true
},
'q' + i: {
required: true
}
},
highlight: function (input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function (input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function (error, element) {
$(element).parents('.form-group').append(error);
}
});
}
});
So I don't really know how and I hope you could help me.

You should use a class for this via jQuery.validator.addClassRules
$(function() {
var myform = $('#form_validation');
jQuery.validator.addClassRules("question", {
required: true
});
$.validator.messages.required = 'Well, we need to know';
var myvalidator = $('#form_validation').validate({
rules: {
'checkbox': {
required: true
}
},
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
$("#dovalidate").on("click", function(e) {
myform.validate();
myvalidator.form();
});
});
.error {
background-color: #ffffdd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<form id="form_validation">
<div class="form-group">
<div class="form-line">
<input name="question1" class="question" type="text" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question2" class="question" type="text" value="I got this" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question3" class="question" type="text" data-msg="WOOPS fill this field" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question4" required class="question" type="text" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question5" class="question" type="text" value="Just GREAT" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question6" class="question" type="text" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question7" class="question" type="text" data-msg="What?" data-msg="What?" />
</div>
</div>
<div class="form-line">
<input type="checkbox" name="needcheese" />
<input type="checkbox" name="needcheese" />
<input type="checkbox" name="needcheese" />
<input type="checkbox" name="needcheese" />
</div>
</form>
<button id="dovalidate">Validate this</button>

Related

can't get the selected value of radio button in jquery

I have a form which has various input field with a common name(input array field). I tried to access the value of all elements once the form gets submitted. I able to access all the input field apart from the radio button.
$(document).ready(function() {
function getValue(elem) {
let val = $(elem).val();
if (val === "video") {
let other = $("#videoLink").val();
return other;
}
if (val === "youtube") {
let other = $("#youtubeLink").val();
return other;
}
}
$("#submit").on("click", function() {
$("#form").trigger("submit");
})
$("#form").on("submit", function(e) {
e.preventDefault();
var firstNameValues = $("input[name='firstName[]']").map(function() {
return $(this).val();
}).get();
var lastNameValues = $("input[name='lastName[]']").map(function() {
return $(this).val();
}).get();
var linkValues = $("input[name='link[]']:checked").map(function() {
return getValue(this)
}).get();
})
$("#add-more").on("click", function() {
$("#form > .container").clone().insertAfter("#form");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12">
<form name="form" id="form" class="form" method="post">
<div class="container">
<div class="col-md-12 form-group">
<input type="text" name="firstName[]" class="form-control" placeholder="First name" />
</div>
<div class="col-md-12 form-group">
<input type="text" name="lastName[]" class="form-control" placeholder="Last Name" />
</div>
<div class="col-md-12 form-group">
<input type="email" name="email[]" class="form-control" placeholder="Email" />
</div>
<div class="col-md-12 form-group">
<input type="radio" name="link[]" value="youtube">Youtube:<input type="text" id="youtubeLink" name="youtubeLink[]" placeholder="Youtube" />
<input type="radio" name="link[]" value="video">Video<input type="text" id="videoLink" name="videoLink[]" placeholder="Video" />
</div>
</div>
</form>
<button type="button" id="add-more">Add</button>
<button type="button" id="submit" name="submit">Submit</button>
</div>

Generating json output from jquery appended div

The html inside contact_info div is appended dynamically using jquery append function (multiple contact person can exist). How can I produce following json format from the input using jquery?
{
"Company":[
{
"company_name":"ABC Company",
"contact_info":[
{
"contact_person":"Mr. ABC",
"email":"abc#def.com"
},
{
"contact_person":"Mr. XYZ",
"email":"xyz#def.com"
}
]
}
]
}
<div class="form-group">
<label>Company Name
</label>
<div class="col-md-5">
<input name="company_name" id="company_name" type="text" class="form-control">
</div>
</div>
<div id="contact_info">
<div class="row">
<div class="form-group">
<div class="row">
<label>Contact Person
</label>
<input name="contact_person" id="contact_person" type="text" class="form-control" maxlength="100">
<label>Email
</label>
<input type="email" name="cp_email" id="cp_email" class="form-control" maxlength="100">
</div>
</div>
</div>
</div>
<button onclick="addCompany()">Add Company</button>
-----------Script------------
var company=[];
function addCompany()
{
var pushed=0;
$.each(company, function(i, data) {
if(data.company_name===$('#company_name').val())
{
company[i].contact_info.push({
"contact_person":$('#contact_person').val(),
"email":$('#cp_email').val()
});
pushed++;
return false;
}
});
if(pushed==0)
{
var obj={
"company_name":$('#company_name').val(),
"contact_info":[
{
"contact_person":$('#contact_person').val(),
"email":$('#cp_email').val()
}
]
};
company.push(obj);
}
alert(JSON.stringify(company));
}

Radiobutton selection validation

I have a form with 2 inputs and 2 radio-button. Form is valid when both fields are filled and one of the radio-button is selected. In this case I enable submit button. The problem is that the submit button becomes enabled even when no radio-button is selected
<form name="formAdd" novalidate ng-submit="sendForm()" class="basic-grey" ng-controller="SignUpController">
<input id="antiForgeryToken" data-ng-model="antiForgeryToken" type="hidden" data-ng-init="antiForgeryToken='#GetAntiForgeryToken()'" />
<div class="bg-danger validationErrors" ng-show="validationErrors">
<ul>
<li ng-repeat="error in validationErrors">{{error}}</li>
</ul>
</div>
<div class="form-group">
<label for="Email">Email</label>
<input name="Email"
type="text"
class="form-control"
placeholder="Enter email"
ng-model="person.Email"
ng-required="true"
ng-minlength="3" />
</div>
<div class="form-group">
<label for="UserName">User name</label>
<input name="UserName"
type="text"
class="form-control"
placeholder="Enter user name"
ng-model="person.UserName"
ng-required="true" />
</div>
<div class="form-group" style="height:30px;">
<label for="Role">Your role</label>
<label data-ng-repeat="choice in question.choices" name="Role">
<input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" ng-required="true" />
{{choice.text}}
</label>
</div>
Cancel
<button type="submit" ng-disabled="formAdd.$invalid" class="btn btn-primary">Save</button>
</form>
Updated
(added controller)
var app = angular.module('signupvalidation', []);
app.controller('SignUpController', function ($scope, $http) {
$scope.person = {};
$scope.question = {
questionText: "",
choices: [{
id: 1,
text: "I'm an admin",
isUserAnswer: "false"
}, {
id: 2,
text: "I'm an user",
isUserAnswer: "false"
}]
};
$scope.sendForm = function () {
$http({
method: 'POST',
url: 'api/accounts/create',
data: $scope.person,
headers: {
'RequestVerificationToken': $scope.antiForgeryToken
}
}).success(function (data, status, headers, config) {
$scope.message = '';
if (data.success == false) {
var str = '';
for (var error in data.errors) {
str += data.errors[error] + '\n';
}
$scope.message = str;
}
else {
$scope.message = 'Saved Successfully';
$scope.person = {};
}
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
};
});
Please see demo below
<label for="Role">Your role</label>
<label data-ng-repeat="choice in question.choices" name="Role">
<input type="radio" name="response" data-ng-model="person.userType" data-ng-value="choice.value" ng-required="!person.userType" />
{{choice.text}}
</label>
var app = angular.module('app', []).
controller('HomeCtrl', function($scope) {
$scope.question = {
questionText: "",
choices: [{
id: 1,
text: "I'm an admin",
value: "admin"
}, {
id: 2,
text: "I'm an user",
value: "user"
}]
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="HomeCtrl">
<form name="formAdd" novalidate ng-submit="sendForm()" class="basic-grey">
<input id="antiForgeryToken" data-ng-model="antiForgeryToken" type="hidden" data-ng-init="antiForgeryToken='#GetAntiForgeryToken()'" />
<div class="bg-danger validationErrors" ng-show="validationErrors">
<ul>
<li ng-repeat="error in validationErrors">{{error}}</li>
</ul>
</div>
<div class="form-group">
<label for="Email">Email</label>
<input name="Email" type="text" class="form-control" placeholder="Enter email" ng-model="person.Email" ng-required="true" ng-minlength="3" />
</div>
<div class="form-group">
<label for="UserName">User name</label>
<input name="UserName" type="text" class="form-control" placeholder="Enter user name" ng-model="person.UserName" ng-required="true" />
</div>
<div class="form-group" style="height:30px;">
<label for="Role">Your role</label>
<label data-ng-repeat="choice in question.choices" name="Role">
<input type="radio" name="response" data-ng-model="question.userType" data-ng-value="choice.value" ng-required="!question.userType" />{{choice.text}}
</label>
</div>
Cancel
<button type="submit" ng-disabled="formAdd.$invalid" class="btn btn-primary">Save</button>
<pre>{{person | json}}
</form>
</body>
</html>

Form validation styles not working

I've been experimenting with JQuery form validation, but haven't been able to get success/failure classes to be added once the validation has been complete.
Here is my code:
https://jsfiddle.net/5WMff/
<form method = "post" id = "signUpForm">
<div class="modal-body">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="surname">Surname:</label>
<input type="text" class="form-control" name="surname" >
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number:</label>
<input type="phone" class="form-control" name="phoneNumber">
</div>
<div class="form-group">
<label for="postalCode">Home Postcode:</label>
<input type="text" class="form-control" name="postalCode">
</div>
<div class="checkbox">
<label><input type="checkbox" name = "acceptTCs">Accept Terms and Conditions</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Back</button>
<input type = "submit" name = "submit" class = "btn btn-success btn-large" value = "Submit" ></button>
</div>
</form>
JS:
$(document).ready(function () {
$('#signUpForm').validate({
rules: {
firstName: {
minlength: 2,
required: true
},
surname: {
required: true,
email: true
},
email: {
minlength: 2,
required: true
},
phoneNumber: {
minlength: 7,
required: true
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.form-group').removeClass('error').addClass('success');
}
});
});
The validation (OK vs. more info required) is working fine, it's just failing to add the success/failure class as well. I know it's something obvious I've missed out, but have come to a bit of a dead end.
The effect I'm looking for is like here: http://jsfiddle.net/5WMff/
Thanks.
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
Use submitHandler . Hope this will help you.

jQuery .validate() and form onsubmit [duplicate]

This question already has an answer here:
Interaction between JQuery validation and form submit handler: Broken, or am I doing something wrong?
(1 answer)
Closed 8 years ago.
So I've got a form with onsubmit="SubmitForm()" and also a $().validate(). The problem is that when submit is clicked, the .validate() works, but SubmitForm() also runs. I'm a little confused, could someone help me out?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#eclub').validate({ // initialize the plugin
rules: {
FirstName: {
required: true,
minlength: 2,
},
LastName: {
required: true,
minlength: 2
},
'Email Address': {
required: true,
email: true
},
Zip: {
required: true,
minlength: 2
},
DOB_Month: {
required: true,
minlength: 2,
},
DOB_Day: {
required: true,
minlength: 1
},
over18: {
required: true
}
}
});
});
function autoDMA() {
var zip_code = $('#zip_code').val();
$.ajax({
url: 'get_zipCode.php',
type: 'POST',
data: {zip_code:zip_code},
success:function(data){$('#dma_code').val(data);}
});
}
function SubmitForm()
{
if($("#emailDeals").is(':checked')){
document.forms['eclub'].action='http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target='_blank';
document.forms['eclub'].submit();
}
if($("#mobileDeals").is(':checked')){
document.forms['eclub'].action='/assets/waterfall/waterfall_rest.php';
document.forms['eclub'].submit();
}
return true;
}
</script>
<div id="" style="width:60%;">
<br/>
<!-- <form action="http://cl.exct.net/subscribe.aspx" id="eclub" method="post" onsubmit="return validateForm(this)" style="width:100%;"> -->
<form method="post" id="eclub" onsubmit="SubmitForm()">
<input name="thx" value="http://papamurphys.com/Deals/ThankYou" type="hidden">
<input name="dma" value="" type="hidden" id='dma-set' />
<input name="dma2" value="" type="hidden" />
<input name="MID" value="29115" type="hidden" />
<input name="lid" value="846154" type="hidden" />
<input name="lid" value="17516793" type="hidden" />
<input name="SubAction" value="sub_add_update" type="hidden" />
<input type="hidden" name="status" value="normal" />
<input name="Birthdate" value="" type="hidden" id="bday"/>
<div class="clearfix">
<label for="name"><span class="bold">First Name</span></label><br />
<input class="required" name="FirstName" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="name"><span class="bold">Last Name</span></label><br />
<input class="required" name="LastName" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="email"><span class="bold">Email</span></label><br />
<input class="required" name="Email Address" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="email"><span class="bold">Mobile Number</span></label><br />
<input class="required" name="MobileNumber" type="text" placeholder="" />
</div>
<div class="clearfix">
<span class="bold">Zip/Postal Code</span><br />
<input class="required zip" id="zip_code" name="PostalCode" type="text" onkeyup="autoDMA()" placeholder="" maxlength="5" size="5" />
</div>
<div class="clearfix">
<input class="zip" id="dma_code" name="DMACode" type="text" placeholder="" maxlength="5" size="5" style="display:none;" />
</div>
<div class="clearfix">
<span class="bold">Birthday</span><br />
<input class="month user required" name="DOB_Month" type="text" placeholder="MM" maxlength="2" style="width:48px;" />
<input class="day user required" name="DOB_Day" type="text" placeholder="DD" maxlength="2" style="width:48px;" />
</div>
<div class="clearfix">
<input class="age user" class="required" name="emailDeals" id="emailDeals" type="checkbox"/> Sign me up for email deals
</div>
<div class="clearfix">
<input class="age user" class="required" name="mobileDeals" id="mobileDeals" type="checkbox"/> Sign me up for mobile deals
</div>
<div class="clearfix">
<input class="age user" class="required" name="over18" id="over18" type="checkbox"/> I'm over 18
</div>
<input class="join-btn" type="submit" style="float:right;line-height:14px;cursor: pointer" onclick="pageTracker._trackPageview('Forms', 'Submit', 'eClubSignUp')" value="SUBMIT" />
<!--<input type="button" class="join-btn" value="" onclick="validateForm()" />-->
</form>
</div>
Why don't you use submitHandler callback in validate()?
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
Anything you want to do when the form is valid, and you click the button, would be done inside the plugin's submitHandler option. (Not via an external function triggered by an inline handler)
$('#eclub').validate({
// rules and other options,
submitHandler: function (form) {
if ($("#emailDeals").is(':checked')) {
document.forms['eclub'].action = 'http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target = '_blank';
form.submit(); // submit the form // this is the default
}
if ($("#mobileDeals").is(':checked')) {
document.forms['eclub'].action = '/assets/waterfall/waterfall_rest.php';
form.submit(); // submit the form // this is the default
}
}
});
Working DEMO: http://jsfiddle.net/vbs32y9u/
As #Mike says Why you use SubmitForm()?
Anyway you can try this:
function SubmitForm()
{
if ($("#eclub").valid())
{
if($("#emailDeals").is(':checked')){
document.forms['eclub'].action='http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target='_blank';
document.forms['eclub'].submit();
}
if($("#mobileDeals").is(':checked')){
document.forms['eclub'].action='/assets/waterfall/waterfall_rest.php';
document.forms['eclub'].submit();
}
return true;
}
else
{
return false;
}
}

Categories