-4

I have a problem, why my Javascript work correct on pure html - localhost, but when include code in jsfiddle - stop working, why? what is wrong? Please help me.

<HTML>
<head>
</head>
<BODY>
<script type="text/javascript">
function CheckContact(val){
 var element=document.getElementById('email');
 if(val=='email')
   element.style.display='block';
 else
   element.style.display='none';

 var element=document.getElementById('sms');
 if(val=='sms')
   element.style.display='block';
 else
   element.style.display='none';
}
</script>
<select name="contactinfo" id="contactinfo" onchange="CheckContact(this.value);">
  <option>Select Contact Option</option>
  <option value="email" class="email">Email</option>
  <option value="sms"class="email">Text (SMS)</option>
</select><br />
<select>
<option> - </option>
<option id="email" style="display: none;">Enter Email: </option>
<option id="sms" style="display: none;">Enter Cell Number: </option>
</select>
</body>
</html>

i have one question, why when include this code in wordpress page - javascript stop working?

3 Answers3

2

jsfiddle lets you choose where to place the javascript code on the page in the dropdown on the left. Change this from onLoad to NoWrap - in <head> to make your function accessible at the global scope.

Will P.
  • 8,437
  • 3
  • 36
  • 45
  • Hmm. That doesn't change anything for me... I don't know why but both the Email and SMS options show up on load. – Albert Xing Mar 05 '14 at 18:27
  • @AlbertXing Make sure you hit "run" again after changing that setting. It is now calling the `CheckContact` method when the first drop down value is changed. – Will P. Mar 05 '14 at 18:28
  • I'm not the OP, just confirming your answer to upvote it if it's correct. I edited my previous comment. – Albert Xing Mar 05 '14 at 18:30
  • Right, it's Chrome - http://stackoverflow.com/questions/2324250/ – Albert Xing Mar 05 '14 at 18:31
  • @AlbertXing ah, my mistake. Yeah I believe the issue he has is that the function is getting defined in the onLoad handler, and so this is probably a duplicate as p.s.w.g mentions in the question's comments – Will P. Mar 05 '14 at 18:33
1

Just change your fiddle to no-wrap in <head>. It is working for me in Chrome.

-2

Well, it helps if you use '{ }'

'function CheckContact(val){
 var element=document.getElementById('email');
 if(val=='email') {
    element.style.display='block';
 }
 else {
    element.style.display='none';
 }
 var element=document.getElementById('sms');
 if(val=='sms') {
    element.style.display='block';
 }
 else {
    element.style.display='none';
 }
 console.log ("test");
}'

Put some console.log calls like the example above, until I added the '{ }' it did not work at all even in normal browser.

alexmac
  • 239
  • 2
  • 9
  • 1
    You’re wrong, by the way. You may want to amend your answer to be correct (if you have something to say beyond the other two answers) or delete it. – Ry- Mar 05 '14 at 23:32