how to pass alerted values in javascript into another page [duplicate] - javascript

Hi I have a table that was created in javascript, what I need to know is how to pass the values in row 1 or 2 into a aspx page using javascript with the click of a button:
here is my javascript code:
newContent += Hesto.Html.StartTR(item.CommonCable, 'lineInfoRow');
newContent += Hesto.Html.CreateTD('<input type="button" value="Print" id="btnprint" onclick="Redirect()">',null);
newContent += Hesto.Html.CreateTD(item.CommonCable, null, null);
newContent += Hesto.Html.CreateTD(item.Wire, null, null);
newContent += Hesto.Html.CreateTD(item.WireLength * 1000, null, 'centerAlign');
newContent += Hesto.Html.CreateTD(item.TerminalA, null, (sideFlag == 1 ? 'highlightOneSide' : (sideFlag == 3 ? 'highlightTwoSides' : 'highlightNone')));
newContent += Hesto.Html.CreateTD(item.SealA, null, (sideFlag == 1 ? 'highlightOneSide' : (sideFlag == 3 ? 'highlightTwoSides' : 'highlightNone')));
newContent += Hesto.Html.CreateTD(item.TerminalB, null, (sideFlag == 2 ? 'highlightOneSide' : (sideFlag == 3 ? 'highlightTwoSides' : 'highlightNone')));
newContent += Hesto.Html.CreateTD(item.SealB, null, (sideFlag == 2 ? 'highlightOneSide' : (sideFlag == 3 ? 'highlightTwoSides' : 'highlightNone')));
newContent = Hesto.Html.EndTR(newContent);
});
$('#AlternativeReworkCablesList').html(newContent);
}
here is my redirect page:
function Redirect() {
window.open ("http://10.19.13.67/ReworkLabels/Default.aspx","my window");
return false;
}

You have a few options: You could save the data in a cookie for re-use later, you could pass the data to the next page as a series of GET variables, or you could load the next page using AJAX so that your variables remain available.
Since you're using ASP, you could do something like this:
function Redirect() {
window.open ("http://10.19.13.67/ReworkLabels/Default.aspx?myVariable=" + myVariable,"my window");
return false;
}

To send big amount of data you can try this:
Create form with method post and action equal to url you want to redirect to (form can be hidden — it is not problem)
Create textarea/text field (not neccessary) in this form
Put your data in this textarea
Submit form via JS
Receive data on new page
Note, that javascript will escape data in this form. To unescape it use unescape() function.

Related

JSF custom component, pass data from JSF to Javascript and reverse

I want to build a custom component in JSF that could :
retrieve a value from its value attribute
display this value
be able to update this value through Javascript (will update bean attribute used in value component attribute)
<t:myComponent value="#{myBean.value}" />
will display
<div>
<input id="my_input" type="text" value="my_value" />
<button onclick="update_value(document.getElementById('my_input').value)">update</button>
</div>
<script>
function update_value(val) {
// ???
}
</script>
and when we click the button, it will change myBean.value by the current content of the input (that user can change obviously).
As I understand, it looks easy to display the value in the component with the ResponseWriter but I do not understand how to build Javascript to call the component to change the value of the component.
example
// myBean.value = "foo"
<t:myComponent value="#{myBean.value}" />
// displays
<div>
<input id="my_input" type="text" value="foo" />
<button ...>update</button>
</div>
// user change input content by "bar"
// user click the update button
// myBean.value = "bar" now
Pass Bean Values to Javascript
There are some ways to do this. I think the most obvious way of doing this is rendering a script tag and putting the information in this.
Single Value:
writer.write("var value = '" + yourValue + "';");
Map Values:
String s = "var values = {";
for (Entry<String, String> entry : map.entrySet()) {
s += entry.getKey() + ": '" + entry.getValue() + "',\n";
}
s = s.trim().substring(1, s.length() - 1); // removes last ','
s += "};";
writer.write(s);
List Values:
String s = "var values = [";
for (String value : list) {
s += "'" + value + "', ";
}
s = s.trim().substring(1, s.length() - 1); // removes last ','
s += "];";
writer.write(s);
I would recommend not to put everthing in this script because this would be very much code in the encode methods. Rather have the static javascript code in a .js file and just write the dynamic content in the script tag. See how to get variables from other scripts.
Another way does not need a script tag. This way would call a js method like this:
function init(values) {
// ...
}
In the Renderer just call the js method:
facesContext.getPartialViewContext().getEvalScripts().add("init(" + yourValue + ");");
Pass Javascript values to Server-Side
Just include an input like this:
// just a random unique id
String generatedId = context.getClientId(context) + ":utility";
// ...
writer.startElement("input", null);
writer.writeAttribute("id", generatedId, null);
writer.writeAttribute("name", generatedId, null);
writer.writeAttribute("type", "hidden", null);
writer.endElement("input");
Then pass the generatedId with the other values to javascript.
In Javascript:
function setValues(value) {
// hiddenInputId is the server-side generatedId
var input = document.getElementId(hiddenInputId);
input.value = value;
}
Then just send an ajax request and get the values in the decode method like this:
// same id as in the encode methods
String generatedId = context.getClientId(context) + ":utility";
Map<String, String> map = facesContext.getExternalContext().getRequestParameterMap();
String value = map.get(generatedId);
// ...

How to populate html element using javascript prior to page_load()?

Maybe a chicken/egg problem.
Based on this answer: https://stackoverflow.com/a/27190520/1438215
I want to use javascript to populate the value of an asp.net hidden field (as soon as it's possible), and then access the value of that populated field in the server-side Page_Load event.
Sample:
aspx portion:
<div id="div_BrowserWindowName" style="visibility:hidden;">
<input type="hidden" name="ctl00$ctl00$BodyContent$MainContent$hf_BrowserWindowName" id="BodyContent_MainContent_hf_BrowserWindowName" />
</div>
<script type="text/javascript">
function PopBrowserWindowName() {
if (typeof window.name != undefined) {
if (window.name == '') {
var d = new Date();
window.name = '_myWnd_' + d.getUTCHours() + d.getUTCMinutes() + d.getUTCSeconds() + d.getUTCMilliseconds();
}
var eDiv = document.getElementById('div_BrowserWindowName');
var e = eDiv.getElementsByTagName('input')[0];
e.value = window.name;
alert(e.value);
}
}
window.onload = PopBrowserWindowName();
</script>
aspx.cs portion (page_load) event:
if (hf_BrowserWindowName != null)
{string winID = hf_BrowserWindowName.Value;}
This does works during postbacks, but does not work on the page's initial load.
Prior to Page_Load, there is no HTML or JavaScript because the Response has not been sent to the client yet. You need to learn the ASP.NET Page Lifecycle.
You can use server side code to populate the information, or after the page is sent to the client you can have some JavaScript populate the information.

How to access data in my razor view from javascript?

in my mvc razor view, I have these codes:
#if (Model != null) {
if (Model.Meals != null)
{
var grid = new WebGrid(Model.Meals, defaultSort: "MDate");
double Total = Model.Meals.Where(x => x.FINtravelID == Model.FINtravelID).Sum( t =>t.MTAmount);
And in the script header, I need to get the data of "Total" above in this code:
$(function () {
$("#grid tbody").append('<tr><td><b>Total</b></td><td><b>' + Total.toFixed(2) + '</b> </td></tr>');
})
I have tried to add # in front of Total, but it does not compile, anybody kow how to make it working?
You won't be able to retrieve Total outside of the code block unless you nest it within an element or a hidden input and then retrieved that data with JS. So, for example, if your code looked like this:
#if (Model != null)
{
if (Model.Meals != null)
{
var grid = new WebGrid(Model.Meals, defaultSort: "MDate");
double Total = Model.Meals.Where(x => x.FINtravelID == Model.FINtravelID).Sum( t =>t.MTAmount);
<div id="Total">#Total</div>
}
}
You could grab the data with JS, but you will need to cast the value as a number in order to use the isFixed() method on it because JS implicitly types as string. So use Number() to convert string => double:
<script type="text/javascript">
$(function() {
var total = Number(document.getElementById('Total').innerHTML).toFixed(2);
$("#grid tbody").append('<tr><td><b>Total</b></td><td><b>' + total + '</b> </td></tr>');
});
</script>

Print cross using javascript in html

I have this code on my external javascript
function cross()
{
var output2 = document.getElementById('output2');
var a = "*"
, b = " "
, i = 0
, j = 0
, k = 0
;
for(i = 1, k = input; i <= input; i++, k--)
{
for(j = 1; j <= input; j++)
{
if (j == i || j == k)
{
output2.value += a;
}
else
{
output2.value += b;
}
output2.value += '\n';
}
}
}
and this html button on my 1st page + text area on my 2nd page so the text area will show in second page (halaman.html) after I click the button on 1st page.
<!-- code page 1-->
<input type="button" value="Muncul page baru" onclick="cross();"><br />
<!-- code page 2-->
<textarea id="output2" rows="20" cols="90"></textarea>
The cross doesn't show on the 2nd page. What's wrong and what should I do?
JavaScript can not set the value of an element on a page that is not even created yet.
You can submit a form with the value, but you would have to use a GET request since JavaScript will not be able to access the POST data without some help a serverside language.
Other options is to use localstorage. Set it on the first page, read it on the second.
I think this is not possible to do. Because when you navigate to second page, there is no javascript available from previous page. You need to store your result in server state or pass the result through the querystring
The javascript only works on the first page. You could send a GET variable through the URL and check for that variable on the second page.
You could also put page2 on a iframe.

How to add a parameter to the URL?

My current URL is: http://something.com/mobiles.php?brand=samsung
Now when a user clicks on a minimum price filter (say 300), I want my URL to become
http://something.com/mobiles.php?brand=samsung&priceMin=300
In other words, I am looking for a javascript function which will add a specified parameter in the current URL and then re-direct the webpage to the new URL.
Note: If no parameters are set then the function should add ? instead of &
i.e. if the current URL is http://something.com/mobiles.php then page should be re-directed to http://something.com/mobiles.php?priceMin=300
instead of http://something.com/mobiles.php&priceMin=300
try something like this, it should consider also cases when you already have that param in url:
function addOrUpdateUrlParam(name, value)
{
var href = window.location.href;
var regex = new RegExp("[&\\?]" + name + "=");
if(regex.test(href))
{
regex = new RegExp("([&\\?])" + name + "=\\d+");
window.location.href = href.replace(regex, "$1" + name + "=" + value);
}
else
{
if(href.indexOf("?") > -1)
window.location.href = href + "&" + name + "=" + value;
else
window.location.href = href + "?" + name + "=" + value;
}
}
then you invoke it like in your case:
addOrUpdateUrlParam('priceMin', 300);
Actually this is totally trivial, because the javascript location object already deals with this. Just encapsulate this one-liner into a function to re-use it with links etc:
<script>
function addParam(v) {
window.location.search += '&' + v;
}
</script>
add priceMin=300
There is no need to check for ? as this is already the search part and you only need to add the param.
If you don't want to even make use of a function you can write as so:
add priceMin=300
Keep in mind that this does exactly what you've asked for: To add that specific parameter. It can already be part of the search part because you can have the same parameter more than once in an URI. You might want to normalize that within your application, but that's another field. I would centralize URL-normalization into a function of it's own.
Edit:
In discussion about the accepted answer above it became clear, that the following conditions should be met to get a working function:
if the parameter already exists, it should be changed.
if the parameter already exists multiple times, only the changed copy should survive.
if the parameter already exists, but have no value, the value should be set.
As search already provides the search string, the only thing left to achieve is to parse that query-info part into the name and value pairs, change or add the missing name and value and then add it back to search:
<script>
function setParam(name, value) {
var l = window.location;
/* build params */
var params = {};
var x = /(?:\??)([^=&?]+)=?([^&?]*)/g;
var s = l.search;
for(var r = x.exec(s); r; r = x.exec(s))
{
r[1] = decodeURIComponent(r[1]);
if (!r[2]) r[2] = '%%';
params[r[1]] = r[2];
}
/* set param */
params[name] = encodeURIComponent(value);
/* build search */
var search = [];
for(var i in params)
{
var p = encodeURIComponent(i);
var v = params[i];
if (v != '%%') p += '=' + v;
search.push(p);
}
search = search.join('&');
/* execute search */
l.search = search;
}
</script>
add priceMin=300
This at least is a bit more robust as it can deal with URLs like these:
test.html?a?b&c&test=foo&priceMin=300
Or even:
test.html?a?b&c&test=foo&pri%63eMin=300
Additionally, the added name and value are always properly encoded. Where this might fail is if a parameter name results in an illegal property js label.
if(location.search === "") {
location.href = location.href + "?priceMin=300";
} else {
location.href = location.href + "&priceMin=300";
}
In case location.search === "", then there is no ? part.
So add ?newpart so that it becomes .php?newpart.
Otherwise there is a ? part already.
So add &newpart so that it becomes .php?existingpart&newpart.
Thanks to hakre, you can also simply set it like:
location.search += "&newpart";
It will automatically add ? if necessary (if not apparent, it will make it ?&newpart this way, but that should not matter).
I rewrite the correct answer in PHP:
function addOrUpdateUrlParam($name, $value){
$href = $_SERVER['REQUEST_URI'];
$regex = '/[&\\?]' . $name . "=/";
if(preg_match($regex, $href)){
$regex = '([&\\?])'.$name.'=\\d+';
$link = preg_replace($regex, "$1" . $name . "=" . $value, $href);
}else{
if(strpos($href, '?')!=false){
$link = $href . "&" . $name . "=" . $value;
}else{
$link = $href . "?" . $name . "=" . $value;
}
}
return $link;
}
I hope that help's someone...
There is an more elegant solution available, no need to write your own function.
This will add/update and take care of any ? or & you might need.
var params = new URLSearchParams(window.location.search);
params.set("name", "value");
window.location.search = params.toString();
var applyMinPrice = function(minPrice) {
var existingParams = (location.href.indexOf('?') !== -1),
separator = existingParams ? '&' : '?',
newParams = separator + 'priceMin=' + minPrice;
location.href += newParams;
}
If you're having the user fill out a textfield with a minimum price, why not let the form submit as a GET-request with a blank action? IIRC, that should do just what you want, without any javascript.
<FORM action="" method="get">
<P>
<LABEL for="brand">Brand: </LABEL>
<INPUT type="text" id="brand"><BR>
<LABEL for="priceMin">Minimum Price: </LABEL>
<INPUT type="text" id="priceMin"><BR>
</P>
use var urlString = window.location to get the url
check if the url already contains a '?' with urlString.indexOf('?'), -1 means it doesnt exist.
set window.location to redirect
this is like 101 of javascript. try some search engines!
<html>
<body>
..
..
..
<?php
$priceMinValue= addslashes ( $_GET['priceMin']);
if (!empty($priceMin)) {
$link = "currentpage.php?priceMin=". $priceMinValue;
die("<script>location.href = '".$link. "'</script>");
}
?>
</body>
</html>

Categories