[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


JavaScript function with arguments 131122

Posted on 2013-11-22
Medium Priority
Last Modified: 2013-11-25
Hello Expert.

JavaScript in HTML page below passes argument from onClick event to function
Hospital _Name to display the name and aliases.

1. Would like to stack the aliases in the alert by putting a page break in the alert like
alert("The Hospital Name is " + name + ".  The aliases are " + alias1 + ",<br />  " + alias2 + "<br />, " + alias3 + "<br />, " + alias4);

But this does not cause a page break but just displays the  string <br />.
How can I begin a new line with each of the alias names?

2. Right now in the function calls by onClick where the last parameter is empty quotes  
a comma appears after the last alias. So I tried taking the comma out but that made the button disappear. How can I get rid of the comma after the last parameter with a string?


Allen in Dallas

<!DOCTYPE html>
<title>LHP Hopsital Group</title>

<style type="text/css">
 body {font-family: arial;}


<p>Click one of the buttons to call see the the hospital alaises</p>

<button onclick="Hospital_Name('Portneuf Medical Center','PMC','Portneuf','Pocatello','_')">Portneuf Medical Center</button><br />
<button onclick="Hospital_Name('Texas Health Presbyterian Hospital-WNJ','Wilson-Jones' , 'THR-WNJ', 'PWNJ', 'Sherman')">Texas Health Presbyterian Hospital-WNJ</button><br />
<button onclick="Hospital_Name('Seton Medical Center Harker Heights','HH', 'SMCHH', 'Killeen', 'Seton')">Seton Medical Center Harker Heights</button><br />
<button onclick="Hospital_Name('Bay Medical Center Sacred Heart Health System','BMC', 'Panama City', 'Sacred Heart', '')">Bay Medical Center Sacred Heart Health System</button> <br />
<button onclick="Hospital_Name('HackensackUMC Mountainside','HUMC', 'MSH', 'Montclair', '')">Hackensack UMC Mountainside</button> <br />
<button onclick="Hospital_Name('Hackensack University Medical Group','HUMC-PV', 'Pasack Valley', 'Westwood', '')">Hackensack University Medical Group</button> <br />
<br />
<br />

function Hospital_Name(name,alias1,alias2,alias3,alias4)
alert("The Hospital Name is " + name + ".  The aliases are " + alias1 + ",  " + alias2 + ", " + alias3 + ", " + alias4);

This page has a function called hospitalName which is declared with five placemaker arguments,<br />
'name', 'alias1', 'alias2', 'alias3', and 'alias4'. When button calls the function there are five arguments,<br />
passed to the function depending on which hospital is called <br />
by the onClick event associated with the button.<br />
These five strings replace the placemaker <br />
arguments used to create the function with string values that are  <br />
passed to function when then button is clicked<br />


Open in new window

Question by:Allen Pitts
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
LVL 14

Expert Comment

ID: 39670301
For the first part of your question, you need to use "\n" for a newline, not the <br> tag.

    alert("Hello \n world");
LVL 14

Assisted Solution

jb1dev earned 800 total points
ID: 39670344
Try this

function Hospital_Name(name,alias1,alias2,alias3,alias4)
    var message = 
            "The Hospital Name is " + name + ".  The aliases are " + 
                alias1 + ",\n" + 
                alias2 + ",\n" + 

    if(alias4 != "") {
        message += ",\n" + alias4;


Open in new window

LVL 15

Accepted Solution

VincentPuglia earned 1200 total points
ID: 39672196
  I took a slightly different approach.  I created an array of objects that contain 2 properties: hName (a string) and alias (an array of strings),  Within the onclick event, I called the hospital_name function with an index into the hospital array.  
Note that "hospitals" only contains aliases; there are no blank ("")  entries. So, if you have a hospital with 0, 1, or 20 aliases, it makes no difference to the code.


var hospitals = [ 
	{ hName: 'Portneuf Medical Center', alias: ['PMC','Portneuf','Pocatello'] },
	{ hName: 'Texas Health Presbyterian Hospital-WNJ', alias:  ['Wilson-Jones' , 'THR-WNJ', 'PWNJ', 'Sherman'] },
	{ hName: 'Seton Medical Center Harker Heights', alias:  ['HH', 'SMCHH', 'Killeen', 'Seton'] },
	{ hName: 'Bay Medical Center Sacred Heart Health System', alias:  ['BMC', 'Panama City', 'Sacred Heart']},
	{ hName: 'HackensackUMC Mountainside', alias:  ['HUMC', 'MSH', 'Montclair'] },
	{ hName: 'Hackensack University Medical Group', alias:  ['HUMC-PV', 'Pasack Valley', 'Westwood']}

function Hospital_Name(ndx)
    var theObject = hospitals[ndx];
    var name = theObject.hName;
	var aliasArray = theObject.alias;

    var message = "The hospital name is " + name + ".  The aliases are \n" ;
   for ( i = 0; i < aliasArray.length; i++)
		message += ((i == 0) ? " \n" : ",  \n") + aliasArray[i];

<style type="text/css">
 body {font-family: arial;}


<p>Click one of the buttons to call see the the hospital alaises</p>

<button onclick="Hospital_Name(0)">Portneuf Medical Center</button><br />
<button onclick="Hospital_Name(1)">Texas Health Presbyterian Hospital-WNJ</button><br />
<button onclick="Hospital_Name(2)">Seton Medical Center Harker Heights</button><br />
<button onclick="Hospital_Name(3)">Bay Medical Center Sacred Heart Health System</button> <br />
<button onclick="Hospital_Name(4)">Hackensack UMC Mountainside</button> <br />
<button onclick="Hospital_Name(5)">Hackensack University Medical Group</button> <br />
<br />

Open in new window


Author Closing Comment

by:Allen Pitts
ID: 39674943
Hello Vinny,

Am splitting the points between you and jb1dev because
in fairness he answered first and did answer the question.

But I am blown away by the thoughtfulness and depth of
your answer. I have been studying it for am about an
hour and only now think I understand it.

In the block that begins
var hospitals = [
      {hName: 'Portneuf Med....
I think an array is created within in an array. The outer array
is called 'hName' and the inner array is called 'alias'

Then in the function called Hospital_Name(ndx) four variables are
created. The first variable the Object receives the argument ndx
and passes it to the object hospitals (i think).
The second variable, 'name', refers to the outer array hName and
attaches it to theObject.
The third variable refers to the inner array and attaches the inner
array top theObject. (Is 'attaches' correct? Is there a better verb?)

The fourth variable is 'message'. I think I get the first part
wherein the variable 'name' is called as the first part of the message string
which eventually is made the parameter of an alert keyword.

The second part of the 'message' variable is the part hat really twists my
head around. I think this is a For Loop (http://www.w3schools.com/js/js_loop_for.asp)
The first line says that i begins at 0 and if i is less than the length of the inner array,
aliasArray, then increment i by one.

The next line looks like a ternary operator but not sure exactly how it works.
The part before the question mark is the expression to be tested.
I think the ternary operator asks: In 'message' does the variable i equal zero?
If so put in the message a line return. If in the variable 'message' i does not equal zero then put in the message the string in the inner array presently associated with  i.

So instead of passing the hospital names and alias using function arguments the outer
array was called by the onClick event by referring to the outer array index number. After that it gets a little fuzzy about how the the outer array is associated with the inner array.
Pretty sure this happens in the first part of the Hospital_Name function but not
really sure how. But once that happens then the inner array associated with the outer array is looped thru and made a part of the message.

Would like to investigate this more and understand it better. But I have probably
taken too much time. Perhaps I could begin a new question to get you more points
or take to a different venue and I could compensate you for your time helping me understand this via PayPal.


LVL 15

Expert Comment

ID: 39675172
Hi Allen,
   Glad you liked it.  :D  
Many people would look at 'hospitals' and see an array within an array.  However, it is an array of objects. Each object has 2 properties:  hName, a string; and alias, an array of strings.  The object's name (for all practical purposes) is the array's index.  

If you'd like to play with it and see one difference between arrays and objects, add the following immediately after the "var hospitals" code:
for (property in hospitals)
    alert( property + ' = ' + hospitals[property]);   

Open in new window

as for the 'solution' and your question:
// using an index into hospitals, get its data, and assign them to "theObject" 
// sort of like: var states = ["NY", "NJ", CA"];  var myState = states[0];
// only difference is a lot more garbage is being dragged over :)   

var theObject = hospitals[ndx];  

// an object's properties are accessed with 'dot' notation: theObject.hName, theObject.alias
// this is just like the DOM (document object method) for accessing html elements:
// document.forms["myForm"].name  document.forms.myForm.name

var name = theObject.hName;

//the 'name' variable is really unnecessary; the line below could be written as:
//var message = "The hospital name is " + theObject.hName + ".  The aliases are \n" ;

var aliasArray = theObject.alias;
// this is a simply assignment, once theObject has been declared and defined.  The difference between alias & hName is that the former is an array.

    var message = "The hospital name is " + name + ".  The aliases are \n" ;
   for ( i = 0; i < aliasArray.length; i++)
		message += ((i == 0) ? " \n" : ",  \n") + aliasArray[i];

the "i' enables us to step through the aliasArray one cell at a time. We are testing at i==0 
 because the linefeeds are going to be put before, rather than after, the alias data, so no comma should be added to the 1st alias (arrays begin counting with 0).    
		message += ( (i == 0) ? " \n" : ",  \n") + aliasArray[i];
normal terniarys are:
 theResult = (if this is true) ? doThis : elseDoThis;
the one I wrote says:
 theResult =  (  (if this is true) ? doThis : elseDoThis  ) + plusThis;
the extra set of parentheses simply makes sure whatever is in them gets calculated first, so theResult ends up equaling
 doThis + plusThis  when i==0
elseDoThis + plusThis  for the rest of the cases

Open in new window

Insofar as other questions, venues, etc...whatever is convenient and appropriate for you.  From what people tell me, I'm retired....but there are still some games of gog.com that I haven't picked up...see my profile for my email.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question