How to separate a js function? - javascript

<!--
Copyright (c) 2008 Google Inc.
You are free to copy and use this sample.
License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license
-->
<!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>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</style>
<script src="https://www.google.com/jsapi?key=ABQIAAAAeEJvEumzGBw8dvenGPw1bRTcyTBaKMmwi780-Sh78Ay3Pg36mBRsO3t_v4eega6kiiiRMl84WG-4eA"></script>
<script type="text/javascript">
google.load('search', '1');
onload = function() {
google.search.Search.getBranding('branding');
//google branding
var searchResultsContainer = document.getElementById('searchResults');
var newsSearch = new google.search.NewsSearch();
newsSearch.setSearchCompleteCallback(this, function() {
if (newsSearch.results && newsSearch.results.length > 0) {
searchResultsContainer.style.display = 'block';
for (var i=0; i<newsSearch.results.length; i++) {
var wrapper = document.createElement('div');
var node = newsSearch.results[i].html.cloneNode(true);
wrapper.className = 'gs-result';
wrapper.appendChild(node);
searchResultsContainer.appendChild(wrapper);
}
}
},null);
newsSearch.execute("sport");
//keyword
}
</script>
</head>
<body>
<div>
<div id="branding" style="float:left;"></div>
<div id="searchResults"></div>
</div>
</body>
</html>
Hi, I want to make a Google news search, the above code runs well. However, I want to separate a js function. I use the following code, but the result shows nothing. How to modify it correctly?
<!--
Copyright (c) 2008 Google Inc.
You are free to copy and use this sample.
License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license
-->
<!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>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</style>
<script src="https://www.google.com/jsapi?key=ABQIAAAAeEJvEumzGBw8dvenGPw1bRTcyTBaKMmwi780-Sh78Ay3Pg36mBRsO3t_v4eega6kiiiRMl84WG-4eA"></script>
<script type="text/javascript">
google.load('search', '1');
function searchcomplete() {
var newsSearch = new google.search.NewsSearch();
if (newsSearch.results && newsSearch.results.length > 0) {
searchResultsContainer.style.display = 'block';
for (var i=0; i<newsSearch.results.length; i++) {
var wrapper = document.createElement('div');
var node = newsSearch.results[i].html.cloneNode(true);
wrapper.className = 'gs-result';
wrapper.appendChild(node);
searchResultsContainer.appendChild(wrapper);
}
}
}
onload = function() {
google.search.Search.getBranding('branding');
//google branding
var searchResultsContainer = document.getElementById('searchResults');
var newsSearch1 = new google.search.NewsSearch();
newsSearch1.setSearchCompleteCallback(this, searchcomplete ,null);
newsSearch1.execute("sport");
//keyword
}
</script>
</head>
<body>
<div>
<div id="branding" style="float:left;"></div>
<div id="searchResults"></div>
</div>
</body>
</html>

A couple of problems here:
function searchcomplete() {
// you create a... uh new empty search here?
var newsSearch = new google.search.NewsSearch();
...
// searchResultsContainer is NOT defined in this scope
searchResultsContainer.style.display = 'block';
...
}
onload = function() {
// this defines searchResultsContainer in the scope of the onload callback,
// but NOT in the global scope
var searchResultsContainer = document.getElementById('searchResults');
...
// the first param is the thing that 'this' in the callback will refer to
// in this case it's the window but you need to change this in order
//to get access to the results
newsSearch1.setSearchCompleteCallback(this, searchcomplete ,null);
...
}
And here's a fixed version:
function searchcomplete() {
// Huh, why this? See below...
if (this.results && this.results.length > 0) {
// get 'searchResultsContainer' here
var searchResultsContainer = document.getElementById('searchResults');
searchResultsContainer.style.display = 'block';
for (var i=0; i < this.results.length; i++) {
var wrapper = document.createElement('div');
....
}
window.onload = function() {
...
// here we supply newsSearch itself as the 'this' so we can access
// its properties inside the callback
newsSearch.setSearchCompleteCallback(newsSearch, searchcomplete ,null);
...
}
You should read up a bit on this and scoping.

I don't know why you tried to do it in this way, but it's the working code:
...
<script type="text/javascript">
google.load('search', '1');
var newsSearch, searchResultsContainer;
function searchcomplete() {
// var newsSearch = new google.search.NewsSearch();
if (newsSearch.results && newsSearch.results.length > 0) {
searchResultsContainer.style.display = 'block';
for (var i=0; i<newsSearch.results.length; i++) {
var wrapper = document.createElement('div');
var node = newsSearch.results[i].html.cloneNode(true);
wrapper.className = 'gs-result';
wrapper.appendChild(node);
searchResultsContainer.appendChild(wrapper);
}
}
}
onload = function() {
google.search.Search.getBranding('branding');
//google branding
searchResultsContainer = document.getElementById('searchResults');
newsSearch = new google.search.NewsSearch();
newsSearch.setSearchCompleteCallback(this, searchcomplete ,null);
newsSearch.execute("sport");
//keyword
}
</script>
...
you don't have to define new variable newsSearch
you should define newsSearch and searchResultsContainer globally.
Happy coding :-)

Related

How to load search data on load?

I received this code from another user in this forum.
Issue: As seen in the below screenshot, the search results (or data) starts to appear when you click or start typing in the search box or else only the search box loads without the data.
Requirement: I want to display the results (or data) as the page loads.
The code is given below
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
   
<style>
.nav-link {
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<ul class="nav nav-tabs">
<li class="nav-item">
<div class="nav-link"id="search-link">Search</div>
</li>
</ul>
<div id="app"></div>
<!-- Content here -->
</div>
<!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
var data;
function loadView(options){
var id = typeof options.id === "undefined" ? "app" : options.id;
var cb = typeof options.callback === "undefined" ? function(){} : options.callback;
google.script.run.withSuccessHandler(function(html){
document.getElementById("app").innerHTML = html;
typeof options.params === "undefined" ? cb() : cb(options.params);
})[options.func]();
}
function setDataForSearch(){
google.script.run.withSuccessHandler(function(dataReturned){
data = dataReturned.slice();
}).getDataForSearch();
}
function search(){
var searchinput = document.getElementById("searchinput").value.toString().toLowerCase().trim();
var searchWords = searchinput.split(/\s+/);
var searchColumns = [0,1,2,3,4,5,6,7];
// and or
var resultsArray = data.filter(function(r){
return searchWords.every(function(word){
return searchColumns.some(function(colIndex){
return r[colIndex].toString().toLowerCase().indexOf(word) !== -1
});
});
});
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function(r){
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
function loadSearchView(){
loadView({func:"loadSearchView", callback: setDataForSearch});
}
window.addEventListener("load", loadSearchView);
function inputEventHandler(e){
if (e.target.matches("#searchinput")){
search();
}
}
document.getElementById("app").addEventListener("input",inputEventHandler);
document.getElementById("app").addEventListener("click",inputEventHandler);
</script>
</body>
</html>
server-side code
function getDataForSearch(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const ws = ss.getSheetByName("TableData");
return ws.getRange(2, 1, ws.getLastRow(),8).getValues();
}
I need to know what modification needs to be done in the code?
I tried document.getElementById("app").addEventListener("load",inputEventHandler);
but it didn't work.
is there any other event listeners available that will load the search results (or data) (without taking any action on the site, i mean without clicking or typing in the search box)?
Thanks in advance.
Edit: loadsearchview function file code
function loadSearchView(){
return loadPartialHTML_("search");
}
You could use addEventListener with DOMContentLoaded to call a function when all the HTML is loaded and the DOM tree is built. For your particular situation, here's how I managed:
First I need to load data into data variable and call the loadSearchView() function when the page loads:
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", function () {
google.script.run.withSuccessHandler(function (r) {
data = r;
loadSearchView();
}).getDataForSearch();
});
} else {
google.script.run.withSuccessHandler(function (r) {
data = r;
loadSearchView();
}).getDataForSearch();
}
Then I need to load the search view, but instead of calling setDataForSearch, I implemented another function to call functions after this view is loaded. This might be useful if you want to call more than one function after the searchView loads. So basically the code would be like this:
function loadSearchView() {
loadView({ func: "loadSearchView", callback: afterSearchViewLoads });
}
function afterSearchViewLoads(){
loadDataWhenPageLoads();
}
function loadDataWhenPageLoads(){
var resultArray = data;
var searchResultsBox = document.getElementById("searchResults");
var templateBox = document.getElementById("rowTemplate");
var template = templateBox.content;
searchResultsBox.innerHTML = "";
resultsArray.forEach(function (r) {
var tr = template.cloneNode(true);
var hinmokuColumn = tr.querySelector(".hinmoku");
var buhinCodeuColumn = tr.querySelector(".buhinCode");
var buhinNameColumn = tr.querySelector(".buhinName");
var hitsuyoColumn = tr.querySelector(".hitsuyo");
var genkaColumn = tr.querySelector(".genka");
var kobaiColumn = tr.querySelector(".kobai");
var sagakuColumn = tr.querySelector(".sagaku");
var kenshoColumn = tr.querySelector(".kensho");
hinmokuColumn.textContent = r[0];
buhinCodeuColumn.textContent = r[1];
buhinNameColumn.textContent = r[2];
hitsuyoColumn.textContent = r[3];
genkaColumn.textContent = r[4];
kobaiColumn.textContent = r[5];
sagakuColumn.textContent = r[6];
kenshoColumn.textContent = r[7];
searchResultsBox.appendChild(tr);
});
}
Hope this can solve your problem!
AddEventListener when you click enter key in keyboard will help you. Link: EventListener Enter Key
Also addEventListener "change" will help you.
edit
If you want your data to load when page is loaded use one of those ways:
window.onload = function() {
Search();
} // way one
window.onload = Search(); //way two
<body onclick="Search()"> // way three

How can I access a variable in Jquery and use its value in another external .js file ? The variable is $generatedP

I need to access in a different .js file the value inside $generatedP and display it
$(document).ready(function() {
var $buttonValue = $(".value_generate");
var $divValue = $(".generated_value");
var $generatedP = $(".generated_p");
var $valueInput2 = $(".value_input_2");
var $submitPages2 = $(".submit_pages_2");
function valueGenerator(value) {
var valueString="";
var lettersNumbers = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i = 0; i < value; i++)
valueString += lettersNumbers.charAt(Math.floor(Math.random()* lettersNumbers.length));
return valueString;
}//generate string
$buttonValue.click(function generate() {
var $key = valueGenerator(12);
$generatedP.html($key);//display generated string
});
$submitPages2.click(function() {
if($valueInput2.val() == $generatedP.text() ){
alert("you are logged in website");
} else {
alert("please check again the value");
return false;
}//check value if true/false
});
I am new to jquery
You have a few options.
Create a namespace inside the jQuery object:
$.myGlobalNamespace = {};
$.myGlobalNamespace.generatedPvalue = "something";
Define an object at the window level:
window.myGlobalNamespace = {};
window.myGlobalNamespace.generatedPvalue = "something";
Just be sure to use a sensible name for the namespace object.
You can improve the behavior doing client-side checking with localStorage, or you can simply use sessionStorage. Variable $generatedP will be available in page1 and page2. Hope it helps!
PAGE 1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script type = "text/javascript">
$(document).ready(function(){
var $generatedP = "27.23.10";
sessionStorage.setItem('myVar', $generatedP);
window.location.href = "page2.html";
});
</script>
</body>
</html>
PAGE 2: to access the variable just use the getItem method and that is all.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var data = sessionStorage.getItem('myVar');
alert(data);
</script>
</body>
</html>

Library.add is not a function error

I am trying to execute this code:
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
Library.add(listItem);
console.log(Library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
The HTML is here:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
What I'm trying to do is press the addButton and the onclick will run the addBook function under the libraryUI object. The title of the book, in an input field, will then be used to create an object with the title of the book in it. I want to add that book to a list of books (an array) in an instance of Library. When I try to do so with the following code, I get the error "Uncaught TypeError: Library.add is not a function". I thought that Library.add is a function.
I added:
var library = new Library();
because I thought I had forgotten to create an iteration of Library, but I still came up with the exact same error. Please help. :)
var addButton = document.querySelector("#add");
var searchButton = document.querySelector("#search");
var titleInput = document.querySelector("#title");
function Book(title) {
this.title = title;
}
function Library() {
this.books = [];
}
Library.prototype.add = function(book) {
this.books.push(book);
}
var library = new Library();
//Library UI
var libraryUI = {
//Add a new book
addBook: function() {
var listItem = libraryUI.createNewBook(titleInput.value);
library.add(listItem);
console.log(library.books);
},
//Create a new book
createNewBook: function(title) {
var book = new Book(title);
return book;
}
};
addButton.addEventListener("click", libraryUI.addBook);
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Library App</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>Personal Library</h1>
<label for="title">Title: </label>
<input type="text" id="title">
<button id="add">Add</button>
<button id="search">Search</button>
<p id="display"></p>
<script src="js/app.js"></script>
</body>
</html>
Shouldn't it be library.add instead of Library.add?
Also: why:
Library.prototype.add = function() {
this.add = function(book) {
this.books.push(book);
};
}
instead of:
Library.prototype.add = function(book) {
this.books.push(book);
}
?
If I change Library.add to library.add and console.log(library.books) I think this does what you want.

calling more than one function on the same button does not work for me (ajax)

i got a ajax procedure that is working ok, but now i need to add a new function to be called just once. so i add this to my current script to get the apex collection clean, but now nothing happens, i placed an alert to verify, but no alert is shown, i guess is because i am placing my clean script in wrong place or there must be something else missing.
// Clean Collection
function()
{
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
}
here is my full script. thanks for your value tips !!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Totals</title>
<script type="text/javascript">
$(function()
{
$("#Calculate").click
(
function()
{
// Clean Collection
function()
{
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
}
$("input[name=f_qty]").each
(
function()
{
var valueInCurrentTextBox = $(this).val();
var productId = $(this).parents('tr').find("input[name=f_prod_id]").val();
$("#P12_PRODUCT_ID").val(productId);
if (valueInCurrentTextBox != '')
{
$("#P12_QTY").val(valueInCurrentTextBox);
var ajaxRequest = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=ADD_PRODUCTS",&APP_PAGE_ID.);
ajaxRequest.add('P12_PRODUCT_ID',html_GetElement('P12_PRODUCT_ID').value);
ajaxRequest.add('P12_QTY',html_GetElement('P12_QTY').value);
ajaxResult = ajaxRequest.get();
}
}
);
alert('Updated!');
}
);
}
);
</script>
</head>
<body>
<div id="totals"></div>
<p align="center" style="clear: both;">
<button type="button" style="font-weight: bold;background-color:lightgray;margin-left:auto;margin-right:auto;display:block;margin-top:0%;margin-bottom:0%" id="Calculate">Add Products</button>
</p>
</body>
</html>
You're declaring that inner function, but never actually calling it. You could assign it to a variable and then call that, but it's actually not needed at all.
Try:
$(function()
{
$("#Calculate").click
(
function()
{
// Clean Collection
alert('Clean All');
var ajaxRequestd = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=DEL_PRODUCTS",&APP_PAGE_ID.);
ajaxResult = ajaxRequestd.get();
$("input[name=f_qty]").each
(
function()
{
var valueInCurrentTextBox = $(this).val();
var productId = $(this).parents('tr').find("input[name=f_prod_id]").val();
$("#P12_PRODUCT_ID").val(productId);
if (valueInCurrentTextBox != '')
{
$("#P12_QTY").val(valueInCurrentTextBox);
var ajaxRequest = new htmldb_Get(null,&APP_ID.,"APPLICATION_PROCESS=ADD_PRODUCTS",&APP_PAGE_ID.);
ajaxRequest.add('P12_PRODUCT_ID',html_GetElement('P12_PRODUCT_ID').value);
ajaxRequest.add('P12_QTY',html_GetElement('P12_QTY').value);
ajaxResult = ajaxRequest.get();
}
}
);
alert('Updated!');
});
});

Javascript opener window

I have function that opens up a window, and the values from the newly opened window are listed in the opener window.
The 2nd window - has this function:
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
opener.jQuery("#r_docs").append(jQuery(html));
}
The function that calls the one above is:
function addRefDoc(){
var count = 0;
var ref_docarray ;
var ref_noarray ;
<%for(int i1=0; i1<vec.size(); i1++) {
prop = (Properties) vec.get(i1);
String ref_no = prop.getProperty("referral_no","");
String ref_name = (prop.getProperty("last_name", "")+ ","+ prop.getProperty("first_name", ""));
%>
if(document.getElementById("refcheckbox_<%=ref_no%>").checked) {
count++;
if ((ref_doctor!=null)&&(ref_doctor!="")&&(ref_docno!=null)&&(ref_docno!="")) {
ref_docarray = ref_doctor.split(";");
ref_noarray = ref_docno.split(";");
if ((containsElem(ref_docarray,"<%=ref_name%>"))||(containsElem(ref_noarray,<%=ref_no%>))) {
alert("Referral doctor " + "<%=ref_name%>" + " already exists");
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
} else {
AddOtherRefDoc("<%=ref_name%>", <%=ref_no%>);
}
}
<%} %>
self.close();
}
function containsElem(array1,elem) {
for (var i=0;i<array1.length;i++) {
if(array1[i]==elem){
return true;
} else{
return false;
}
}
}
When this function is called, it is supposed to carry the 2 input elements "ref_docs" and "ref_nos" into the page that opened this window. But it is not doing so. It lists the elements alright but when I try to use "ref_docs" and "ref_nos" in another Javascript function in the 1st window, I see that "ref_nos" and "ref_docs" are empty.
What am I doing wrong?
function updateRd(){
var ref_docs = jQuery("#updatedelete").find('input[name="ref_docs"]');
var ref_nos = jQuery("#updatedelete").find('input[name="ref_nos"]'); alert(ref_docs.val() + ref_nos.val());
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";")); }
–
This function returns an error saying "ref_docs" and "ref_nos" are undefined.
I think it is trying to use the jQuery on the other page to find "#r_docs" on the current page.
Try:
jQuery(opener.document).find("#r_docs").append(html);
UPDATE:
I created index.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
window.jQuery = jQuery;
function openChild ()
{
var mychildwin = window.open("child.html");
}
</script>
</head>
<body>
<input type="button" value="click" onclick="openChild();" />
<div id="r_docs">
Redocs here.
</div>
</body>
</html>
and child.html:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.js"></script>
<script type="text/javascript">
function AddOtherRefDoc(name, number) {
var remove = "<a href='javascript:void(0);' onclick='removeRefDoctor(this)'>Remove</a>";
var html = "<li><b> Referral Doctor: </b>"+name+"<b>, Referral No: </b>"+number+ " " +remove+" <input type='text' name='ref_docs' value='"+name+"'></input><input type='text' name='ref_nos' value='"+number+"'></input></li>";
jQuery(opener.document).find("#r_docs").append(html);
}
</script>
</head>
<body>
<input type="button" value="click" onclick="AddOtherRefDoc('name', 42);"/>
</body>
</html>
UPDATE2:
in your update function document.updatedelete has no attributes ref_docs and ref_nos.
try:
jQuery("#updatedelete")
.find('input[name="ref_docs"], input[name="ref_nos"]')
Where your form is
<form id="updatedelete" ... >
Your function that accesses the DOM elements is incorrect. updatedelete is not a property of document, nor will accessing a ref_docs or ref_nos property automatically build a collection of input elements. Since you're using jQuery already, try this:
var ref_docs = $('input[name="ref_docs"]');
var ref_nos = $('input[name="ref_nos"]');
That will give you Array (or at least array-like) objects that will let you access your inputs:
var rdocs = new Array();
var rnos = new Array();
ref_docs.each(function() { rdocs.push($(this).val()); } );
ref_nos.each(function() { rnos.push($(this).val()); } );
$('#r_doctor').val(rdocs.join(";"));
$('#r_doctor_ohip').val(rnos.join(";"));

Categories

Resources