0

I am currently in the middle of the development of a website. If a user presses a button an javascript function needs to be called. I simplified this function to:

<html>
<head>
<script type="text/javascript">
function newProd(number,customer,software,hardware,name)
{
       //I simplified this function
       alert('number is: '+number+'customer is: '+customer+' software is: '+software+' hardware is: '+hardware+' name is: '+name);
}
</script>
</head>

<body>
     <input type="text" name="textfieldCustomer"><br>
     <input type="text" name="textfieldSoftware"><br>
     <input type="text" name="textfieldHardware"><br>
     <input type="text" name="textfieldDescription"><br>
     <input type="button" name="button" value="go to function" onClick="newProd('a number',textfieldCustomer.value,textfieldSoftware.value,textfieldHardware.value,textfieldDescription.value)">
</body>

when the user presses the button in Internet explorer, the function works perfectly! Unfortunately the function does not work in Chrome or Safari.

Does anyone have any idea what is going wrong?

Alex van Rijs
  • 803
  • 5
  • 17
  • 39
  • Do you know something of jQuery ? – Sllix Jul 08 '12 at 11:50
  • 2
    Using the `onclick` attribute is considered bad practice, as it puts Javascript logic into your HTML markup. You should rather set up your event handling in pure Javascript. More detailed reasons are described here: http://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice – pixelistik Jul 08 '12 at 11:54

2 Answers2

3

The form fields are not supposed to be defined as global variables. Maybe in IE they are but that's not a behavior you can depend on. Try this:

onClick="newProd('a number',
    this.form.textfieldCustomer.value,
    this.form.textfieldSoftware.value,
    this.form.textfieldHardware.value,
    this.form.textfieldDescription.value)">

Oh, and add a form to wrap the inputs of course.

Demo: http://jsfiddle.net/kdUMc/

Esailija
  • 138,174
  • 23
  • 272
  • 326
0

In my eyes there are two big mistakes in your code. First, the access to inputs fields is wrong. It needs a connection to an instance variable, like 'document'. The second one, the form tag is missing. If you wrap the input fields into a form tag you can access the values as Esailija has posted.

Reporter
  • 3,897
  • 5
  • 33
  • 47