Take Postcode to New Field in New Window - javascript

I have a read only field on a html field which has a name of _Dataaddr_postcode I now need to capture this data and pass it into a new window which loads another file (proxcomp.asp) and use the data in a field on this page the field has an ID of inpAddr.
I have this code so far
<script type="text/javascript">
var pcodeStart = document.getElementbyId("_Dataaddr_postcode");
var newWindow;
function makeNewWindow( ) {
if (!newWindow || newWindow.closed) {
newWindow = window.open("../hpwprox/proxcomp.asp","sub","status=0,title=0,height=600,width=800");
setTimeout("writeToWindow( )", 50);
} else if (newWindow.focus) {
newWindow.focus( );
}
}
</script>
<input type="button" value="Create New Window" onclick="makeNewWindow();" />
Can someone tell me how to achieve this with some sample code?
Thanks
Justin.

Passing just that one field as a form input to the server-side script:
var genForm = document.createElement("form");
genForm.target = "sub";
genForm.method = "get"; // or "post" if appropriate
genForm.action = "../hpwprox/proxcomp.asp";
var genInput = document.createElement("input");
genInput.type = "hidden";
genInput.name = "inpAddr";
genInput.value = pcodeStart.value;
genForm.appendChild(genInput);
document.body.appendChild(genForm);
if(!newWindow || newWindow.closed) {
window.open("", "sub", "status=0,title=0,height=600,width=800");
} else if(newWindow.focus) {
newWindow.focus();
}
genForm.submit();
If you wish to use client-side code to set a textbox in the pop-up rather than server-side code, you need to do it from the pop-up window to avoid the delay you would add otherwise and the page's load time from "racing" each other. In JavaScript, global variables are properties of the window object they exist inside of, and window.opener gives the window that opened this one. Note that because of the same-origin policy, the two windows need to have the same protocol, hostname, and port number in their URLs.
// Using the variable referring to the text box:
document.getElementById('inpAddr').value = window.opener.pcodeStart.value;
// Or even using getElementById directly:
document.getElementById('inpAddr').value = window.opener.document.getElementById('inpAddr').value
You can omit the window. part of window.opener if you want to, provided that you are using no variable called opener.

Maybe doing this:
newWindow.document.getElementById('inpAddr').value = pcodeStart;
Or from the open window:
document.getElementById('inpAddr').value = opener.document.getElementbyId("_Dataaddr_postcode").value;
Please read this great article!

Related

Error on javascript queryselector

I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.
Here the main javascript
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.
<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">
I tried 2 functions call.
document.getElementByName("satisfaction_case_number").value = getParameterByName("case")
and
document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")
I have to say I'm kinda blind here. Any flag would be appreciated.
Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.
I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks
Wait till the window has loaded then execute it;
window.onload = function () {
document.getElementsByName("satisfaction_case_number")[0].value = getParameterByName('case');
}
The form is being dynamically generated after the rest of your content has loaded, It's unreliable to rely on timing as connection speeds can vary, using
window.onload will ensure the page is fully loaded before executing.
I tested this by throttling my browser connection to "Slow 3G" and it still worked, Your original piece of code that selected the element by name wasn't selecting the first entry in the NodeList, to do this you need to add [0] before the .value
You can try document.querySelector('input[id *= satisfaction_case_number]').value = 'example'
setTimeout(function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}, 1000);
or try to modify the code that creates HubSpot form:
hbspt.forms.create({
// ...
onFormReady: function () {
var input = document.querySelector('[id^="satisfaction_case_number"]');
input.value = getParameterByName('case');
input.dispatchEvent(new Event('change'));
}
});

Passing a Javascript variable to C# code in <script> section

var code = $('#hastane').val();
var url = '#Url.Action("HataIstatistikleriExcel", "Reports", new
{
baslangicDonem = Model.BaslangicDonem,
bitisDonem = Model.BitisDonem,
hospitalCode = code
})';
window.open(url);
I can't pass code variable to Url.Action... "It shows cannot resolve code"
Quickest way to solve it by adding a placeholder in MVC built URL then replace that value dynamically using javascript while click event is triggered as shown below.
$("#expHastaneAna").click(function () {
var code = 'dynamicCode';
var url = '#Url.Action("HataIstatistikleriExcel", "Reports", new
{
baslangicDonem = Model.BaslangicDonem,
bitisDonem = Model.BitisDonem,
hospitalCode = "{0}"
})';
url = decodeURI(url);
url = url.replace("{0}", code);
url = decodeURI(url);
console.log(url);
});
You cannot directly access Server side variable in JavaScript. First you have to assign it's value to hidden field and then get value from that hidden field in JavaScript.

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

Passing a value from child window to text field in parent window

I'm trying to pass and insert value from child window to the value attribute of text field which located in parent window, and not to its property. I've tried all the following but no luck so far:
Child window:
function getFile(oImg){
var id = <?php echo $id; ?>;
var editPage = window.opener.document;
oSrc = oImg.src;
lastSlash = oSrc.lastIndexOf('/');
oName = oSrc.substr(lastSlash+1);
var logo = 'logo'+id, logoHolder = 'logoHolder'+id;
//window.opener.document.getElementById(logo).value = oName;
//window.opener.document.getElementById(logo).setAttribute("value", oName);
//window.opener.document.getElementById(logo).innerHTML = oName;
//window.opener.document.getElementById(logo).setValue = oName;
window.opener.document.getElementById(logoHolder).src = "templates/img/user/" + oName;
this.close()
}
Parent page:
<input type="text" id="logo1" name="logo1" value="VALUE-SHOULD-BE-INSERTED-HERE" />
The first one just display the value in the text-field but when I'm trying to save it with jquery, the value is actually empty. Any idea?
window.opener.document.getElementById(logo).value = fileName;
This should work—except that logo should be a string. Otherwise the opened child window will try to find a variable with the name logo, which it will probably not find.
So, do this:
window.opener.document.getElementById('logo').value = fileName;
No idea what you are doing wrong, maybe the PHP echo won’t output the correct ID? Anyway, it works fine for me. See this example:
parent.html
<input type="text" id="logo1" value="VALUE-SHOULD-BE-INSERTED-HERE" />
<script>window.open('child.html');</script>
child.html
<button id="btn">Click me</button>
<script>
btn.addEventListener('click', function () {
var logo = 'logo' + '1';
window.opener.document.getElementById(logo).value = 'something';
window.close();
});
</script>
The better way to do this is now Window.postMessage(), see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage for details.
I'm not sure what's causing the issue, but maybe you can try to update via a function in the parent called by the child.
So in the parent add the function (I assume you can use jQuery, because you mentioned it in the question)
function UpdateValue(newVal){
$("#logo").val(newVal);
}
And call it in the child
window.opener.UpdateValue(fileName);
Although I would like to know why the original isn't working. This might be a good workaround.

Appending an Array and String in javascript into a variable

How can you run a getelementbyid on an Array and a String in Javascript and set it as a variable that is not null for example foo["dog"] x = getelementbyid(foo[0]+"food") and now x = dogfood
<script>
var myrows = new Array();
$(function() {
$("#check").click(function(){
myrows=[]
$(".head input:checked").not("#selectall").each(function(){
myrows.push($(this).parent().attr("id"));
}).value;
alert(myrows);
});
$("#subbut").click(function(){
var x;
var r=confirm("Are you sure you?");
if (r==true){
x="You pressed OK!";
}else{
Object.cancel;
}
**alert( myrows[0]+"servername" + " before" );
for(var i =0; i< myrows.length; i++){
alert(myrows[i] +"rootname" +" in loop" );
var j= document.getElementById(xmyrows[i] +"rootname" );
alert(j+" after call" );
var y = document.getElementById(myrows[i]+"servername");
document.getElementById("id_rootname").value= j.textContent;
document.getElementById("id_servername").value= y.textContent ;**
$.post($("#forms").attr("action"), $("#forms").serialize(), function(data) {
});
}
});
});
</script>
I don't really understand what the array/string problem is, but from the comments it seems you're looking for a way to do dynamic form submission: Dan Davis has provided the nuts and bolts of the solution in his comment — for each form you need to submit dynamically (without a refresh), create an iframe, then set the respective form's target attribute to that iframe's ID:
<form id="form1" target="#form1Response">
...
</form>
<form id="form2" target="#form2Response">
...
</form>
<iframe id="#form1Response"></iframe>
<iframe id="#form2Response"></iframe>
You will then need to attach your server response callbacks to the various iframes' load events. Beware though: even an empty iframe fires a load event, so you will need to filter false positives (empty iframe contents) in your callback.
Another caveat: if your server responds with JSON, IE will prompt the user to save the response to the filesystem before your script can intercept — so make sure the MIME type heading is set to text/plain or text/html to make sure the response is loaded into the iframe's DOM.
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = myrows[i]+"rootname";
str = str.replace(/^\s+|\s+$/g,"");
var str1 = myrows[i]+"servername";
str1 = str1.replace(/^\s+|\s+$/g,"");
var j= document.getElementById(str);
var y = document.getElementById(str1);
document.getElementById("id_rootname").value= j.textContent;
document.getElementById("id_servername").value= y.textContent ;
}

Categories

Resources