Javascript function validation not working for changing button value - javascript

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>

Related

Webpage vanishes when clicking button to send data to server with jQuery

I am having a issue with HTML and jQuery programming.
I am making a bulletin board with HTML and jQuery, with 2 textboxes and a button.
$(document).ready(function(e) {
$('save').click(function() {
const name = $('name').val();
const words = $('words').val();
$.post(
"http://localhost:8000/board_write",
{
name: words
},
function(data, status) {
}
)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="0">
<tr>
<td class="vert" bgcolor="">
Name
</td>
<td>
<input class="name">
</td>
</tr>
<tr>
<td bgcolor="">
Anything you'd like to say
</td>
<td>
<textarea class="words" cols="40" rows="5" placeholder="please enter anything">
</textarea>
</td>
</tr>
<tr>
<td>
<input class="save" type="button" onclick="write()" value="Save">
</td>
</tr>
</table>
And, I also coded with jQuery to send the data of the two textboxes to localhost:8000, which is a node.js server to log the data to the console.
When I click the button, the page vanishes. What causes the situation? And, how can I solve the problem?
You have onclick = "document.write()"; that explicitly deletes the document . https://www.w3schools.com/jsref/met_doc_write.asp
Explanation: the code in onclick is scoped such: {window{document{element{}}}}; if you meant to implement a write() function, do so and invoke it by window.write(), or name it something differently to document.write. Otherwise, write() will de resolved to document.write().

How to get a number value from an input field?

I have some issues with calculating some stuff with JS and getting the right values out of the input fields (number). When I use this code it doesn't show anything. So what is wrong with my JS? Do I need to include a jQuery file?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td><input type="number" name="TotalProductionTime" placeholder=""> hours</td>
</tr>
<tr>
<td>Breaks</td>
<td><input type="number" name="Breaks" placeholder=""> minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td><input type="number" name="Malfunctions" placeholder=""> minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td><p id="test"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" name="Calculate" value="calculate">
<script>
function Calculate()
{
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
</script>
</body>
</html>
You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle
You you are trying to get elements by their ID, but you don't give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.
function Calculate() {
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td>
<input type="number" id="TotalProductionTime" placeholder="">hours</td>
</tr>
<tr>
<td>Breaks</td>
<td>
<input type="number" id="Breaks" placeholder="">minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td>
<input type="number" id="Malfunctions" placeholder="">minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td>
<p id="test"></p>
</td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
</form>
Every id must be converted to integer. Example
var Malfunctions = parseInt(document.getElementById("Malfunctions").value);
then your ready to go
With HTMLInputElement you can use property .valueAsNumber which returns a numeric property if possible:
const str = document.querySelector("input").value;
const num = document.querySelector("input").valueAsNumber;
console.log(typeof str, str, str + 2);
console.log(typeof num, num, num + 2);
<input type="number" value="40" disabled />
You've got two problems here. One obvious is that you try to get a reference to the form inputs by id, but didn't give them any (you gave them a name). To fix, either change the name attribute to an id, or use the form-specific way to reference them, e.g.:
var TotalProductionTime = document.forms.frm1.TotalProductionTime
Second problem is more vicious and has to do with the scope of execution of what you put in onclick attributes. You see, your button is named "Calculate" just like your function, and in the context of the onclick attribute, its parent form is used to resolve identifiers before the global scope. So instead of calling the function named Calculate, you're trying to call the button itself. Fix that by giving them different names, referencing window.Calculate explicitly, or much better, define your event handler in JavaScript instead of using the HTML attribute:
document.forms.frm1.Calculate.onclick=Calculate

How to get elements' value in Javascript

I've the follow code for get the value fot two input and send it to a Ajax file for proccess it. It doesn't work and I put an alert for see what's wrong and the alert return me [object HTMLInputElement].
<tr>
<td>Introduzca licencia: </td>
<td><input type="text" id="lic" name="lic" value=""/></td>
</tr>
<tr>
<td>Introduzca apellidos: </td>
<td><input type="text" id="ape" name="ape" value=""/></td>
</tr>
<script type="text/javascript">
var lic=document.getElementById("lic").value;
var ape=document.getElementById("ape").value;
</script>
<tr>
<td><input type="button" value="Buscar" onclick="load(lic, ape);"/></td>
</tr>
If I try that it return the value of the input
<script type="text/javascript">
function prueba(){
var lic=document.getElementById("lic").value;
var ape=document.getElementById("ape").value;
alert("La licencia es: "+lic+" y los apellidos son: "+ape);
}
</script>
<tr>
<td><input type="button" value="Buscar" onclick="prueba();"/></td>
I don't know why the first code doesn't work if I'm making the variables of the same way.
In the onclick handler (load(lic, ape);) for <input type'='button'> in the first code block, neither the load function nor the two arguments (lic and ape) are defined.
Change it to:
onclick="load();"
and make your script file as:
function load(){
var lic = document.getElementById("lic").value,
ape = document.getElementById("ape").value;
alert("lic is " + lic); // test
alert("ape is " + ape); // test
}
DEMO
P.S. You are missing <table> tags. And document.getElementById will always return a DOM object.

unedined output in javascript alert box

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.

How to clear textbox on HTML using Javascript

I have code in html like this
<html>
<script type="text/javascript" src='LatihanKuisJs.js'></script>
<body>
<form name="kuis">
<table border="1" width="50%">
<tr>
<th colspan="2" >Celcius
</tr>
<tr>
<td align="center" width="80%">Kelvin</td>
<td align="center"><input type="text" id="kelvin">
</td>
</tr>
<tr>
<td align="center" width="80%">Reamur</td>
<td align="center"><input type="text" id="reamur"></td>
</tr>
<tr>
<td align="center" width="80%">Fahrenheit</td>
<td align="center"><input type="text" id="fahrenheit"></td>
</tr>
</table>
<input type="button" value="Calculate" onclick='calculateCelcius();'/>
<br/><br/>
<textarea rows="20" cols="90" id="textarea">
</textarea>
<br/><br/>
<input type="button" value="Clear" onclick='clear();'/>
</form>
</body>
</html>
and external javascript function like this:
function calculateCelcius(){
var kelvin = document.getElementById('kelvin');
var reamur = document.getElementById('reamur');
var fahrenheit = document.getElementById('fahrenheit');
var textarea = document.getElementById('textarea');
var hasil=(kelvin.value*1 + reamur.value*1 + fahrenheit.value*1);
textarea.value += hasil + '\n';
}
function clear(){
document.getElementById("textarea").value="";
}
When I tried to click the clear button on my page, the text area wasn't clear.
What's wrong? And what should I do?
Just rename your function from clear to something like clearTextarea and it will work.
The clear() method refers to obsolete document.clear() method, which is described at MDN as:
This method used to clear the whole specified document in early
(pre-1.0) versions of Mozilla. In recent versions of Mozilla-based
applications as well as in Internet Explorer and Netscape 4 this
method does nothing.
Also according to HTML5 specification:
The clear() method must do nothing.
References:
https://developer.mozilla.org/en-US/docs/DOM/document.clear
http://www.whatwg.org/specs/web-apps/current-work/multipage/obsolete.html#dom-document-clear
if you use a function like this one
function clearInput(element){
element.value="";
}
then in the input add this
onfocus="clearInput(this)"
this can be used multiple times for any text fields or text areas because the id of the object is passed where it calls the function from.
RKillah
Try adding javascript: before your function name when defining onclick event.
Something like this:
<input type="button" value="Clear" onclick='javascript: clear();'/>

Categories