Filling out a form using javascript - javascript

I want to fill out a form when opening a page (it's a page where you edit your profile information).
Here is my code:
<head>
<script type="text/javascript">
function addValues() {
document.getElementById("datePicker").value = ViewBag.b.DateOfBirth.ToShortDateString();
document.getElementById("name").value = ViewBag.b.Username;
document.getElementById("username").value = ViewBag.b.Username;
document.getElementById("password").value = ViewBag.b.Password;
document.getElementById("lastname").value = ViewBag.b.Lastname;
}
</script>
</head>
<body onload="addValues()">
<h2>EditProfile</h2>
<form action="~/Authentication/EditProfile" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td>Last name:</td>
<td><input type="text" name="lastname" /></td>
</tr>
<tr>
<td>Date of birth:</td>
<td><input type="date" name="dateofbirth" id="datePicker" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save" />
</td>
</tr>
</table>
</form>
</body>
When loading a page, it doesn't fill out the information, and I can't find the mistake.
Is there a better way of doing this?
The rendered JavaScript looks like:
function addValues() {
document.getElementById("datePicker").value = 11.9.2001. 00:00:00;
document.getElementById("name").value = Mirko;
document.getElementById("username").value = micro;
document.getElementById("password").value = 123456789;
document.getElementById("lastname").value = Mijanovic;
}

You missed setting the id for some of the <input/> elements.
<head>
<script type="text/javascript">
// Example data
const ViewBag = {
b: {
DateOfBirth: '2020-09-30',
Username: 'username',
Password: 'password',
Lastname: 'lastname'
}
};
function addValues() {
document.getElementById("datePicker").value = ViewBag.b.DateOfBirth;
document.getElementById("name").value = ViewBag.b.Username;
document.getElementById("username").value = ViewBag.b.Username;
document.getElementById("password").value = ViewBag.b.Password;
document.getElementById("lastname").value = ViewBag.b.Lastname;
}
</script>
</head>
<body onload="addValues()">
<h2>EditProfile</h2>
<form action="~/Authentication/EditProfile" method="post">
<table>
<tr>
<td>Username:</td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" id="password" /></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name" /></td>
</tr>
<tr>
<td>Last name:</td>
<td><input type="text" name="lastname" id="lastname" /></td>
</tr>
<tr>
<td>Date of birth:</td>
<td><input type="date" name="dateofbirth" id="datePicker" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save" />
</td>
</tr>
</table>
</form>
</body>
</html>
Hope this helps,

I think the problem is a combination of things, as highlighted in a couple of comments / answers.
Add IDs to all inputs (password and lastname don't have IDs)
Ensure that ViewBag is accessed with the # prefix
Ensure that JavaScript literals are rendered appropriately
I believe the following code should handle ViewBag and JavaScript literals:
<script type="text/javascript">
function addValues() {
document.getElementById("datePicker").value = '#ViewBag.b.DateOfBirth.ToShortDateString()';
document.getElementById("name").value = '#ViewBag.b.Username';
document.getElementById("username").value = '#ViewBag.b.Username';
document.getElementById("password").value = '#ViewBag.b.Password';
document.getElementById("lastname").value = '#ViewBag.b.Lastname';
}
</script>
Note that all of the literal values are quoted. You may need to handle additional escaping to prevent any of the ViewBag properties from causing an error due to a ' in the property value.

Related

How to display data from array of objects in a textbox using javascript?

I want to display data stored in an array in form-
for example:
var users =
[
{
'name':'John',
'age':'10'
},
{
'name':'Rose',
'age':'18'
}
];
and I want to display name and age of users logged in, in the form below:
<form id="myform">
<div>
</div>
<h2 align="center"> Edit Details</h2>
<table id="table1"; cellspacing="5px" cellpadding="5%"; align="center">
<tr>
<td align="right" class="style1">First Name:</td>
<td class="style1"><input id="firstname" type="text" placeholder="FirstName" /></td>
</tr>
<tr>
<td align="right">Last Name:</td>
<td><input id="lastname" type="text" placeholder="LastName" /></td>
</tr>
<tr>
<td align="right">Email ID:</td>
<td><input id="email" type="text" placeholder="Email" /></td>
</tr>
<tr>
<td align="right">User Name:</td>
<td><input id="username" type="text" placeholder="UserName" /></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input id="password" type="password" placeholder="Password" /></td>
</tr>
<tr>
<td> <input type="button" value="Edit" onclick="edit()" />
<td> <input type="button" value="Reset" />
</td>
</tr>
</table>
</form>
You can just change the text content with pure javascript.
name.textContent = 'First name' + users[0].name;
Of course, you will need to select all the fields you want to change.

Re-Using JavaScript Function

Creating a cake ordering form, and the # of cakes available can vary from month to month. I am attempting to tweak a JS function created from #Anderson Contreira but in my fiddle it does not work. Here is what I have thus far - Why does nothing change when I enter a quantity?
https://jsfiddle.net/2uack1w6/
Syntax
JS
function calculate(el){
var quantity = el.val();
var id = el.attr("id").replace("item_","").replace("_qty","");
var data = {quantity: quantity,id:id};
var targetTax = $("#item_"+id+"_tax");
var targetTotalPrice = $("#item_"+id+"_totalprice");
$.post($.post(window.alert("It's been one or two or three entered");
});
}
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
window.alert("It's been one or two or three entered");
});
HTML/PHP
<body>
<form id="Form1" runat="server">
<div id="Form1" runat="server">
<table id="table1" border="1">
<tr>
<th>Item</th>
<th>Price</th>
<th>Quantity</th>
<th>Tax</th>
<th>Total</th>
</tr>
<tr>
<td><label for="lblChoccake">Choc Cake</label></td>
<td><label for="lblitem1price">$25.00</label></td>
<td><input type="text" id="item_1_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_1_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_1_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblLemonFudgecake">Lemon Fudge Cake</label></td>
<td><label for="lblitem2price">$15.00</label></td>
<td><input type="text" id="item_2_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_2_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_2_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
<tr>
<td><label for="lblCoconut">Coconut Cake</label></td>
<td><label for="lblitem3price">$35.00</label></td>
<td><input type="text" id="item_3_qty" name="txtitem1qty" value="0" maxlength="10" size="3"></td>
<td><input type ="text" id="item_3_tax" name="txtitem1tax" maxlength="10" size="3" readonly></td>
<td><input type="text" id="item_3_totalprice" name="txtitem1totalprice" maxlength="10" size="3" readonly></td>
</tr>
</table>
</div>
</form>
</body>
jQuery(function($) {
var qty = $("#item_1_qty");
var qty1 = $("#item_2_qty");
var qty2 = $("#item_3_qty");
qty.on("keyup",function(){
alert("It's been one or two or three entered");
});
});
Try this, you are assigning variables before the document has actually loaded.
Take a look here: https://jsfiddle.net/andersoncontreira/mtu6syby/1/
You can make some changes and will work well:
Add a class in each input of item_?_qty e.g.: <input type="text" id="item_1_qty" class="item_qty" />
In your javascript, you can leave the call generic:
jQuery(document).ready(function(){
//you can use a class for help you
$(".item_qty").on("keyup",function(){
//window.alert("It's been one or two or three entered");
calculate($(this));
});
});

Java script add days to date does not produce a result

Please can someone help
I have written some JavaScript that should add the number of days written into my form to the start date of a reservation. It should then output the date of return. I don't see any syntax errors but the script doesn't run. Please can someone help me identify the source of the problem.
JavaScript
<script type="application/javascript">
function ReturnDate(){
var reservationStart = document.getElementById('ReservationStart').value;
var requestedDays = parseInt(document.getElementById('days').value);
var returnDate = document.getElementById('ReturnDate');
var arrParts = reservationStart.split("/");
var myDate = new Date(arrParts[2], parseInt(arrParts[1])-1, parseInt(arrParts[0]) + requestedDays, 0, 0, 0, 0);
var sResult = ("0"+myDate.getDate()).substr(-2)+"/";
sResult += ("0"+(myDate.getMonth()+1)).substr(-2)+"/";
sResult += myDate.getFullYear();
document.getElementById('ReturnDate').value = sResult;
}
</script>
HTML
<form name="frmHTML" method="post" action="">
<table id="tables" class="form" style="width:100%">
<tr>
<td>Game ID</td>
<td><input type="text"
required autocomplete="off"
value= "<?php echo (isset($ID))?$ID:'';?>"
name="gameID"
id="gameID"
placeholder= "Enter A Number between 1 and 8"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Search For Game"
name= "FindDetails"
id= "FindDetails"
style= "width:80%" /></td>
</tr>
<tr>
<td>Game Name</td>
<td><input type= "text"
value = "<?php echo (isset($GameName))?$GameName:'';?>"
name="GameName"
id= "GameName"
readonly
style "width:80%" /></td>
</tr>
<tr>
<td>Game Rental Cost(per day)</td>
<td><input type= "text"
value = "<?php echo (isset($GameCost))?$GameCost:'';?>"
name="gameCost"
id="gameCost"
readonly
style= "width:80%" /></td>
</tr>
<tr>
<td>Number of days</td>
<td><input type= "text"
name="days"
id="days"
placeholder="Enter the number of days you wish to borrow the game for"
onkeyup = "mycalculate()"
autocomplete="off"
style="width:80%" /></td>
</tr>
<tr>
<td>Total Cost</td>
<td><input type="text"
value=""
name="total"
id= "total"
readonly
style="width:80%"/></td>
</tr>
<tr>
<td>Your Name</td>
<td><input type="text"
value=""
name="StudentName"
id="StudentName"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date Start(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReservationStart"
id="ReservationStart"
onkeyup = "ReturnDate()"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date End(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReturnDate"
id="ReturnDate"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Book Game Now"
name= "Submit"
id= "Submit"
style= "width:80%" /></td>
</tr>
</table>
</form>
The problem was the function name was the same as one of the variables. This meant the computer got confused.
The solution:
JavaScript
<script>
function myReturnDate(){
var reservationStart = document.getElementById('ReservationStart').value;
var requestedDays = parseInt(document.getElementById('days').value);
var returnDate = document.getElementById('ReturnDate');
var arrParts = reservationStart.split("/");
var myDate = new Date(arrParts[2], parseInt(arrParts[1])-1, parseInt(arrParts[0]) + requestedDays, 0, 0, 0, 0);
var sResult = ("0"+myDate.getDate()).substr(-2)+"/";
sResult += ("0"+(myDate.getMonth()+1)).substr(-2)+"/";
sResult += myDate.getFullYear();
document.getElementById('ReturnDate').value = sResult;
}
</script>
HTML
<form name="frmHTML" method="post" action="">
<table id="tables" class="form" style="width:100%">
<tr>
<td>Game ID</td>
<td><input type="text"
required autocomplete="off"
value= "<?php echo (isset($ID))?$ID:'';?>"
name="gameID"
id="gameID"
placeholder= "Enter A Number between 1 and 8"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Search For Game"
name= "FindDetails"
id= "FindDetails"
style= "width:80%" /></td>
</tr>
<tr>
<td>Game Name</td>
<td><input type= "text"
value = "<?php echo (isset($GameName))?$GameName:'';?>"
name="GameName"
id= "GameName"
readonly
style "width:80%" /></td>
</tr>
<tr>
<td>Game Rental Cost(per day)</td>
<td><input type= "text"
value = "<?php echo (isset($GameCost))?$GameCost:'';?>"
name="gameCost"
id="gameCost"
readonly
style= "width:80%" /></td>
</tr>
<tr>
<td>Number of days</td>
<td><input type= "text"
name="days"
id="days"
placeholder="Enter the number of days you wish to borrow the game for"
onkeyup = "mycalculate()"
autocomplete="off"
style="width:80%" /></td>
</tr>
<tr>
<td>Total Cost</td>
<td><input type="text"
value=""
name="total"
id= "total"
readonly
style="width:80%"/></td>
</tr>
<tr>
<td>Your Name</td>
<td><input type="text"
value=""
name="StudentName"
id="StudentName"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date Start(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReservationStart"
id="ReservationStart"
onkeyup = "myReturnDate()"
autocomplete="off"
style="width:80%"/></td>
</tr>
<tr>
<td>Date End(dd/mm/yyyy)</td>
<td><input type="text"
value=""
name="ReturnDate"
id="ReturnDate"
style="width:80%"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"
value= "Book Game Now"
name= "Submit"
id= "Submit"
style= "width:80%" /></td>
</tr>
</table>
</form>

How to reflect a calculation from one field to another

I'm very new to JavaScript and I have an assignment that I'm unable to resolve. So I have a table with five fields and I need to calculate the total for a month, then automatically generate the yearly total in a different cell. I got to make the total work for the month but I have no idea how to reflect that in the year cells. Any help will be much appreciated. Thanks a lot for your time :)
Here's my code:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function update() {
var a = +document.forms['calc'].elements['fieldOne'].value,
b = +document.forms['calc'].elements['fieldTwo'].value,
c = +document.forms['calc'].elements['fieldThree'].value,
d = +document.forms['calc'].elements['fieldFour'].value,
e = +document.forms['calc'].elements['fieldFive'].value,
fieldTotal = ((b-d)*a)*c;
document.forms['calc'].elements['fieldTotal'].value = fieldTotal;
return false;
}
function update2() {
var f = +document.forms['calc'].elements['field6'].value,
g = +document.forms['calc'].elements['field7'].value,
h = +document.forms['calc'].elements['field8'].value,
i = +document.forms['calc'].elements['fieldFour'].value,
j = +document.forms['calc'].elements['fieldFive*12'].value,
field9=fieldFour;
field10=fieldFive*12;
fieldTotal2=fieldTotal*12;
document.write('fieldTotal2');
document.write('field9');
document.write('field10');
return false;
}
</script>
</head>
<body>
<form name="calc" action="#">
<table width="600" border="1">
<tr>
<td colspan="2"> </td>
<td width="63">Month</td>
<td width="109">Year</td>
</tr>
<tr>
<td colspan="2">Field1</td>
<td><input type="text" name="fieldOne" id="fieldOne" size="15" value="5,000" /></td>
<td><input type="text" name="field6" id="field6" size="15" value="60,000"/></td>
</tr>
<tr>
<td colspan="2">Field2</td>
<td><input type="text" name="fieldTwo" id="fieldTwo" value="3.0" size="15" /></td>
<td><input type="text" name="field7" id="field7" value="3.0" size="15" /></td>
</tr>
<tr>
<td colspan="2">Field3</td>
<td><input type="text" name="fieldThree" id="fieldThree" size="15" value="$350"/></td>
<td><input type="text" name="field8" id="field8" size="15" value="$350"/></td>
</tr>
<tr>
<td colspan="2">Field4</td>
<td><input type="text" name="fieldFour" id="fieldFour" value="1.5" size="15" /></td>
<td><input type="number" name="field9" id="field9" value="1.5" size="15" /></td>
</tr>
<tr>
<td colspan="2">Filed5</td>
<td><input type="text" name="fieldFive" id="fieldFive" size="15" value="75"/></td>
<td><input type="text" name="field10" id="field10" size="15" /></td>
</tr>
<tr>
<td width="137">Total</td>
<td width="83"><input type="button" value="Calculate" onClick="update();return false;" /></td>
<td><input type="text" name="fieldTotal" id="fieldTotal" size="15" readonly /></td>
<td><input type="text" name="fieldTotal2" id="fieldTotal2" size="15" readonly /></td>
</tr>
</table>
</form>
</body>
Based on what you described I think this should work for you.
Demo
function update() {
var frmEles = document.forms.calc.elements,
a = frmEles.fieldOne.value.replace(',',''), //Remove comma
b = frmEles.fieldTwo.value,
c = frmEles.fieldThree.value.replace('$',''), //Remove Dollar sign
d = frmEles.fieldFour.value,
e = frmEles.fieldFive.value,
fieldTotal = ((b-d)*a)*c;
//Total for the month
frmEles.fieldTotal.value = formatNumber(fieldTotal);
//Calculations for the year
frmEles.field6.value = formatNumber(a * 12);
frmEles.field7.value = formatNumber(b * 12);
frmEles.field8.value = '$' + formatNumber(c * 12); //Add back dollar sign
frmEles.field9.value = formatNumber(d * 12);
frmEles.field10.value = formatNumber(e * 12);
frmEles.fieldTotal2.value = formatNumber(fieldTotal * 12);
return false;
}
//Format the numbers with commas.
function formatNumber(n){
return n.toLocaleString();
}

Instruction error outside javascript function

I'm making a form with a submit button to check login and a link to make a new user!
I'm coding this with:
<script language="javascript">
function new_user()
{
document.getElementById("login").value='registo';
}
</script>
<form id="frmLogin" name="frmLogin" method="post" action="#">
<table>
<tr>
<td><label for="username">Nome do utilizador</label></td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td><label for="password">Palavra-passe</label></td>
<td><input type="text" name="password" id="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="OK" id="OK" value="Submit"/></td>
</tr>
<tr>
<td><input type="hidden" name="login" id="login" value="login"/></td>
<td>Novo Utilizador</td>
</tr>
</table>
</form>
I want to use a hidden field to know if the user pressed the button or the link.
To make the code smaller I'd like to use this code instead:
<form id="frmLogin" name="frmLogin" method="post" action="#">
<table>
<tr>
<td><label for="username">Nome do utilizador</label></td>
<td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td><label for="password">Palavra-passe</label></td>
<td><input type="text" name="password" id="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="OK" id="OK" value="Submit"/></td>
</tr>
<tr>
<td><input type="hidden" name="login" id="login" value="login"/></td>
<td>Novo Utilizador</td>
</tr>
</table>
</form>
Can anyone explain me why this doesn't work?
You might be having a quote clash in the definition of the onclick event handler. Your browser is interpreting it as onclick="document.getElementById(".
Try enclosing the argument of the document.getElementById sentence in single quotes.
onclick="document.getElementById('login').value='registo';document.frmLogin.submit();">
You can use it as below
<td>Novo Utilizador</td>
use single quote for getElementById that will solve it.

Categories

Resources