JavaScript form same values - javascript

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code

You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');

You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.

If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}

Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>

With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/

Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.

You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

Related

How to validate all inputs which exists on page?

All inputs from page
I have this html page which is dynamical created, which contains some divs. Every div-question(0,1,2, etc) contain an input based on which answer type the user chose. I want to validate every single inputs from page and:
If value of one input type number,text,date is != "" alert("something")
else send the value in an array;
If checkbox/radio is not checked alert("something");
I tried something like this:
let nrDiv = document.getElementsByClassName("div-question");
let existInput = nrDiv[0].querySelector("input[type='text']");
let numberInput = nrDiv[0].querySelector("input[type='number']");
if (document.body.contains(existInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container[0].querySelector("input[type='text']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
It's working but if I come with another for loop, for input type="number" is not working anymore. I'm getting value null. So if I come with this:
if (document.body.contains(numberInput)) {
for (let i=0; i < nrDiv.length ;i++) {
let container = document.getElementsByClassName("div-questions" + i + "");
let userInputAnswer = container.querySelector("input[type='number']");
if (userInputAnswer.value == "") {
alert("Adaugati un raspuns!")
return;
}
if (userInputAnswer.value != ""){
let answer = {
question: questions[i].textQuestion,
answer: userInputAnswer.value
}
answers.push(answer);
}
}
}
And for the checkbox and radio inputs I don't have any idea. I want something like this:
If all inputs are not empty and minimum one checkbox/radio is checked, send the answer and question in an array else alert("error");
I feel like this is simple once you add the required attribute and/or a pattern.
This is a simple POC:
<form action="">
<input type="text" required>
<input type="number" required>
<input type="checkbox" required>
<input type="radio" required>
<input type="date" required>
<button type="submit">Submit</button>
</form>
Notice that when you click the submit button, it does the verification you want, in this case != "".

getElementByID.readOnly in array

Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?
script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function(){
var index, len;
$.get('/SomeList.txt', function(data){
var SomeList = data.split('\n');
for (index = 0, len = SomeList.length; index < len; index++) {
document.getElementById(SomeList[index]).readOnly = true;
}
});
});
});
</script>
and txt file contains name of input ID:
TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
Assuming you have some elements with the given IDs you must check if the element exists first before doing
document.getElementById(SomeList[index]).readOnly = true;
so replace that line with
var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
return;
}
myElement.readOnly = true;
That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.
var dataArray = [
'TextFieldName',
'TextFieldEmailxxxxx',
'TextFieldDepartment',
'TextFieldOffice'
];
dataArray.forEach(function(id){
var myElement = document.getElementById(id);
if(myElement == null) {
return;
}
myElement.readOnly = true;
});
<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
document.getElementById(id_array[i]).readOnly = true;
}
Email: <input type="text" id="email" value="test#mail.com"><br>
Country: <input type="text" id="country" value="Norway" >
it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements

Search for equal numbers or alphanumeric values inserted in input elements

I want to loop through all the input elements and find if the same value exists.
For example when a user inserts 1(one) and then inserts again the number 1(one), I would like to apply CSS to change the background color of the input element for these 2 equal values or no matter how many they may be.
If the user tries to insert an alphanumerical value then JavaScript handles the code and adds the selected-wrong-input CSS class.
I would like on that element to have a setInterval for 2 seconds and take out the alphanumerical value from the input in order for the user to be able to insert a number again.
I don't mind if the proposed solution is with JavaScript, jQuery or a combination of both.
The html code:
<div class="bus-builder-seat-box-container" id="dynamic-bus-builder-1">
<input id="posA100" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA101" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA102" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA103" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA104" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA105" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA106" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA107" type="text" class="input seat_box selected-wrong-input" onchange="bc.seatBoxHandleEvent(this)">
</div>
The JavaScript code. The first is the event which is called in the html input element onchange
bc.seatBoxHandleEvent = function (el) {
bc.checkInput(el);
var seatNumberFirstFloor = $('#dynamic-bus-builder-1');
if (seatNumberFirstFloor && seatNumberFirstFloor.valueOf()) {
var leftStreaming = (event.target.id);
var rightStreaming = 'posB1' + leftStreaming.substring(5, 7);
document.getElementById(rightStreaming).innerHTML = event.target.value;
}
}
bc.checkInput = function (el) {
let $el = $(el);
var targetValue = event.target.value;
var id = event.target.id;
var classOfInput = event.target.classList;
if (targetValue !== 8 && targetValue !== 0 && (targetValue < 48 || targetValue > 57)) {
console.log('valid number');
console.log(classOfInput);
$(el).toggleClass('selected');
}
else {
console.log('invalid character');
$(el).toggleClass('selected-wrong-input');
//console.log(el.value);
}
var array = new Array(120);
var existsValue = false;
for(var i = 0; i <= array.length; i++) {
console.log(el.value);
console.log(i);
if (el.value === array[i]) {
console.log('hi');
console.log(el.value);
console.log(array[i]);
var existsValue = true;
console.log('existsValue');
console.log('equal number forbidden');
//break;
}
}
I'd suggest to use IsNaN() function to check if the input is a number. Also a keyup event is better for input fields.
var inputList = [];
$('.seat_box').keyup(function(elem){
if(IsNaN(elem.value)) return; //input isn't numeric, add your functionality
if (!valueExists(elem)) inputList.push(elem.value);
else //dublicate value, add functionality
});
function valueExists(elem) {
$(".seat_box").each(function(elem) {
if ($.inArray(this.value, inputList) != -1) return true;
else return false;
});
}

Form element values equal to another form values using a loop

I want to have text field values in one form equal to another form values when a radio button is checked. I can do it manually, but is there a way to do it using a loop? Thanks in advance!
<script type"text/javascript>
function setfields()
{
var radioSel = document.getElementById('radioChoice');
if(radioSel.checked)
{
//loop to set fields
}
}
</script>
<input name="radioChoice" type="radio" id="radioChoice" onChange="setFields">
<field set>
First Name:<input id="fname1" name="fname1" type="text"><br>
Last Name:<input id="lname1" name="lname1" type="text"><br>
</field set>
<!--make second field set values equal to first field set values-->
<field set>
First Name:<input id="fname2" name="fname2" type="text"><br>
Last Name:<input id="lname2" name="lname2" type="text"><br>
</field set>
You can specify the names (except the trailing 1 or 2) in an array and iterate through that:
var names = ['fname', 'lname', ...];
for (var i = 0; i < names.length; i++) {
var src = document.getElementById(names[i] + '1');
var dst = document.getElementById(names[i] + '2');
dst.value = src.value;
}
Or you could find the names yourself by iterating through children of the <field> block -- let's assume you've given the first one id="fields1":
var fields = document.getElementById('fields1').childNodes;
for (var i = 0; i < fields1.length; i++) {
if (fields[i].nodeType == 1 /*ELEMENT_NODE*/ && fields[i].tagName == 'input') {
var baseId = fields[i].id.substr(0, fields[i].id.length - 1);
document.getElementById(baseId + '2').value = fields[i].value;
}
}

to check duplicate values for text box with same id onkeyup event

please help to validate duplicate values for the text box having same id which is in loop with onkeyup or onblur event, i need to validate before submitting the form,
N number of textbox generated in loop, in each text box i need to enter rank, thereby i need to validate that duplicate rank should not be entered after the value is entered into the text box,
enter code here
<%Iterator iterator_t = tem.keySet().iterator();
int i =0;
while (iter.hasNext()) {
String key_t = (String) iter.next();
ModuleBean moduleBean = (ModuleBean) tem.get(key_t); %>
<input type="text" name="rank1" id="rank1" size="2" "/>
<%}%>
You can not use same id for it, instead add a class to it. Demo
<input type="text" name="rank1" id="rank1" size="2" class="rank" value="1"/>
<input type="text" name="rank2" id="rank2" size="2" class="rank" value="2"/>
function find_duplicates(arr) {
var len=arr.length,
out=[],
counts={};
for (var i=0;i<len;i++) {
var item = arr[i];
var count = counts[item];
counts[item] = counts[item] >= 1 ? counts[item] + 1 : 1;
}
for (var item in counts) {
if(counts[item] > 1)
out.push(item);
}
return out;
}
$('.rank').keyup(function()
{
var listOfValues = [];
$('.rank').each(function()
{
if($(this).val()!='')
listOfValues.push($(this).val());
});
var duplicates = find_duplicates(listOfValues);
if(duplicates.length>0)
{
$('#result').html('Duplicates are:');
$('#result').append(JSON.stringify(duplicates));
}
else
{
$('#result').html('No Duplicates found');
}
});

Categories

Resources