0

I've been facing a problem with javascript into JS page and since I'm a newbie on it I can't figure out why this code works on Firefox but not on Google Chrome. I'd be very thankful if someone can help me with this problem.

<script type="text/javascript">

function showFC(form) {

    var selElem = document.getElementById(form);
    var selIndex  = selElem.selectedIndex;

    document.form1.S4.options[0] = new Option("C=1",1);
    if(selIndex==0) {
        for(var i=0;i<10;i++) {
            var val = (i+1)+0.5;
            document.form1.S4.options[i+1] = new Option(val,val);
        }
    }
}
</script>

It doesn't create dynamically elements into the select when it clicked by a button.

Here my html code:

<form name="form1" method="post" action="ComputeResult">
     ... other things
     ....
     ....
   <select name="S4" id="S4" onclick="showFC('S4')">
      <option value="1">FC</option>
      <option value=""></option>
   </select>
</form>
  • any error in console? check it. – Zaheer Ahmed Nov 21 '13 at 10:05
  • Any errors in the console? – Jite Nov 21 '13 at 10:05
  • you sure [JavaScript is not disabled in chrome](http://stackoverflow.com/questions/13405383/how-to-disable-javascript-in-chrome-developer-tools)? – SajjadHashmi Nov 21 '13 at 10:08
  • 2
    Show you html or create fiddle. http://jsfiddle.net/ – Roopendra Nov 21 '13 at 10:10
  • You're passing in `form` and then using `document.form1`. Can you confirm that `
    ` and `
    – freefaller Nov 21 '13 at 10:37
  • I added my Html code above. @ Zaheer Ahmed no error man. @ SajjadHashmi javascript is enabled on Chrome. I cant figure out why it doesnt work :/ – Davide Nardone Nov 21 '13 at 15:56
  • I tried to run your code in a Fiddle (jsfiddle.net/tLbWk), it has a wieird behavior on Chrome indeed. First time you click on the select, it changes the values, but only has the first 2. Only when you select it a second time does it put the right values. Haven't found why just yet. – Stilltorik Nov 22 '13 at 13:42
  • Haven't tested this, but are you sure that `document.form1` will find `
    `? I was under the impression that it would only work if you had `
    `
    – freefaller Nov 22 '13 at 15:43

2 Answers2

0

In JavaScript, you have two ways of declaring a function. Either you declare it like this:

function f() {}

or

var f = function(){}

The difference between the two is that the first is defined at run time, the second one at parse-time (more details here: var functionName = function() {} vs function functionName() {}).

Most probably what happened in your case, is that your function is declared after your HTML is read, and so the function does not exist. So:

window.showFC = function(){}
showFC = function(){}

should both work.

Community
  • 1
  • 1
Stilltorik
  • 1,482
  • 4
  • 18
  • 29
0

instead of onclick, use onchange it will work

<select name="S4" id="S4" onchange="showFC('S4')">
Roukas
  • 36
  • 4