Getting value of element with javascript from jsp page - javascript

I have the following jsp form:
<form action = "dt.jsp" METHOD = "GET" ONSUBMIT="return validateForm()">
<table>
<tr>
<td><input type=date name="fdate"/></td>
<td><input type=date name="tdate"/></td>
</tr>
</table>
<input TYPE = "SUBMIT" VALUE = "Search by date">
</form>
and javascript function:
function validateForm()
{
alert(document.getElementsByName('fdate').value);
return false;
}
when I do the alert I get undefined. why?

document.getElementsByName('fdate') returns an array, or more accurately a NodeList.
Use document.getElementsByName('fdate')[0].value
See https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByName

Related

Cannot reset readonly input text

I have an input text which i use to show results of computation:
<input type="text" id="total" readonly/>
The total gets populated inside a function on a js file as follows:
//Inside a .js file
function calculate(){
document.getElementById("total").setAttribute("value", document.getElementById("amount").value * 45);
}
and i also have a reset button which resets the form, but it doesn't reset the readonly input text:
<input type="reset" value="Reset"/>
I have tried changing the reset to button and wrote my function to disable readonly, reset then enable readonly but it doesn't work as well:
<input type="button" value="Reset" onclick="resetForm(this.form.name);"/>
//Inside .js file
function resetForm(formName){
document.getElementById("total").readonly = false;
document.forms[formName].reset();
document.getElementById("total").readonly = true;
}
Does anyone know a workaround of this case? I am new to javascript and i am doing this as a learning purpose only.
Heres the complete code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="allJsCodesHere.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1> <strong>CDs Purchase Order</strong></h1>
<form name="ex2Form" action = "">
<table>
<thead>
<tr>
<th>
Number of CDs ordered:
</th>
<td>
<input type="text" id="amount" value="0"/>
</td>
<td>
<input type="button" value="Calculate" onclick="calculate();"/>
</td>
</tr>
</thead>
<tbody>
<td colspan="3">
At the rate of AED 45 for each CD
</td>
</tbody>
<tfoot>
<tr>
<th>
Total Order:
</th>
<td>
<input type="text" id="total" readonly/>
</td>
<td>
<input type="button" value="Reset" onclick="resetForm(this.form.name);"/>
</td>
</tr>
</tfoot>
</table>
</form>
<footer>
<p>Created by Mir Adnan Siraj</p>
</footer>
</body>
</html>
The calculate function:
function calculate(){
document.getElementById("total").setAttribute("value", document.getElementById("amount").value * 45);
}
Document.forms returns a collection of all of the forms within a particular page. Writing document.forms["myForm"] will return the form with the name "myForm" from that collection. So what you need to do is this. Say for example your form name is myForm with an id of myForm.
<form id="myForm" name="myForm">
<input id="email" name="email" value="some#email.com" />
</form>
Now to access this form, you have to do this.
document.forms["myForm"].reset()
This will reset your form successfully. So to be clearly, you are doing everything perfectly just console.log and check the parameter passed. You dont need to reset all the fields manually by assigning them empty string. Thats wrong!
//Inside .js file
function resetForm(formName){ //==========> this needs to return the form name. console.log and check if its returning the formname
document.getElementById("total").readonly = false;
document.forms['formName'].reset();
document.getElementById("total").readonly = true;
}
Assuming that you have your inputs inside a form you'll need to prevent the default behavior of a form, which is to send a request to any URL you might pass and refresh the page, which you don't want, I suppose. To do this, if you are triggering your reset function by attaching a listener to the submit event on a form, you'll need to use the event and call the .preventDefault method - https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Your function:
//Inside .js file
function resetForm(formName){
document.getElementById("total").readonly = false;
document.forms[formName].reset();
document.getElementById("total").readonly = true;
}
Try changing it to this:
//Inside .js file
function resetForm(){
const form = document.getElementById("formName");
const totalInput = document.getElementById("total");
form.reset() // Resetting form
totalInput.readOnly = false; // Making readonly false so input is editable
}
Here's a codesandbox where you can try this out
https://codesandbox.io/s/lucid-frost-4pnbz?fontsize=14&hidenavigation=1&theme=dark
Hope this helps!

Javascript Form Validation, multiple functions on a single button not working correctly

I'm working on a form validation project that requires multiple input fields connected to a single submit button. I more or less figured the button out, but I'm having an issue getting the functions themselves to work properly. I currently only have three of the eleven fields typed up for testing, but what the page should do is let you know which fields are invalid when there is nothing filled out in them (changing text/background colors, message below, etc).
The issue I'm having is that when the requirements for the first field (Gift Card Number) are met, it acts as though there isn't any issues anywhere, regardless of whether or not the other input fields (First name, Last name) have been filled. They all seem to function correctly if none of the fields are filled, but my concern is that the functions seem to be firing in order and first one to work negates all the ones after (for example, Gift Card prevents First and Last, First prevents Last, etc).
Any ideas where I've gone wrong here? I'll include my html and my javascript. (Yes, I know the html is a bit ugly, I plan to move the material over to a div table later, just trying to get it to function for now) Any help appreciated as always!
HTML
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<table>
<tbody>
<tr id="rONE">
<td><h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5></td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
</form>
<tr id="rTWO-1">
<td><h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td><form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4></td>
</form>
</tr>
<tr>
<td><h5 id="recipientMessage"></h5></td></td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
</body>
<footer>
<script src="Form Validation.js"></script>
</footer>
</html>
Javascript
document.getElementById('btn').addEventListener('click', function(){
validateGiftCard();
validateRecipient();
});
function validateGiftCard() {
valid = true;
if ( document.giftForm.giftInput.value == "" )
{
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if ( document.firstForm.firstInput.value == "" )
{
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor="#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
document.getElementById('btn').addEventListener('click', function(e) {
var v1 = validateGiftCard();
var v2 = validateRecipient();
console.log(v1, v2);
if (!v1 || !v2)
e.preventDefault();
});
function validateGiftCard() {
valid = true;
if (document.giftForm.giftInput.value == "") {
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if (document.firstForm.firstInput.value == "") {
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor = "#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
<table>
<tbody>
<tr id="rONE">
<td>
<h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5>
</form>
</td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
<tr id="rTWO-1">
<td>
<h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td>
<form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4>
</form>
</td>
</tr>
<tr>
<td>
<h5 id="recipientMessage"></h5>
</td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>

javascript validation empty field with error messages

Can any one please tell me the wrong of this code, I just want to j=give an error message when the first_name is empty.
<script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var first_name=$('#first_name').val();
if(first_name==="" ){
$('#first_name').css('background-color','#D8D8D8');
$('#fNameErr').show();
return false;
}
else{
$('#first_name').css('background-color','#FFFFFF');
$('#fNameErr').hide();
return true;
}
});
});
</script>
HTML
<form name="myForm" action="../controller/users.php" method="POST"
enctype="multipart/form-data" >
<table align="left" width="700" height="330">
<tbody>
<tr>
<td>First Name: </td>
<td><input type="text" name="first_name" value=""size="45" id="first_name"/>
<div id="fNameErr" class="err"><b>Please Enter First Name</b></div></td>
</tr>
First of all i need to know whether you downloaded jquery file from ,if not do it first.. else jquery wont work.. follow this link http://code.jquery.com/jquery-1.11.1.min.js, save this file in the folder where is your code is...name of the file i used is 'jquery-1.11.1.min.js'
then there was some more mistakes in your code. you need to give a submit button first with the id 'submit', which you used in your script's 3rd line, then need to close form tag..
correct code is..
<html><script src="jquery-1.11.1.min.js"></script><script type="text/javascript">
$(document).ready(function(){
$('#submit').click(function(){
var first_name=$('#first_name').val();
if(first_name=="" ){
$('#first_name').css('background-color','#D8D8D8');
$('#fNameErr').show();
return false;
}
else{
$('#first_name').css('background-color','#FFFFFF');
$('#fNameErr').hide();
return true;
}
});
});
</script>
<body>
<form name="myForm" action="../controller/users.php" method="POST" enctype="multipart/form-data">
<table align="left" width="700" height="330">
<tbody>
<tr>
<td>First Name: </td>
<td><input type="text" name="first_name" value=""size="45" id="first_name"/>
<div id="fNameErr" class="err"><b>Please Enter First Name</b></div></td>
</tr>
<input type="submit" id="submit" value="submit">
</form>
</body>
</html>
try to learn basics first.. Accept my answer if it helps.. :)

Forms inside td html

My html code is:
<table><tr><td onclick="submit_form_patient();")>
<form name="select_patient" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="27" />27</form>
</td></tr>
<tr><td onclick="submit_form_patient();")>
<form name="select_patient" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="49" />49</form></td></tr>
My Java script is:
<script>
function submit_form_patient()
{
document.forms["select_patient"].submit();
}
</script>
My form gets submitted but if I use $_POST to retrieve the values I get 27 all the time namely the first value I never get the other values.
Yours forms have same name. You need to name them differently.
And modify js code:
<script>
function submit_form_patient(formName)
{
document.forms[formName].submit();
}
</script>
And html code need to be like this
<table>
<tr>
<td onclick="submit_form_patient('select_patient');")>
<form name="select_patient" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="27" />27</form>
</td>
</tr>
<tr>
<td onclick="submit_form_patient('select_patient2');")>
<form name="select_patient2" method="POST" action="./select_bed.php">
<input name="raw_data" type="hidden" value="49" />49</form>
</td>
</tr>
The name of the forms is the same. I don't know whether the standard handles this, but browsers pick the first matching item. So it's always going to be the first.
Create only one form, and based on the click POST the right value.
When you use document.forms["select_patient"].submit();, JS will find first form/element with that name.
Try this:
<script>
function submit_form_patient()
{
document.getElementsByName("select_patient")[0].submit();
document.getElementsByName("select_patient")[1].submit();
}
</script>
you can also create a for block to be more consistent.

retype password verification not working

I used the following code:
<script type="text/javascript">
function validate() {
if ((document.changepass.newpassword.value != '') &&
(document.changepass.retypenewpassword.value ==
document.changepass.newpassword.value)){
document.changepass.retypenewpassword.blur();
document.changepass.submit();
}
}
</script>
<form name="changepass" method="POST" action="changepassword.jsp" onsubmit="return validate();">
<table align="center">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" size="20"
style="width: 145px" maxlength="10"></td>
</tr>
<tr>
<td>Retype New Password:</td>
<td><input type="password" name="retypenewpassword" size="20"
style="width: 144px" maxlength="10"></td>
</tr>
<tr>
<td><input type="submit" value="Change Password" name="operation" ></td>
<td><input type="reset"></td>
</tr>
</table>
</form>
but when I'm giving unmatched entry then also it getting changed.i mean the validate function is not getting called.
plz help
in hope
robin
Your form will submit no matter what, because you are not returning false from the validating function on error. It should be:
function validate() {
var d = document.changepass;
if((d.newpassword.value != '') && (d.retypenewpassword.value == d.newpassword.value)) {
return true;
}
return false;
}
At current, you are not specifying a return value for validate(), and it is interpreted as always returning true, so the form gets submitted. You don't need to call submit() from your function, simply return true if everything is ok.
The onsubmit handler on your <form> is looking for a return value, but is not given one from your validate function. Instead of calling submit() in the function, you should return true or false, depending on if the form validates (if the function returns false, that is equivalent to onsubmit="false", which will cancel the submission):
function validate()
{
if ((document.changepass.newpassword.value != '') && (document.changepass.retypenewpassword.value != document.changepass.newpassword.value))
{
// A password is given but it doesn't match
// Perhaps you want to alert() an error message here to tell the user why the form doesn't validate?
return false;
}
return true;
}

Categories