unedined output in javascript alert box - javascript

I have written simple jsp file which contain textfield for username and password.
I want to validate that field using javascript, but when I write
var a=document.getElementsByID("uname") and prints length of a, it shows me output as 'undefined'.
here is my code..
<head>
<script>
function validate() {
var a=document.getElementById("uname");
alert(a.length);
return false;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form method="post" action="/Edzeal/Validate">
<table align="center">
<tr>
<td>User Name:</td>
<td><input type="text" name="uname" id="uname"></td>
<td><p id="uerror"></p></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr></tr>
<tr>
<td><input type="submit" value="Login" onclick="return validate()"></td>
<td><input type="reset">&nbspRegister</td>
<td></td>
</tr>
</table>
</form>
</body>
</html>

You are trying to alert the 'length' property of the reference to that element. Element objects do not have any such property, unlike arrays or strings, so you are seeing 'undefined'.
See the docs for Elements: https://developer.mozilla.org/en-US/docs/Web/API/element
And document.getElementById
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById

Element has no property length on it, it being undefined is expected.
https://developer.mozilla.org/en-US/docs/Web/API/element?redirectlocale=en-US&redirectslug=DOM%2Felement
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById

Just change
alert(a.length);
to
alert(a.value);
a is an Element, no the string value of the form field. You need .value to get that.

Related

Javascript function validation not working for changing button value

This function isn't working. Can anyone please help? When I press the validate button, nothing happens.
<script>
function validate()
{
int user = document.getElementById("uname");
if(user=="rohit")
document.getElementById("btnsubmit").value = "Sucess";
else
document.getElementById("btnsubmit").value = "Fail";
}
</script>
<body>
<div>
<table id="tbl-aut">
<tr>
<td colspan="2"><h2>Enter Login Details</h2></td>
</tr>
<tr>
<td >Username<span style="color:red">*</span></td>
<td><input type="text" ></td>
</tr>
<tr><td colspan="2" align="center"><input id="btnsubmit" type="button" value="Validate" onclick="validate()"><td></tr>
</table>
</div>
</body>
Nothing is happening because you have a few problems:
First, you have a syntax error. int is not a valid keyword in JavaScript. In JavaScript, data types are implicitly determined. You cannot explicitly specify a type (and there is no integer type in JavaScript anyway).
Next, you are attempting to check an object (the text field) against the value stored in the object. You need to access the value property of the text field to get the data entered into it.
Also, you are attempting to get an object with an id of uname, but you didn't set up that id in the text field at all.
Lastly, and this is more of a best-practice thing. Always wrap the true/false branches of your if statements with curly braces {}. Although it is syntactically OK to omit them when there is only one statement in the branch, this is a well-know bug magnet.
<script>
function validate() {
var user = document.getElementById("uname");
if(user.value =="rohit"){
document.getElementById("btnsubmit").value = "Sucess";
} else {
document.getElementById("btnsubmit").value = "Fail";
}
}
</script>
<body>
<div>
<table id="tbl-aut">
<tr>
<td colspan="2"><h2>Enter Login Details</h2></td>
</tr>
<tr>
<td >Username<span style="color:red">*</span></td>
<td><input id="uname" type="text" ></td>
</tr>
<tr><td colspan="2" align="center"><input id="btnsubmit" type="button" value="Validate" onclick="validate()"><td></tr>
</table>
</div>
</body>

locally add javascript to xampp to do math/formula

I'm trying to make a table, in which user can fill some cells with values and then click submit to show the calculation result. I have jquery-2.0.3.min.js and script.js in my directory. Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Inteligence Decision Support System</title>
<script src='localhost/idss/jquery-2.0.3.min.js'></script>
<script type="text/javascript" src='localhost/idss/script.js' charset="utf-8"></script>
</head>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Cost</th>
<th>x20</th>
<th>x25</th>
</tr>
<tr>
<td>someName</td>
<td><input name="Cost" type="text" value="0"></td>
<td><input name="a20" type="text" value=""></td>
<td><input name="a25" type="text" value=""></td>
</tr>
</table>
<input type="button" onclick="Zcount()" value="Submit" >
</body>
</html>
and here is the script.js file
<script type="text/javascript">
function Zcount(){
var cost, a20, a25;
a20 = document.getElementById("a20").value;
a25 = document.getElementById("a25").value;
cost = (2*parseInt(a20))+(3*parseInt(a25));
document.getElementById("Cost").value=cost;
}
</script>
but when I filled a20 and a25 and click the submit button, nothing happened. The result stayed zero. Where did I go wrong?
You have to check if the external javascripts are actually loaded. You can do this by right-clicking in he browser ind click "inspect element" in chrome or firefox. If you click "console" in these inspectors you can check if they are loaded. If they aren't, you have to adjust your src attribute in the HTML script element.
Also, you have to use the id attribute on the input's because you're using getElementById, and officially inputs have to be surrounded by a form element. So, in the body tag, your HTML will be like this:
<form id="form" action="#" method="post">
<table border="1">
<tr>
<th>Name</th>
<th>Cost</th>
<th>x20</th>
<th>x25</th>
</tr>
<tr>
<td>someName</td>
<td><input name="Cost" id="Cost" type="text" value="0"></td>
<td><input name="a20" id="a20" type="text" value=""></td>
<td><input name="a25" id="a25" type="text" value=""></td>
</tr>
</table>
<input type="submit" value="Submit" >
</form>
Inside the script.js, you don't have to use the HTML script tags.
Why are u including jquery if you don't use it?
But because you do, you can use this script:
$('form').submit(function(){
var cost, a20, a25;
a20 = $("#a20").val();
a25 = $("#a25").val();
cost = (2*parseInt(a20))+(3*parseInt(a25));
$("#Cost").val(cost);
return false;
});
Working jsFiddle: http://jsfiddle.net/jwvanveelen/ch2wR/

Using javascript to get a value from html input

I am new to this forum and I want to be able to get a value from my html inputs into javascript. Right now i have this code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PWS</title>
</head>
<body bgcolor="#009933" text="#FFFFFF">
<H1 align="center">PWS Julia en Sophie</H1>
<hr>
<br>
<strong>DOUCHE</strong>
<table>
<tr>
<td>Temperatuur</td>
<td><input type="text" name="dtemp" onClick="calculateTotal()" /></td>
</tr>
<tr>
<td>Tijd</td>
<td><input type="text" name="dtijd" onClick="calculateTotal()" /></td>
</tr>
<tr>
<td>Hoe vaak per week</td>
<td><input type="text" name="dfreq" onClick="calculateTotal()" /></td>
</tr>
</table>
<br>
<strong>BAD</strong>
<table>
<tr>
<td>Temperatuur</td>
<td><input type="text" name="btemp" onClick="calculateTotal()" /></td>
</tr>
</tr>
<tr>
<td>Hoe vaak per week</td>
<td><input type="text" name="bfreq" onClick="calculateTotal()" /></td>
</tr>
</table>
<script type="text/javascript">
var dTemp = document.getElementsByName("dtemp").value;
document.write(dTemp);
</script>
obviously, its not working. Because the dTemp value stays undefined.
Can anyone help me, thanks in advance,
Bob
document.getElementsByName returns an array, so you have to reference the position of the element:
var dTemp = document.getElementsByName("dtemp")[0].value;
I would also recommend giving ID's to your inputs, since it seems that each name is unique in your case, that way you could use document.getElementById
document.getElementsByName("dtemp") will give you array of elements, traverse through one by one and get the value from it.
var elements = document.getElementsByName("dtemp");
var firstValue = elements[0].value;
1) You need to index the result of getElementsByName, as described in other answers; append [0] to document.getElementsByName("dtemp").
2) You can’t use document.write in code that is executed after the page has loaded. It would replace the current document by the written content. Write to an element instead.
3) You have not defined the function calculateTotal at all. Wrap your JavaScript code in a function, e.g.
<div id=result></div>
<script>
function calculateTotal() {
var dTemp = document.getElementsByName("dtemp")[0].value;
document.getElementById('result').innerHTML = dTemp; }
</script>
4) You have a long way to go, since now your code makes no attempt at calculating anything, you should hardly use onclick on an input element to start the calculation (rather, onchange on it, or onclick on a separate button element). You should read a good JavaScript primer, really.

Setting an input to its most recent valid value

I'm trying to write a polyfill for HTML5's input type="number" element. Here's a comparative example if your browser already supports it.
If you enter a value that cannot be parsed as a number, such as "abc", when you blur, Chrome will set the value back to whatever the most recent valid value you was. I suppose I could do that by storing the value in a data- attribute whenever the field gets focus, just in case I need to set it back, but is there any more natural way to go about "remembering" the most recent valid value a form field had?
This is often called undo. This fellow shows you how to do it with JavaScript:
<html>
<head>
<title>Title</title>
<script type="text/javascript" language="javascript">
function InputBalance_OnChange(sender) {
if(isNaN(sender.value)) {
sender.value = isNaN(sender.prevValue) ? 0 : sender.prevValue;
} else {
sender.prevValue = sender.value;
}
}
</script>
</head>
<body>
<table>
<tr>
<td>Account Number</td>
<td><input id="inputAccountNumber" type="text" /></td>
</tr>
<tr>
<td>Balance</td>
<td><input id="inputBalance" type="text" onChange="InputBalance_OnChange(this)" value="0" /></td>
</tr>
</table>
</body>
</html>

Java script function not called

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<br><br><br><br>
<body style="background-color: cornflowerblue" >
<form action="Login" method="post" name="frmLogin">
<table style="background-color: darkgrey" align="center" border="1">
<thead>
<tr>
<th colspan="2" style="font-size: xx-large;color:darkmagenta" >Login Details</th>
</tr>
</thead>
<tbody>
<tr>
<td style="font-weight: bold" >Username</td>
<td><input type="text" name="txtUsername" value="" /></td>
</tr>
<tr>
<td style="font-weight: bold">Password</td>
<td><input type="password" name="txtPassword" value="" /></td>
</tr>
<tr>
<td align="center" colspan="2" >
<input type="button" onclick="return reset();" value="Reset" name="btnReset" />
<input type="submit" onclick="return submit();" value="Submit" name="btnSubmit" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript" language="javascript">
function submit()
{
var username=frmlogin.document.txtUsername.vlaue;
var password=frmlogin.document.txtPassword.vlaue;
if(username=="")
{
alert("Username Must be filled");
return false;
}
if(password=="")
{
alert("Password Must be filled");
return false;
}
return true;
}
function reset()
{
frmlogin.document.txtUsername.vlaue="";
frmlogin.document.txtPassword.vlaue="";
return false;
}
</script>
</form>
</body>
</html>
I have html code above, and on successfully submit I call a servlet name Login.
But it directly call the servlet. It skips the java script function.
And if i remove the form then java script executes.
Your problem is that you gave the custom form validator function the same name as the form's default submit function form.submit(). The form's default submit function will have precedence in this context.
To fix this, you need to rename submit() to something else. E.g.
onclick="return validate();"
with
function validate() {
// ...
}
Unrelated to the concrete problem, you've several major bugs in your JS function, the following line for example is completely wrong:
var username=frmlogin.document.txtUsername.vlaue;
but that's subject for a different question if you can't figure it out.
Last but not least, I hope that you're aware that JS can be disabled/spoofed by the client? Ensure that you're also validating the form in the server side. See also our servlets wiki page for a concrete example.
add the onsubmit event handler for the form:
<form action="Login" method="post" name="frmLogin" onsubmit="return submit();">
devang you need to capture event for the submit button click if you want to execute that javascript code. i am having the same problem but i solved it using jquery click events, because the by default it submits directly without moving through the code . if any alternate solution is there , please letme know too
btw jquery code can be written as
$("input[name=btnSubmit]").click(function(e) {
..if fails conditions..
e.preventDefault();
});

Categories