"Undefined" when passing data to JavaScript from Android - javascript

I'm using this code but the value said "undefined" can anyone point me the problem?
this is my java class codes
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.frux.web.R.layout.activity_main);
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/index.html");
web.loadUrl("javascript:setValue(\""+ value +"\")");
}
and this is my webpage codes
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Whats your Name?
<input id="name" value="" />
<button onclick = "setValue()">Submit</button>
<script type="text/javascript">
function setValue(value){
var myValue = value;
document.getElementById("name").value = myValue;
}
</script>
</body>
</html>
I also try this one
web.loadUrl("javascript:setValue('"+ value +"')");
any thoughts will be highly appreciated
I used the codes in this HTML codes and its display nothing unlike the other codes above that I post.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript">
function setValue(amount1)
{
myValue = amount1;
document.getElementById("amount").value = myValue;
}
function rand ( n )
{
document.getElementById("orderRefId").value = ( Math.floor ( Math.random ( ) * n + 1 ) );
}
</script>
</head>
<body onLoad="rand(200000);setValue();">
<!--
Note: https://www.pesopay.com/b2c2/eng/payment/payForm.jsp for live payment URL
https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp for test payment URL
-->
<form method="POST" name="frmPayment" action="https://test.pesopay.com/b2cDemo/eng/payment/payForm.jsp">
<table>
<tbody>
<tr>
<td>Order Reference No. (your reference number for every transaction that has transpired):</td>
<td><input type="text" id="orderRefId" name="orderRef" value="Test-001"/></td>
</tr>
<tr>
<td>Amount:</td>
<td><input type="text" name="amount" id="amount" value=""/></td>
</tr>
<tr>
<td>Currency Code - "608" for Philippine Peso, "840" for US Dollar:</td>
<td><input type="text" name="currCode" value="608"/></td>
</tr>
<tr>
<td>Language:</td>
<td><input type="text" name="lang" value="E"/></td>
</tr>
<tr>
<td>Merchant ID (the merchant identification number that was issued to you - merchant IDs between test account and live account are not the same):</td>
<td><input type="text" name="merchantId" value="18056869"/></td>
</tr>
<tr>
<td>Redirect to a URL upon failed transaction:</td>
<td><input type="text" name="failUrl" value="http://www.yahoo.com?flag=failed"/></td>
</tr>
<tr>
<td>Redirect to a URL upon successful transaction:</td>
<td><input type="text" name="successUrl" value="http://www.google.com?flag=success"/></td>
</tr>
<tr>
<td>Redirect to a URL upon canceled transaction:</td>
<td><input type="text" name="cancelUrl" value="http://www.altavista.com?flag=cancel"/></td>
</tr>
<tr>
<td>Type of payment (normal sales or authorized i.e. hold payment):</td>
<td><input type="text" name="payType" value="N"/></td>
</tr>
<tr>
<td>Payment Method - Change to "ALL" for all the activated payment methods in the account, Change to "BancNet" for BancNet debit card payments only, Change to "GCASH" for GCash mobile payments only, Change to "CC" for credit card payments only:</td>
<td><input type="text" name="payMethod" value="ALL"/></td>
</tr>
<tr>
<td>Remark:</td>
<td><input type="text" name="remark" value="Asiapay Test"/></td>
</tr>
<!--<tr>
<td>Redirect:</td>
<td><input type="text" name="redirect" value="1"/></td>
</tr>-->
<tr>
<td></td>
</tr>
<input type="submit" value="Submit">
</tbody>
</table>
</form>
</body>
</html>

Wrap your passed value in double quotes:
web.loadUrl("javascript:setValue(\""+value+"\")");
I got this! When you call loadUrl for the second time the page has not loaded yet. The solution would be attaching your setValue call to window.onload event:
super.loadUrl("javascript:window.onload = function(){setValue(\"haha\");};");
This code loads 'haha' into input correctly.

Try wrapping your value in a single quotes like so
web.loadUrl("javascript:setValue('"+ value +"')");

I had this issue when trying to access the DOM before it was ready. devmilles.com's solution worked but I spent a little more time experimenting.
Both of
webView.loadUrl("javascript:window.addEventListener('DOMContentLoaded',
function(){setValue('haha');}, false);");
webView.loadUrl("javascript:window.addEventListener('load',
function(){setValue('haha');}, false);");
worked for me, but attaching the event to document instead of window did not. DOMContentLoaded, where supported, responds slightly faster than load.
Additionally, it turns out that WebViewClient has always had an onPageFinished() event, which appears to work like the load event
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:setValue('haha');");
}
});
Lastly, I could emulate the behaviour with
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
view.loadUrl("javascript:setValue('haha');");
}
}
});
but I see no reason to use that over the WebViewClient approach (they may or may not be equivalent).

I am also facing same problem.But the issue is resolved using below way.
String testValue="abcdedfg";
String value = "\'"+testValue+"\'";
web.loadUrl("javascript:setValue(\""+value+"\")");

Related

Any Javascript event for form population?

I need to call Javascript function after form value gets populated from the backend. So far I went through these Javascript events. I don't see any existing events I can use for this purpose.
I don't want a jQuery based solution. Any ideas how I can do this simply?
Edit:
I am populating the values in Java (Spring boot) in the backend. I am not having problems with populating the values to the screen. I want to know whether I can call any Javascript event after the values have been populated in the screen.
Edit2:
enter <form action=# th:action="#{/main}" name="Form2" th:object="${formObject}"
method="post">
<table
id="collateral_position_table">
<tr class="header">
<th style="text-align: left" colspan="4"
id="collateral_position_title">Collateral Position</th>
</tr>
<tr>
<td >NPV</td>
<td ><input
name="otherNpv" id="otherNpv"
th:value="${collateralAppliqueInputForm.otherNPV}"
style="text-align:right" type="text"/></td>
<td >NPV As Of Date</td>
<td><input
name="otherAsOfDate" id="otherAsOfDate"
th:value="${collateralAppliqueInputForm.otherAsOfDate}"
style="text-align:right" type="text" /></td>
</tr>
<tr>
<td colspan="4"><input
type="submit" value="Update" name="action"/></td>
</tr>
</table>
</form> here
And the controller to populate this form
#RequestMapping(value = {"/main"}, method = RequestMethod.POST,params="action=Update")
public String updateForm( #Valid #ModelAttribute(value = "formObject") FormObject formObject, HttpServletRequest request, HttpServletResponse response,BindingResult result, Model model, Principal principal) {
formObject=methodToPopulateTheForm();
model.addAttribute("formObject", formObject);
}
so I solution was to use onload on the page body itself.

How to return values from external javascript function

I have a function in an external java script file and I dont know how to call and return the value that my function returns in text properly. When I click place order, I want the values to be calculated by my function and then the final value to be displayed underneath the place order box. I can get my function to alert if I enter nothing but I can't get it to return my final value- what am I doing wrong?
function sum2()
{
var one = document.getElementById("book_1").value;
var two = document.getElementById("book_2").value;
var three = document.getElementById("book_3").value;
if ((one == "")||(two == "")||(three == ""))
{
alert ('Error', 'values missing');
}
else
{
var sum1 = one * 19.99;
var sum2 = two * 86.00;
var sum3 = three * 55.00;
var sum = sum1 + sum2 + sum3;
document.getElementById('output').value = sum;
document.write(sum);
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Work</title>
<script type="text/javascript" src="ex4.js"></script>
</head>
<body>
<div id="container">
<h2>Order Books Online</h2>
<form action="" method="post" id=”frm”>
<fieldset>
<table border="0">
<tr>
<th>Book</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Basics of C++</td>
<td><input type="text" size="3" id="book_1" /></td>
<td>$19.99</td>
</tr>
<tr>
<td>Program Development in Perl</td>
<td><input type="text" size="3" id="book_2" /></td>
<td>$86.00</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td><input type="text" size="3" id="book_3" /></td>
<td>$55.00</td>
</tr>
</table>
<br /><br />
<input type="submit" onclick="sum2(); return false;" value="Place Order" id="sub" />
</fieldset>
</form>
</div>
</body>
</html>
Try this, its working, output is displaying on last.
function sum2()
{
var one = document.getElementById("book_1").value;
var two = document.getElementById("book_2").value;
var three = document.getElementById("book_3").value;
if ((one == "")||(two == "")||(three == ""))
{
alert ('Error', 'values missing');
}
else
{
var sum1 = one * 19.99;
var sum2 = two * 86.00;
var sum3 = three * 55.00;
var sum = sum1 + sum2 + sum3;
document.getElementById('output').innerHTML = sum;
// document.write(sum);
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Work</title>
<script type="text/javascript" src="ex4.js"></script>
</head>
<body>
<div id="container">
<h2>Order Books Online</h2>
<form action="" method="post" id=”frm”>
<fieldset>
<table border="0">
<tr>
<th>Book</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Basics of C++</td>
<td><input type="text" size="3" id="book_1" /></td>
<td>$19.99</td>
</tr>
<tr>
<td>Program Development in Perl</td>
<td><input type="text" size="3" id="book_2" /></td>
<td>$86.00</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td><input type="text" size="3" id="book_3" /></td>
<td>$55.00</td>
</tr>
</table>
<br /><br />
<input type="submit" onclick="sum2(); return false;" value="Place Order" id="sub" />
</fieldset>
</form>
</div>
<div id="output"></div>
</body>
</html>
The use of document.write() doesn't seem to be what you'd want here. (And, honestly, should be avoided in general anyway.)
However, this will do what you want:
document.getElementById('output').value = sum;
All you need is an HTML input element which has that id (which your HTML is currently missing):
<input type="text" id="output" />
(Additionally, your JavaScript is missing a closing }, which is a syntax error.)
Once you have that HTML element and remove the document.write() call, this should be outputting the value correctly.
If you want to output to something other than another input element, then you wouldn't use .value but something more like .innerHTML instead:
document.getElementById('output').innerHTML = sum;
with an element such as:
<span id="output"></span>
As an aside regarding terminology, this isn't "returning" the value from the function. "Return" has a very specific meaning when it comes to functions, it's when the function itself results in a value using the return keyword, passing that value back up the stack to the code which called the function.
This function is writing a value to the HTML, but it's not returning anything.

HTML Table onclick not firing in Android

I am trying to get an html table to work properly in android with an onclick event for certain rows and cells.
It's supposed to get user input from 2 rounds, then add them up and then keep adding up after each round till the 7th round. This is my code so far and everything runs fine on the PC but when I go to do it through my tablet ver 4.2.2 I get no results from the inputs.
Sample Code:
Javascript / HTML Code:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<script language="JavaScript" type="text/javascript">
/*<![CDATA[*/
function calcP1()
{
var p1ro1 = document.getElementById("p1r1").value;
var p1ro2 = document.getElementById("p1r2").value;
var pl1 = document.getElementById("p1").value;
var sum1 = (parseInt(p1ro1) + parseInt(p1ro2));
document.getElementById("sp1r2").value = sum1;
}
/*]]>*/
</script>
</head>
<body>
<table>
<tr>
<td>Player Names:</td>
<td><input type="text" id="p1"/></td>
</tr>
<tr>
<td>Round 1: 2 Books</td>
<td><input type="text" id="p1r1"/></td>
</tr>
<tr>
<td>Round 2: 1 Book 1 Run</td>
<td><input type="text" id="p1r2"onclick="calcP1();"/></td>
</tr>
<tr>
<td>Total Round 1 & 2 </td>
<td bgcolor="#00FF00"><input type="text" id="sp1r2" readonly /></td>
</tr>
</table>
</body>
</html>
TableActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.table);
wv = (WebView)findViewById(R.id.tables);
wv.loadUrl("file:///android_asset/ScoreCard.html");
}
Would I have to use addJavascriptInterface into my TableActivity so how? Thank you.
try adding these lines to your activity after you get a reference to the webview but before you load the url
wv.setWebChromeClient(new WebChromeClient());
wv.getSettings().setJavaScriptEnabled(true);
adding a javascriptinterface will allow you to call java methods within the application from your javascript and vice versa

Passing values from multiple input fields to popup using javascript/jquery

I am trying to pass multiple input fields to a popup page.
Here's what I have done:
<tr>
<th>Item Category</th>
<td><input type="text" name="object_category" disabled="disabled" id="pid1" />
</td>
<tr>
<th>Item Name</th>
<td><input type="text" name="object_name" disabled="disabled" id="pid2" />
<input type="button" id="item_name" name="choice" onClick="selectValue2('id2')" value="?"></td>
</tr>
The value of is filled up by returning its value from a different page.
Now I want to pass the values of id: pid1 and id:pid2 to a new popup page using javascript.
Here's my selectValue2() function definition:
function selectValue2(pid2){
// open popup window and pass field id
var category = getElementById('pid1');
window.open("search_item.php?id=pid2&&cat="+category+""",'popuppage',
'width=600,toolbar=1,resizable=0,scrollbars=yes,height=400,top=100,left=100');
}
But, selectValue2 is not working, as popup is not opening. How to pass the values of these two fields to my new popup?
Here you have the problem:
var category = getElementById('pid1');
You need to replace it by :
var category = document.getElementById('pid1');
As getElementById works with document object.
You need to use
document.getElementById
Further, you will need to use value, because getElementById is grabbing the entire element
Your code would look something like:
function selectValue2(pid2){
// open popup window and pass field id
var category = document.getElementById('pid1').value;
window.open("search_item.php?id=pid2&&cat=" + category + """,'popuppage',
'width=600,toolbar=1,resizable=0,scrollbars=yes,height=400,top=100,left=100');
}
You can do something similar for the 2nd pid value - not sure why you are passing it to the function.
try this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function selectValue2(){
// open popup window and pass field id
var category = document.getElementById('pid1').value;
var pid = document.getElementById('pid2').value;
window.open("test.php?id="+pid+"&cat="+category+"",'popuppage',
'width=600,toolbar=1,resizable=0,scrollbars=yes,height=400,top=100,left=100');
}
</script>
</head>
<body>
<tr>
<th>Item Category</th>
<td><input type="text" name="object_category" id="pid1" />
</td>
<tr>
<th>Item Name</th>
<td><input type="text" name="object_name" id="pid2" />
<input type="button" id="item_name" name="choice" onClick="selectValue2()" value="?"></td>
</tr>
</body>
</html>
for Jquery,
var pid1Val = $("#pid1").val();
var pid2Val = $("#pid2").val()
for Javascript,
var pid1Val = document.getElementById('pid1');
var pid2Val = document.getElementById('pid2');

Load a script for the elements of an array

I am trying to create a dynamic form where you can order something.
In basic form, we have one row, but if you want to order more things we can dynamically without reloading the page, add the new row. So far everything is working properly for me, but in this form we have two dropdown ("input select") lists. These drop-down lists are dependent on each other and do not know how to load them the relationship between them and the option of choice. I have tried many different examples from the internet, but always work correctly only the first default row. Dynamically created rows are no longer dependent on one another.
If I am doing something wrong, and you know a better way, please show me this way.
I ask you for help, because I really depend on that. Thank you in advance. ;)
Update
Hmm .. Now I understand, but I do not know much how to use it in my web page code. Will show you the web page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><br>
<html><br>
<head><br>
<title>Dynamic forms</title><br>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><br>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><br>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script><br>
<script language="javascript" src="chainedselects.js"></script><br>
<script language="javascript" src="exampleconfig2.js"></script><br>
</head>
<body onload="initListGroup('vehicles', document.formm.elements['group[]'], document.formm.elements['product[]'], 'cs')">
<script type="text/javascript">
$(document).ready(function(){
var i = 2;
var templateRow = jQuery.format($("#template").val());
function addRow() {
var ii = i++;
$(templateRow(ii)).appendTo("#listProducts tbody");
$("#removeProduct_" + ii).click(function(){
$("#row_" + ii).remove();
});
}
$("#addProduct").click(addRow);
});
</script>
<!-- Template row in the table -->
<textarea id="template" style="display:none;" cols="1" rows="1">
<tr id="row_{0}" valign="top">
<td>{0}.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="remove.png" id="removeProduct_{0}" alt="remove"></td>
</tr>
</textarea>
<!-- This summary table -->
<form name="formm" action="parser.php" method="post">
<table id="listProducts" name="list">
<thead>
<tr>
<th>Nr</th>
<th>Group</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>+/-</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="3" align="left">
<input type="submit" name="send" value="Send" style="width: 100px;">
</th>
</tr>
</tfoot>
<tbody>
<tr valign="top">
<td>1.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="add.png" id="addProduct" alt="add"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
This is a parser.php:
<?php
$data = array();
$data['Groups'] = $_POST['group'];
$data['Products'] = $_POST['product'];
$data['Prices'] = $_POST['price'];
$data['Quantity'] = $_POST['quantity'];
$result = print_r($data,true);
echo "<pre>$result</pre>";
?>
Here is link to all code.
The click events are not attached to the newly created rows, so you need to make sure that any new rows, after they are created have click events attached to them.
function dependantFunction() {
/* code */
}
function addNewRow() {
var a=document.createElement("div");
var b=document.createElement("img");
b.src="images/add.png";
b.addEventListener("click", dependantFunction, false);
a.appendChild(b);
document.getElementById("rowholder").append(a);
}
Then all new rows should have all the necessary events attached to them.

Categories

Resources