.test() method in javascript is not working properly - javascript

In this code, the variable value of "ans" is always false whether I have entered value according to pattern or not. I cannot understand the reason.
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>

Try this
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>
<script>
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
</script>

You should move all your code into a defined function validate()
function validate(){
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert("name");
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}

You used function named validate in the submit button event, but did not define it. After defining the validate function, everything works fine.
function validate() {
if (document.getElementById("name") != null)
var name = document.getElementById("name").value;
alert(name);
var patt = /[A-Za-z0-9]+#[a-z]+\.[a-z]+/;
var ans = patt.test(name);
alert("ans: " + ans);
}
<form>
name:
<input type="text" id="name" value="">
<input type="submit" value="submit" onClick="validate();">
</form>

Related

EndsWith in Javascript for Validation Form

I have a question. How to do a validation form in javascript that the condition is "Must be ended with 'City'"?
This is simple example i have to taken to make you understand about the endsWith() method.
function myFunction2() {
var str = "This is City but I am not there";
var n = str.endsWith("City");
document.getElementById("result").innerHTML = n;
}
function myFunction() {
var str = "Welcome to my City";
var n = str.endsWith("City");
document.getElementById("result").innerHTML = n;
}
function validate(){
var txtdata = document.getElementById("city").value;
var txtdata = txtdata.endsWith("City");
if(txtdata){
document.getElementById("result2").innerHTML = "City Found at end";
}else{
document.getElementById("result2").innerHTML = "Must be ended with City";
}
}
<button onclick="myFunction()">Check its working with City</button>
<button onclick="myFunction2()">Check its working without City</button>
<div id="result"></div>
<!-- Validate in form data -->
<form>
<input type="text" id="city" name="city"/>
<input type="button" onclick="validate()" value="Submit"/>
</form>
<div id="result2"></div>
In the similar way you have to take input from form store it in a variable do validation.

return string in javascript

I want to get apiUrl depending on a user's input
<form name="test">
<input type="text" name="Edit">
<input type="button" value="Test" onClick="gettext()">
<input type="text" name="Edit2" readonly style="border:1px solid white">
</form>
Then i have a script which does not work, to form a url based on that
<script>
function gettext(Edit, Edit2) {
document.test.Edit2.value=document.test.Edit.value;};
var apiKey = '07gh4c95ca7e23d41ghggf/';
var userWord = Edit2;
var txtjson = '/json';
var apiUrl = 'http://words.bighugelabs.com/api/2/' + apiKey + userWord + txtjson;
</script>
I need var userWord to be a string to insert its value in the apiUrl.
Please help me with that. Thank you
Edit2 is not declared outside the gettext function. Try this:
function gettext(Edit, Edit2) {
document.test.Edit2.value = document.test.Edit.value;
return document.test.Edit2.value;
}
var userWord = gettext(<param1>, <param2>);

javascript error: function is not defined

I was trying to find the reason why my code doesnt work, and chrome comes back with this eror:
Uncaught ReferenceError: calcMPG is not defined...
Can someone spot my mistake ?(desperate)
<script type="text/javascript">
function calcMPG() {
document.calc.startingMileage.value = startMileage;
document.calc.endingMileage.value = endMileage;
document.calc.gallonsUsed.value = gallUsed;
var MPG = (endMileage - startMileage) / gallUsed;
if (isNAN(startMileage) || isNAN(endMileage) || isNAN(gallUsed)) alert('please type in numbers only!');
else document.calc.milesPerGalon.value = MPG;
}
</script>
<form name="calc">Starting mileage:
<input type="text" value="0" name="startingMileage" onchange="calcMPG()">
<br>Ending mileage:
<input type="text" value="0" name="endingMileage" onchange="calcMPG()">
<br>Gallons used:
<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()">
<br>Miles per galon:
<input type="text" value="0" name="milesPerGalon">
</form>
Your declarations are wrong please correct them.
var startMileage = document.calc.startingMileage.value ;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
I don't know why you do that, but try this:
<script type="text/javascript">
function calcMPG(){
var startMileage = document.calc.startingMileage.value,
endMileage = document.calc.endingMileage.value,
gallUsed = document.calc.gallonsUsed.value,
MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed)){
alert('please type in numbers only!');
} else {
document.calc.milesPerGalon.value = MPG;
}
}
</script>
<form name="calc">
Starting mileage:<input type="text" value="0" name="startingMileage" onchange="calcMPG()"><br>
Ending mileage:<input type="text" value="0" name="endingMileage" onchange="calcMPG()"><br>
Gallons used:<input type="text" value="0" name="gallonsUsed" onchange="calcMPG()"><br>
Miles per galon:<input type="text" value="0" name="milesPerGalon">
</form>
startMileage
and your other right side references don't mean anything, they are undefined variables.
Give your inputs an id and fetch the values from them like this:
var startingMileage = document.getElementById('startingMileage').value;
Check here Fiddle
function calcMPG(){
var startMileage = document.calc.startingMileage.value;
var endMileage = document.calc.endingMileage.value;
var gallUsed = document.calc.gallonsUsed.value;
var MPG = (endMileage - startMileage) / gallUsed;
if(isNaN(startMileage) || isNaN(endMileage) || isNaN(gallUsed))
alert('please type in numbers only!');
else
document.calc.milesPerGalon.value = MPG;
}

Javascript text field validation

I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:
index.html:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Validation Form
</title>
<script type = "text/javascript" src ="vForm.js">
</script>
</head>
<body>
<form id = "myForm" action ="">
First name: <input type="text" name="fname"></br>
Last name: <input type="text" name="lname"></br>
Password: <input type="password" name="pass1"></br>
Re-enter password: <input type="password" name="pass2"></br>
Email: <input type="text" name="email"></br>
Phone: <input type="text" name="phone"></br>
Address: <input type="text" name="add"></br>
Date: <input type="date" name="date"></br>
Time: <input type="time" name="time"></br>
<input type="reset" name="reset">
<input type="submit" name="submit">
</form>
<script type = "text/javascript" src ="vFormRun.js">
</script>
</body>
</html>
vForm.js:
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
vFormRun.js:
document.getElementById("myForm").onsubmit = validateForm;
You need to give .value to each of it. And also, give an id of the same name.
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname.value == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
document.getElementById("fname");
That will only work if you have an element with an ID of fname, which you do not.
You can set the ID attribute to an element like so:
<input type="text" name="fname" id="fname">
Alternatively, you can reference the form elements like this:
var fname = document.forms["myForm"]["fname"]
Then you want to get it's value property when comparing.
fname.value
The <br> tag is self closing, so it should be <br /> instead of </br>
Here is the solution...
function validateForm(form) {
var fname = form.fname,
lname = form.lname,
pass1 = form.pass1,
pass2 = form.pass2,
email = form.email;
if(fname && fname.value === "") {
alert("Please enter first name");
document.getElementById('result').innerHTML = 'Invalid';
return false;
}
document.getElementById('result').innerHTML = 'Passed';
return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
First name: <input type="text" name="fname"><br/>
Last name: <input type="text" name="lname"><br/>
Password: <input type="password" name="pass1"><br/>
Re-enter password: <input type="password" name="pass2"><br/>
Email: <input type="text" name="email"><br/>
Phone: <input type="text" name="phone"><br/>
Address: <input type="text" name="add"><br/>
Date: <input type="date" name="date"><br/>
Time: <input type="time" name="time"><br/>
<input type="reset" name="reset">
<input type="submit" name="submit">
<p id="result">
</p>
</form>
There were a few issues here that I corrected.
I changed all of the var declarations to use one var declaration. This is a best practice.
In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
You were missing a semicolon at the end of the alert statement.
If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources