Checking duplicate array element with javascript - javascript

<form action="" method="post" name="frm" onsubmit="return check()">
<input type="text" name="val[]" class="bla">
<input type="text" name="val[]" class="bla">
<input type="text" name="val[]" class="bla">
<input type="text" name="val[]" class="bla">
<input type="submit" value="send">
</form>
i want to using javascript validation
check(){
// if array elements duplicate return false and show error ?
}
inputs maybe empty , not required , i found that this javascript function , but I could not adapt.
function checkIfArrayIsUnique(arr) {
var map = {}, i, size;
for (i = 0, size = arr.length; i < size; i++){
if (map[arr[i]]){
return false;
}
map[arr[i]] = true;
}
return true;
}

Related

Adding Number Result in NaN

<script>
function myFunction(val) {
const ele = document.querySelectorAll('input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
</script>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name= "submit" id="submit" value="Submit"/></p>
</form>
Why the result is NaN? But if I remove the value="Submit" in the last 5th line, then everything working fine. Why? and what should I do to solve this problem?
Your
const ele = document.querySelectorAll('input');
will iterate over all inputs, including the <input type="submit" name= "submit" id="submit" value="Submit"/>.
When you don't use value="Submit", that element doesn't have a real .value, so it defaults to the empty string:
console.log(submit.value);
console.log(submit.value.length);
<input type="submit" name="submit" id="submit">
In contrast, <input value="Submit"/> will have a .value of Submit, which can't be turned into a number.
Select only your inputs with input classes instead:
function myFunction() {
const ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name="submit" id="submit" value="Submit" /></p>
Also note that duplicate IDs are invalid HTML, and event handlers should be attached properly using Javascript instead of using inline handlers:
const inputs = document.querySelectorAll('input.input');
inputs.forEach((input) => {
input.addEventListener('keydown', () => {
const sum = [...inputs].reduce((a, input) => a + Number(input.value), 0);
document.getElementById('result').textContent = sum.toFixed(2);
});
});
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" class="input">
<input type="text" class="input">
<p id="result"></p>
<br>
<p><input type="submit" value="Submit"></p>
</form>
Because you are selecting all the input tag, you should be specific on selecting like querySelectorAll('input[type="text"]'). so it will select only text input tags. Try this one
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(val) {
const ele = document.querySelectorAll('input[type="text"]');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
</script>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name= "submit" id="submit" value="Submit"/></p>
</form>
</body>
</html>
Because document.querySelectorAll('input'); selecting all inputs including submit button as well which has value='submit' and value submit is not a number (NAN). When you remove value attribute from the submit button it returns nothing.

Having problems understanding checked radio buttons

I'm trying to validate my form through JavaScript and instead of manually checking each radio button I decided to loop through a group of radio buttons and check to see if they were checked or not.
I'm simply trying to see if a group of radio buttons is checked or not. But the problem I'm facing is. It's returning both true and false when I check either of them. If I don't check either, they both return false but if I check one, it returns true and false.
Here is my code:
function validateForm(){
let firstliGroup = document.getElementsByName("yesnocheck");
for(i=0; i<firstliGroup.length; i++){
//console.log(firstliGroup[i].checked);
if(firstliGroup[i].checked == true){
console.log('success');
return true;
}
else {
console.log('failed');
return false;
}
}
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<input type="submit" value="Send">
</form>
Try this:
function getRadioValue(name) {
let elements = document.getElementsByName(name);
for (let i = 0; i < elements.length; i++) {
if (elements[i].checked) {
return elements[i].value;
}
}
return null;
}
function validateForm() {
var yesnocheck = getRadioValue("yesnocheck");
console.log(yesnocheck);
return false;
}
If nothing is checked, then getRadioValue function will return null.
If any option was checked, it will return it's value.
Try using document.forms[0].yesnocheck.
function validateForm()
{
return (document.forms[0].yesnocheck.value.length > 0 &&
document.forms[0].yesnoremote.value.length > 0 &&
document.forms[0].yesnocable.value.length > 0 &&
document.forms[0].condition.value.length > 0);
}
<form name="driverkeylistform" method="post" onsubmit="return validateForm()">
<fieldset id="group1">
<input type="radio" name="yesnocheck" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocheck" value="No"><span>No</span>
</fieldset>
<label for="gateremote">Gate remote batteries checked?:</label>
<input type="radio" name="yesnoremote" value="Yes"><span>Yes</span>
<input type="radio" name="yesnoremote" value="No"><span>No</span>
<label for="internetcabletv">Internet and Cable TV checked?:</label>
<input type="radio" name="yesnocable" value="Yes"><span>Yes</span>
<input type="radio" name="yesnocable" value="No"><span>No</span>
<label for="unitcondition">Unit Condition?:</label>
<input type="radio" name="condition" value="clean"><span>Clean</span>
<input type="radio" name="condition" value="light"><span>Light</span>
<input type="radio" name="condition" value="heavy"><span>Heavy</span>
<input type="radio" name="condition" value="superheavy"><span>SuperHeavy</span>
<input type="submit" value="Send">
</form>

how to add n number of input value with javascript

Friends, I want the sum of the numbers I put in fields and these input value total are equal to my total value. it show a Nan Error When i add these input values please help
This is my body Content
<form action="" method="post">
<input type="text" name="cnum" placeholder="enter no. of input">
<input type="submit" name="submit" >
</form>
<?php
if(isset($_POST['cnum']))
{
$cnum=$_POST['cnum'];
$i=0;
?>
<form action="" method="post">
<input type="hidden" name="total" id="total" value="10">
<input type="hidden" name="cnum" id="cnum" value="<?php echo $cnum ;?>">
<?php
while($i<$cnum)
{
?>
<input type="number" id="aq<?php echo $i; ?>" onKeyup="add()" name="aq<?php echo $i; ?>"><br />
<?php
$i++;
}
?>
<input type="submit" name="aqsub">
</form>
<?php
}
?>
This is my java script function
var val=0;
var total=document.getElementById('total').value;
var cnum=document.getElementById('cnum').value;
var anum;
function add()
{
var n=0;
while(n<cnum)
{
anum = 0;
if(document.getElementById('aq'+n).value != "") {
anum=parseInt(document.getElementById('aq'+n).value);
}
val += anum;
n++;
}
alert(val);
}
Update JS part:
var total=document.getElementById('total').value;
total = parseInt(total);
var cnum=document.getElementById('cnum').value;
cnum= parseInt(cnum);
function add()
{
var anum;
var val=0;
var n=0;
while(n<cnum)
{
anum = 0;
var temp = document.getElementById('aq'+n).value;
if( temp != "") {
anum=parseInt(temp);
}
val = +val + anum;
n++;
}
alert(val);
}
var total=document.getElementById('total').value;
total = parseInt(total);
var cnum=document.getElementById('cnum').value;
cnum= parseInt(cnum);
function add()
{
var anum;
var val=0;
var n=0;
while(n<cnum)
{
anum = 0;
var temp = document.getElementById('aq'+n).value;
if( temp != "") {
anum=parseInt(temp);
}
val = +val + anum;
n++;
}
alert(val);
}
<form action="" method="post">
<input name="total" id="total" value="10" type="hidden">
<input name="cnum" id="cnum" value="10" type="hidden">
<input id="aq0" onkeyup="add();" name="aq0" value="" type="number"><br>
<input id="aq1" onkeyup="add();" name="aq1" value="" type="number"><br>
<input id="aq2" onkeyup="add();" name="aq2" value="" type="number"><br>
<input id="aq3" onkeyup="add();" name="aq3" value="" type="number"><br>
<input id="aq4" onkeyup="add();" name="aq4" value="" type="number"><br>
<input id="aq5" onkeyup="add();" name="aq5" value="" type="number"><br>
<input id="aq6" onkeyup="add();" name="aq6" value="" type="number"><br>
<input id="aq7" onkeyup="add();" name="aq7" value="" type="number"><br>
<input id="aq8" onkeyup="add();" name="aq8" value="" type="number"><br>
<input id="aq9" onkeyup="add();" name="aq9" value="" type="number"><br>
Add Following code in your javascript
cnum = parseInt(cnum);
Update code as:
var total= parseInt(document.getElementById('total').value);
As you are using total to comparing with anum. so must be error Nan for total
Well I don't understand your logic but you get NAN because your value of fields are blank.
try this code
var val=0;
var total=document.getElementById('total').value;
var cnum=document.getElementById('cnum').value;
var anum;
function add()
{
var n=0;
while(n<cnum)
{
anum = 0;
if(document.getElementById('aq'+n).value != "") {
anum=parseInt(document.getElementById('aq'+n).value);
}
val += anum;
n++;
}
if(total==anum)
{
alert('Its Work');
}
else
{
alert('Its not Work');
}
}
why dont you directly include the PHP var into a JS var?
var cnum=<?php echo $cnum ;?>;
Also may check against "", and then use a zero
parseInt(input.value)||0;

Validate a form by passing the form name as a constructor

I'm trying to validate a form by passing the form node through a constructor. I know using OO is a bit over the top but it's a request. I've got the code below, but when I try to alert out the values of the text boxes in function(form), they are coming up as undefined.
<SCRIPT LANGUAGE="JavaScript">
function Validator(fields) {
this.fields = fields;
}
Validator.prototype.validate = function (form) {
for (var i = 0, l = this.fields.length; i < l; i++) {
alert(this.fields[i].value);
if (this.fields[i].value == 0) {
alert("The field is empty");
return false;
}
}
}
var validator = new Validator(["username", "password"]);
function runValidate(form) {
validator.validate(form);
}
</SCRIPT>
</head>
<body>
<form NAME="AbbeyRoad">
<fieldset>
<legend>Please login</legend>
<div class="form-element">
<label for="username"><span class="shortkey">U</span>sername:</label>
<input type="text" name="username" id="username" accesskey="u">
</div>
<div class="form-element">
<label for="password"><span class="shortkey">P</span>assword:</label>
<input type="password" name="password" id="password" accesskey="p">
</div>
<input type="button" name="login" value="Login" id="login" onClick="runValidate(this.form)">
</fieldset>
</form>
Change:
alert(this.fields[i].value);
to:
alert(form[this.fields[i]].value);
and this:
if (this.fields[i].value == 0) {
to:
if (form[this.fields[i]].value == 0) {

How to validate an element is exist in form or not using JS

<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error
//Don't write individual validation
//check element is exist or not if exist check for validation
//I need know how to check an element is exist or not
</script>
<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*
</pre>
Apply a class to them:
<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />
and go about like this:
function validate(){
var elms = document.getElementsByTagName('input');
for (var i = 0; i < elms.length; i++){
if (elms[i].className === 'txt'){
if (elms[i].value === ''){
alert('Make sure to fill in all required fields');
// now focus it
elms[i].focus();
return false;
}
}
}
return true;
}
And then call the above function like this:
<form ............ onsubmit="return validate();">
Post your code.
Easiest way to validate is by using jquery validate plugin.(Why write your own code when somebody else has done the same?).
An example
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#feedbackform").validate();
});
</script>
<body>
<form id = "feedbackform" method = "POST" action = "">
<h3><span>Contact Us</span></h3>
<fieldset>
<legend>Contact form</legend>
<label for="id_name">Name *</label>
<input id="id_name" class="required" type="text" name="name" />
<label for="id_email">Email</label>
<input id="id_email" type="email" name="email" class="email"/>
<label for="id_comments">Message *</label>
<textarea id="id_comments" class="required" name="comments"></textarea>
<button type="submit">Send</button>
</fieldset>
</form>
The elements that you want to validate add class="required". I hope the example provided is self-explainatory
You can get a reference to the element and check if the reference is null or not:
for (var i=1; i<=100; i++) {
var elem = document.getElementById('txtbox' + i);
if (elem != null) {
...
}
}
Another approach is to look at the elements in the form, but then you need a way to access the form of course:
var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
...
}
}

Categories

Resources