How to check if two passengers have same name in javascript - javascript

I have 2 input boxes for first name and last name of passengers travelling.
There could be maximum 9 number of passengers.
It is not allowed to have two passengers with same name(first and last combined)
How can I check if none of the passenger have same names(first and last name combined)
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;">
Thanks.
Edit:
I am not using a database to store the passenger names and the passengers are all entered on the same page.

You can add a verification javascript function , but first u need to have specific names for all input boxes .
U can try something like this :
<input type="text" name="adultFirstName1" id="adultFirstName1" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify();">
.
.
.
<input type="text" name="adultFirstName10" id="adultFirstName10" class="form-control input-sm" placeholder="" style="width:100%; padding:5px;" OnClick="Verify(id);">
then you'll need to verify at every change of value of a boxe .

var name=[];
var sameName=false;
for(var i=1;i<=<%=detailsModel.getNumberOfAdult()%>;i++)
{
var fullName = document.getElementById("adultFirstName"+i).value+" "+document.getElementById("adultLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfChild()%>;i++)
{
var fullName = document.getElementById("childFirstName"+i).value+" "+document.getElementById("childLastName"+i).value
name.push(fullName);
}
for(var i=1;i<=<%=detailsModel.getNumberOfInfant()%>;i++)
{
var fullName = document.getElementById("infantFirstName"+i).value+" "+document.getElementById("infantLastName"+i).value
name.push(fullName);
}
for(var i=0;i<name.length;i++)
{
for(var j=i+1;j<name.length;j++)
{
if(name[i]==name[j])
{
var sameName=true
valid= false;
}
}
}
if(sameName==true)
{
$('#sameNameError').html('2 Passengers Cannot Have Same Name');
}
else
{
$('#sameNameError').html('');
}

Are there 2 input boxes for each passenger? If so, try something like this:
$(document).ready(function(){
$("button").click(function(){
if($("#adultFirstName1").val() == $("#adultFirstName2").val()
&& $("#adultLastName1").val() == $("#adultLastName2").val()) {
//Names are the same
}
});
});
Or are you needing to check against the names of other passengers already in a database somewhere?

Related

How can I check if a variable is a specific type using javascript?

I'm a beginner in web development and I have an HTML form where a person can add his address , address number, region and postal code . In this form the address and the region have to contain only char letters .
(ex. Lakewood : correct Lakewood13 : error) . If any of these two variables contains a number I have to enter my data again to continue . Else, I move to the next page . I'm a complete beginner in javascript which I need to use to check my variable types and I would appreciate your help with guiding me to solve this problem .
This is my code with my HTML form with the address number and the region which are the variables we need in this problem :
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(typeof(a.value) === 'string'&&(typeof b.value) ==='string'){
//continue to next page(but how can I check if numbers are in the strings ?)
}
else{
//go back to form and enter again(how can I enter the elements again ? )
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs"> Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "checkdata()">Continue</button>
</form>
</div>
Thank you in advance .
You can try using regex to check if string contains any number in it:
if(!(/\d/.test(a.value)) && !(/\d/.test(b.value))){
Please Note: You also have to return false to prevent the default event if the condition is false and prefix return the function call in onclick attribute.
Demo:
function checkdata(){
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
if(!(/\d/.test(a.value)) && !(/\d/.test(r.value))){
alert('form submit');
}
else{
alert('no submit');
return false;
}
}
<div class = "form-area" id = "forma">
<form action="/action.page.html" class = "sign-form" >
<div class = "form-container">
<h1> Enter purchase data below : </h1>
<label for="addrs" Address Name</label>
<input type = "text" placeholder = "Enter address name " id = "address" name = "addr" required/>
<label for="regn" > Region </label>
<input type = "text" placeholder = "Enter region " id = "region" name = "reg" required/>
</div>
<button type="submit" class="continuebtn" onclick = "return checkdata()">Continue</button>
</form>
</div>
You can write a function for validity, then you can check for dependencies based on that **
function checkData() {
let adress = document.getElementById('address');
let region = document.getElementById('region');
function isValid(e) {
let isTrue;
for (let char in e) {
typeof e[char] !== 'string' ? alert('Please only type strings') : (isTrue = true);
}
return isTrue;
}
isValid(adress.value) && isValid(region.value) ? console.log('next page') : console.log('error');
}
checkData();
**
So need to check if the strings are containing numbers or not
hope you find more insight here: Check whether an input string contains a number in javascript
working demo :
// check if string contains number
function hasNumber(myString) {
return /\d/.test(myString);
}
function checkdata(e) {
e.preventDefault()
//the two elements we need to check
var a = document.getElementById("address");
var r = document.getElementById("region");
var isAddressContainsNumber = hasNumber(a.value);
var isRegionContainsNumber = hasNumber(r.value);
console.log(isAddressContainsNumber, isRegionContainsNumber)
if (isAddressContainsNumber === false && isRegionContainsNumber === false) {
console.log('None of string contains number')
} else {
console.log('One or Both string contains number')
}
}
const form = document.querySelector('.sign-form');
form.addEventListener('submit', checkdata);
<div class="form-area" id="forma">
<form class="sign-form">
<div class="form-container">
<h1> Enter purchase data below : </h1>
<label for "addrs" Address Name</label>
<input type="text" placeholder="Enter address name " id="address" name="addr" required/>
</label>
<label for "regn" > Region </label>
<input type="text" placeholder="Enter region " id="region" name="reg" required/>
</label>
</div>
<button type="submit" class="continuebtn">Continue</button>
</form>
</div>
I would recommend going through the string and getting the ASCII value of each character. Numbers 0-9 are ASCII characters 48-57. Javascript uses UTF-16 and the appropriate method (charCodeAt) returns a 16-bit UTF-16 value, but UTF-16 characters 0-127 match ASCII. So:
var testString = "abcd123";
var isValid = true;
for (var i=0;i<testString.length;i++)
{
if (testString.charCodeAt(i) > 47 && testString.charCodeAt(i) < 58)
{
isValid = false;
}
}
if (!isValid)
{
//Code here to alert the user
alert("There's a number in there!");
}
You are using typeof in wrong way, try this way
typeOf(variable you want to check)

how to give "same as the above" in form entries

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<form method="POST" class="form-group">
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form><br><br>
<form method="POST" class="form-group">
<label>Same as Above</label><input type="checkbox" name="chd"><br><br>
<label>First Name</label><input type="text" name="FName" class="form-control">
<label>Last Name</label><input type="text" name="LName" class="form-control"><br>
<label>I am Ready</label><input type="checkbox" name="ch"><br><br>
<label>Address</label><input type="text" name="Address" class="form-control">
</form>
when we checked the checkbox named 'same as the above' then the second form will have to take same values that are in the first form fields.
you can use jQuery like suppose you have 2 input fields and a checkbox
if you click on checkbox it has to get value from first input and assign it to second like
$(function(){
("#checkbox").click(function(){
if($(this).is(':checked')){
var input1=$("#input1").val();
$("#input2").val(input1);
}
});
});
You need to start listening on proto form fields changes if "same as above" checked and stop listening if unchecked. And when value of any field changes then just proxy values of all proto form fields to surrogate form fields
(function($) {
var $forms = $('form');
var $protoForm = $forms.eq(0);
var $surrogateForm = $forms.eq(1);
var proxyValues = function(name) {
var $fields = $protoForm.find('input');
if (typeof name === 'string') {
$fields = $fields.filter('[name="' + name + '"]');
}
$fields.each(function() {
var field = $surrogateForm.find('[name="' + name + '"]').get(0);
if (field.type === 'checkbox') {
field.checked = this.checked;
} else {
field.value = this.value;
}
});
};
var startValuesProxy = function() {
proxyValues();
$protoForm.on('change.valuesProxy', 'input', function(e) {
proxyValues(e.target.name);
});
};
var stopValuesProxy = function() {
$protoForm.off('.valuesProxy');
};
$surrogateForm.on('change', '[name="chd"]', function(e) {
if (e.target.checked) {
startValuesProxy();
} else {
stopValuesProxy();
}
});
})(jQuery);
1) When You check the checkbox, which would mean you would need to create a hidden field on your Address form, and have the results of the address form fields that you require passed to the hidden fields on the address form.
2) On Checked Box Checked Event. Example
Hope Its Work !!!
In my experience you can just disable the controls - seems to be that way on other sites - then in your submit method - if the checkbox is clicked - send that to the controller and use the 'above' values there too..
$(function() {
$('#chkSameAsAbove').on('change', function() {
var otherControls = $(this).parent().find('input:not(#chkSameAsAbove)');
if($(this).is(':checked')) {
otherControls.prop('disabled', true);
} else {
otherControls.prop('disabled', false);
}
});
});
https://jsfiddle.net/7xv5bv4h/
Get all the inputs in javascript.
Let's say you have two input fields and one checkbox, if checkbox is checked both field will have same value, if not user will enter second value in second input.
so lets try this code:
var input1 = document.getElementById("input1");
if (document.getElementById('checkbox_field_ID').checked) {
$('#input2').append(input1);
}
I hope it helps :)

I want to make the input field has unique value

let us say that there is 5 input field for page (A)
<form class="classesName" action="action.php" method="POST">
<input type="text" name="class1" placeholder="Class Name1?" required="">
<input type="text" name="class2" placeholder="Class Name2?" required="">
<input type="text" name="class3" placeholder="Class Name3?" required="">
<input type="text" name="class4" placeholder="Class Name4?" required="">
<input type="text" name="class5" placeholder="Class Name5?" required="">
</form>
I want the user to fill all the fields BUT it must be unique class name for each field
so he can't fill
class a
class b
class a < this one is duplicated so it should display an error message
class c
class d
I think I can make if statement in the action.php page to check is there a duplication in the submitted field or not
but I don't want all the other values to be lost when I reload this page again to display the error for him
is there like a property in html5 or anything like that ?
thanks
No, this cannot be done with HTML5 alone. You'll have to write some JavaScript to make this happen. The JavaScript code should check all the values and if any two are identical prevent the form from submitting successfully.
In this case you could use javascript to validate the fields every time the user fills out a textbox. Here is an example:
$('input[type=text]').on('change',function(){
var arr = [];
$siblings = $(this).siblings();
$.each($siblings, function (i, key) {
arr.push($(key).val());
});
if ($.inArray($(this).val(), arr) !== -1)
{
alert("duplicate has been found");
}
});
JSFiddle: http://jsfiddle.net/x66j3qw3/
var frm = document.querySelector('form.classesName');
var inputs = frm.querySelectorAll('input[type=text]');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
for(var i = 0; i < inputs.length; i++) {
if(classArr.indexOf(inputs[i].value) != -1) {
inputs[i].style.backgroundColor = "red";
return false;
}
else
classArr.push(inputs[i].value);
}
frm.submit();
});
jsfiddle DEMO

Issue with validating a user-selected amount of appended input forms

I'm trying to validate a set of inputs that are being appended based on a pre-selected value.
Psudo-code version:
Select from a list of options with values set from 0-10
On change Javascript appends 0-10 input forms with incrementing values of w, starting from 0 (so the names are dinnerform0, dinnerform1, dinnerform2, etc for all that exist).
$('#dinnerQty').change(function(){
dinnerQty = $('#dinnerQty').val() ;
if(dinnerQty > 0){
$('#dinnerForm').empty();
$('#dinnerFormCont').show();
for (w = 0; w <= (dinnerQty-1); w++) {
$('#dinnerForm').append('<div class="dinnerformcloneinput"> <input type="text" class="foodform" name="dinnerFirstName' + w +'" placeholder="First Name" /> <input type="text" class="foodform" name="dinnerLastName'+ w +'" placeholder="Last Name" /> </div>')
}
} else {
$('#dinnerFormCont').hide();
$('#dinnerForm').empty();
}
});
For Validation I've been trying to do it based on each input like this but haven't been able to get it to work.
$('input .foodform').each(function() {
if ($("input").val() == ""){
alert("You must enter a First and Last Name for each Dinner Guest");
return false;
}
}
Thanks for any help!
Try this like,
$('input.foodform').each(function() {
// -----^ remove space from here if you input has foodform class
if (this.value == ""){ // use this.value or $(this).val()
alert("You must enter a First and Last Name for each Dinner Guest");
return false;
}
});

Creating an array and skipping empty fields

I have the following form:
<input type="text" name="name1" id="names1" class="names" value="" placeholder="1) Name Here . . .">
<input type="text" name="name2" id="names2" class="names" value="" placeholder="2) Name Here . . .">
<input type="text" name="name3" id="names3" class="names" value="" placeholder="3) Name Here . . .">
<input type="text" name="name4" id="names4" class="names" value="" placeholder="4) Name Here . . .">
I am trying to create an array when the user clicks the submit button that stores each name:
var values = $('.names').map(function() { return this.value; }).get();
It works, but it also collects the empty fields which I do not need. I figure I require a conditional For statement for this, but I can't manage the syntax for it.
Thanks
Try this:
var values = $('.names').map(function() { if(this.value.trim() != '') return this.value; }).get();
Or:
var result = [];
var elements = getElementsByClassName('names');
for(var i = 0; i < elements.length; i++){
if(elements[i].value.trim() != '')
result.push(elements[i].value);
}
just select all .names with non empty value
var values = $('.names[value!=""]').map(function() { return this.value; }).get();
in real world you will need to store names also:
var values = $('.names[value!=""]').map(function() {
return {name: this.name,value: this.value};
}).get();
http://jsfiddle.net/oceog/7ZcbY/

Categories