Display data in HTML form when loaded - javascript

N00b alert; I know enough to be dangerous, so forgive my ignorance...I've been through all of the related questions here and elsewhere, but I just can't seem to comprehend the answer that's surely included in the responses :-(
I'm posting a record id to a page where I want a form to display with the contents of the related record. I'm getting the record in correctly (confirmed using the alert) with this script in the HEAD section (jquery 1.9 is called as well):
<script type="text/javascript">
function getSelectedCustomer () {
...use the id to get the right record...
databaseAPI.callback = function() {
if (databaseAPI.error) {
alert("Database Error: " + databaseAPI.error);
}
else {
var customerRecord = databaseAPI.result;
alert("Test Callback: " + new String(customerRecord.full_name));
$("#quoteForm").load(customerRecord);
}
return;
};
databaseAPI.ajaxGet();
}
window.onload = getSelectedCustomer;
</script>
...and the form in the BODY to be loaded:
<form method="post" id="quoteForm" action="process_quote.php">
<table>
<tbody>
<tr>
<td>Name</td>
<td><input type="text" value="<?php $customerRecord['full_name']; ?>" name="full_name"></td>
</tr>
...other bits of the form...
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
I know I'm incorrectly munging various things together. Can someone please get me straightened out on what to do?
Michael's answer solved the INPUT fields in the form. Didn't mention I had SELECT fields as well:
<select size="0" name="email_sent">
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
Changing INPUT to SELECT works.

What your missing is where code is being executed. The PHP code is being executed on the server, before being sent to the browser. The Javascript is then rendered by the browser. You can't pass variables back and forth between Javascript and PHP.
You want to inject the name with Javascript. I see you're already using jQuery, so the heavy lifting is already done for you. Remove the value="<?php $customerRecord['full_name']; ?>" from the PHP file, and replace $("#quoteForm").load(customerRecord); with $("#quoteForm input[name='full_name']").val(customerRecord.full_name);
Should work, might need some variation depending on your exact circumstances. At least it should put you down the right path.

Related

javascript not displaying in jsp page

I wrote a code for retrieving data from database table and displaying it. The entire table is passed as arraylist through servlet to jsp page. Inside the jsp.. first only name is displayed in dropdown box. The objective was to choose a name from dropdown , and rest of the data corresponding to the name is displayed after the name is chosen. Arraylist has been passed correctly. Dropdown is working fine.
but javascript code to display the rest is not working. please help.code below iv shown only for one field. ie,for id.
output page with dropdown
<body>
<form action="Servletname" method="post" name="searchdatabase">
<%int i=0;
ArrayList<Cust> newlist=(ArrayList<Cust>) request.getAttribute("CusList");
if(newlist.size()>0){
%>
<table>
<tr>
<td> name :</td>
<td>
<select id="selectUsers" name="users" onChange='Choice();'>
<option> </option>
<%for(Cust c:newlist){ %>
<option value="<%=c.getCustId()%>"> <%=c.getName() %></option>
<%}%>
</select>
</td></tr>
<tr>
<td> id :</td>
<td>
<input type="text" id="ids" name="id" >
</td></tr>
</table>
</form>
<script type="text/javascript">
function Choice() {
//x = document.getElementById("users");
y = document.getElementById("selectUsers");
x=y.selectedIndex;
Cust c1= newlist.get(y.selectedIndex);
document.getElementById("ids").value =c.getCustId();
}
</script>
<%} %>
</body>
There are a few problems with your code.
First of all, scriptlets are deprecated and should be avoided. Use JSTL instead.
Secondly, your JavaScript code has no visibility of any of the variables used in your Java code. The Java is executed on the server, then some text (the HTML response) is sent to the browser. If it contains JavaScript, the browser runs the JavaScript.
I've rewritten what you're trying to achieve using JSTL instead of scriptlets for flow control and changing the JavaScript to get what you seem to be attempting:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<body>
<form action="Servletname" method="post" name="searchdatabase">
<c:if test="${not empty CusList}">
<table>
<tr>
<td> name :</td>
<td>
<select id="selectUsers" name="users" onChange='Choice();'>
<option> </option>
<c:forEach items="${CusList}" var="c">
<option value="${c.custId}"> <c:out value="${c.name}" /></option>
</c:forEach>
</select>
</td></tr>
<tr>
<td> id :</td>
<td>
<input type="text" id="ids" name="id" value="${CusList[0].custId}" >
</td></tr>
</table>
<!-- Note that I've moved the closing form tag and put it outside of this c:if block
because putting it here means it will only be output if your List is not empty -->
<script type="text/javascript">
function Choice() {
var y = document.getElementById("selectUsers");
var x = y.selectedIndex;
document.getElementById("ids").value = y.children[x].value;
}
</script>
</c:if>
</form><!-- outside of c:if because the opening tag is also outside of c:if -->
</body>
Edit:
I've just reread the question and realised that I haven't addressed your additional need of populating other inputs with other attributes of the customer.
As I said above, JavaScript has no visibility of data which is on the server, including your List of Customer objects. There are a few options available to you, but these are the two I would recommend:
Use HTML5 Data Attributes
HTML5 introduced data-* attributes for elements which can be accessed via your scripts. For example, you could do something like this:
<c:forEach items="${CusList}" var="c">
<option
value="${c.custId}"
data-surname="<c:out value="${c.surname}" />"
data-tel="<c:out value="${c.tel}" />"><!-- etc -->
<c:out value="${c.name}" />
</option>
</c:forEach>
Then in the JavaScript:
function Choice() {
var y = document.getElementById("selectUsers");
var x = y.selectedIndex;
var opt = y.children[x];
document.getElementById("ids").value = opt.value;
document.getElementById("surname").value = opt.dataset.surname;
document.getElementById("tel").value = opt.dataset.tel;
// etc
}
The downside of this approach is that if you have a large list with a high number of attributes you want to make available, that's a lot of text in the response.
Use AJAX
You could make an AJAX call in response to the select change and have the server return the customer data encoded in JSON format. The JavaScript would then decode the JSON and populate the elements with the correct values.
You'd need to research how to do this (there are plenty of tutorials available) but the steps in response to your select changing would be:
Disable the select box to prevent another change before you get the AJAX response from the server
Show some sort of throbber to indicate to the user that the data is being loaded
Make an AJAX request indicating the ID of the selected customer
The server responds with a JSON-encoded version of the corresponding customer object.
Update the inputs using the JSON data.
Hide the throbber and re-enable the select element.
The downside of this approach is that you'll need to learn how to properly use AJAX, including adding code to deal with errors (e.g., if the user loses network connectivity and you get no response from server to your AJAX request, you need to show an error message and have some sort of "retry" mechanism).

Jquery Form-Plugin doesn't get Submit - Basic understanding

I know there are several threads about this topic but I couldn't find one to fit my needs.
I'm simply trying to sand an form asynchronous using the jQueryFormPlugin.
I've got this basic form in index.php
<form id="test_form" action="http://127.0.0.1/MwebCms/index.php?admin=1&p=navigation&add=1" method="POST">
<table>
<tr>
<td>Title</td>
<td><input type="text" name="title"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Speichern" name="submit"></td>
</tr>
</table>
</form>
Now after including Jquery and the Jquery form plugin I added this in my JavaScript file:
$(document).ready(function() {
$('#test_form').ajaxForm(function() {
alert("test");
});
});
Now that's all fine and dandy, but if I now check in index.php for:
echo $_POST["title"];
It will never be set.
What am I doing wrong or is my basic understanding of the jqueryFormPlugin completely wrong at all?
Source: http://malsup.com/jquery/form/#getting-started
I found the mistake I made:
The $_POST was sent alright, but it wasn't displayed. After changing the jquery to the following:
$(document).ready(function() {
$('form').ajaxForm(function(data) {
$("body").html(data);
});
});
It all worked properly.

Is there a way to use a general purpose table structure for HTML pages?

In my project, I am using a lot of HTML pages where I am using table structures for better formatting the fields in the page. Now say for page A, I have written the following code:
<div align="center">
<u>Create User</u><br>
<table>
<tr>
<td>
User-name
</td>
<td>
<input type="text" name="username"><br>
</td>
</tr>
</table>
</div>
Now for a different page I may need to use 3 table rows to show all the fields in the page. So the basic structure is same in both the pages i.e. I am opening a div-opening table-opening table row- Opening table cells and closing them in the same order.
The only thing that will be different in the pages are number of table rows required. So I was wondering is there any functionality present so that I can create the pages easily without writing the same code again and again. It may act like a function which will take number of rows required. Is there any such functionality?
In HTML there is no function to do that. But if you can use PHP or JavaScript you can make a function to "render" your HTML.
For example, in PHP (server side):
<?php
function MakeTR($title, $name) {
print('<tr><td>'.$title.'</td><td><input type="text" name="'.$name.'"><br></td></tr>');
}
MakeTR('User-Name:','username');
MakeTR('Password:','pass');
MakeTR('Email:','email');
?>
Or you can do almost the same with JavaScript (client side):
<script>
function MakeTR(title, name) {
document.write('<tr><td>'+title+'</td><td><input type="text" name="'+name+'"><br></td></tr>');
}
MakeTR('User-Name:','username');
MakeTR('Password:','pass');
MakeTR('Email:','email');
</script>

Get javascript calulations to post as form data and display in php page

I am somewhat familiar with JavaScript and php and very familiar with HTML but have limited experience in getting them to work together. I have looked at many examples and am either not understanding or other posts do not specifically address my situation. I am trying to accomplish two things at the time of form submission. One is to retrieve the information from a div populated by innerHTML to post with the form and the other is to generate a unique number for the transaction at form posting and then display.
I have an HTML form that displays a generated list, each of which has a check box beside it. When a check box is selected I am using onclick="calTotal()" to calculate and display the total of all boxes checked. Code listed below.
The display script works perfectly and displays a value such as Total $125.00. What I need to do is post that total value when I post the form. The only value being passed at this time is the last check box value. Should that total be assigned within the JavaScript or should it be assigned within an input field?
The second part of my question is with the value of my algorithm that creates a unique transaction number. I want to generate that number upon submission of the form but then need to have it display on the php page. I have tested my algorithm separately and know it works correctly when I hard code the values in. I need to take values from the form and use them to calculate the transaction number. Once calculated it needs to be passed to the php page. Again I am not completely sure where to assign the value so that it passes to the next page.
Anything that will get me pointed in the right direction is appreciated.
<script type="text/javascript">
function calTotal() {
var ch, i=0;
var total=0;
while(ch=document.getElementsByName("amt")[i++]) {
if (ch.checked)
{
total=total+Number(ch.value);
}
}
var div=document.getElementById('divTotal');
total="$"+total.toFixed(2);
div.innerHTML= "Total: " +total;
return total;
}
function calTrans(x,y,z)
{
do calculations here
// concatenate into Trans number
var transNum=rm.concat(em,tm,am);
return transNum;
}
</script>
<form id="frmcheckout" action="out.php" method="post" onsubmit=calTrans()>
<table cellspacing="25">
<tbody>
<tr>
<th>Selection</th>
<th>Title</th>
<th>Cost</th>
</tr>
<tr>
<td>
<input type="checkbox" name="amt" value="$cost" onclick="calTotal()"></td>
<td>$Title</td>
<td>$cost</td>
</tr>
#end
</tbody>
</table>
<table>
<tbody>
<tr>
<td colspan="2">
E-mail address:<input type="text" name="email" value="E-mail required">
</td>
</tr>
<tr>
<td>
<div id="divTotal"></div>
</td>
<td>
<input type="submit" value="Submit";>
</td>
</tr>
</tbody>
</table>
</form>
Have you tried using hidden fields? e.g.
<input type="hidden" name="total" id="total" value="" >
You can use the same method for your unique transaction id. Then you can populate the hidden fields when you populate your "divTotal" div. e.g
document.getElementById("total").value = total;
This way when the form is submitted, the value will be passed to the script as "total" (in my example above). You can get values in php like this:
<?php
$total = $_POST["total"];
$amount = $_POST["amount"];
$email = $_POST["email"];
$transactionId = generateTransId(<<someparams>>);//YOUR FUNCTION TO CREATE TRANS ID
?>
Then to display your transaction id or output it anywhere on your php page, this is one example:
<div id="transId"><?php echo $transactionId; ?></div>

JS verify form data inside ajax-returned html

Ajax-returned HTML includes a table and a submit button (type=button)
The table includes jQuery routine to clone table row (each row allows choosing/uploading one file, and has two values: <input type="text"> for doc title, and <input type="file">.
<table id="MyTable">
<tr name="tr3" id="tr3">
<td>
<input type="text" name="dt[]" id="dt1">
</td>
<td>
<input type="file" name="fff[]" id="ff1">
</td>
</tr>
</table>
<input type="button" name="sub1" id="sub1" value="Submit" onclick="checkform();">
Upon form submit, I must check that each doc title has been filled-in, so the submit button calls a javascript routine:
function checkform()
{
if(document.updateprojectdocs.dt[0].value=='')
{
alert("Fields marked with an asterisk are required.");
document.updateprojectdocs.dt[0].focus();
return;
}
document.getElementById("TheForm").submit();
}
Of course, this does not work (script dies before form submit -- but submits if I remove the preceeding if structure). Can anyone tell me why and how to fix?
Also, there will be an indeterminate number of dt[] fields to check. How could I structure a loop to do this? I suspect jQuery's .find().each() could be used, but not sure what that would look like?
UPDATES:
Thanks to DaHaKa's response below, I am closer to a solution. I mod'd DaHaKa's suggested code into jQuery.
I was having trouble communicating with DaHaKa - for some reason his responses were not appearing until long, long, long after he posted them (the problem was probably on my end). While I was waiting (hours), I posted part of the problem in another question and ended up resolving it there. That other question grew into the FULL CORRECT ANSWER, and I direct future viewers there. Note that user thecodeparadox created a working JSFiddle of the full solution.
I have awarded this question to DaHaKa as he was more than willing and able to assist, but comm problems intervened. Thanks again, D.
In this case jQuery each function isn't neccessary, you can do it simple like this =>
try
<table id="MyTable">
<tr name="tr3" id="tr3">
<td>
<input type="text" name="dt" id="dt1">
</td>
<td>
<input type="file" name="fff" id="ff1">
</td>
</tr>
</table>
<input type="button" name="sub1" id="sub1" value="Submit">
JavaScript
document.getElementById("sub1").onclick = function(){
if (document.getElementById("dt1").value!=""){
document.getElementById("TheForm").submit();
} else {
alert("Empty Field(s) !");
}
};
you should use ids in JavaScript from html tags , NOT NAME tags
And whats about you file input , you could understand it from your server side scripting language like php , with super global variables $_FILES['file']['error'] types

Categories

Resources