Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to use the following javascript to restrict a field on my registration form to accept only numbers:

<script language="javascript">
function forceNumber(event){
var keyCode = event.keyCode ? event.keyCode : event.charCode;
if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 9 && keyCode != 32 && keyCode != 37     && keyCode != 39 && keyCode != 40 && keyCode != 41 && keyCode != 43 && keyCode != 45 && keyCode != 46)
return false;
}
</script>

I first just added the code to the top of functions.php. It worked but gave me an "cannot modify header information" error.

I looked into it further and saved it as forceNumber.js and attempted to call it in functions.php using the wp_enqueue function which is supposed to be the normative way of calling it like so:

function forceNumber() {
wp_enqueue_script( 'force-number',  get_template_directory_uri() . '/js/forceNumber.js', array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'forceNumber' );

This did not work at all, even though this is how the documentation suggests to do it. When I check it out with Firebug the javascript is not even being called in the header (?!). So no wonder it is not working. I just don't understand how the js is not being called correctly.

Thanks and kind regards, Helena

share|improve this question
add comment

2 Answers

In your .js-file, you have to remove the html-tags < script language="javascript"> and < /script>.

share|improve this answer
    
Thank you for the response. I removed the html tags but the script is still not being pulled into the head of the document. –  Helena Jun 18 '13 at 9:28
    
That's odd. I copypasted your code without changing into a template of my own - and it works as it should. –  John Trash Jun 18 '13 at 13:28
    
Wordpress adds a line <script type='text/javascript' src='localhost/(wordpress)/wp-content/themes/(theme)/js/…; ... If you are sure it's still not there, check at first all URLs, and if they are correct check if some plugins or such are making trouble. –  John Trash Jun 18 '13 at 13:30
    
Thanks for the response John. Let me investigate this further and I'll get back to you. Where does it add that particular line? –  Helena Jun 19 '13 at 6:04
add comment
up vote 0 down vote accepted

I was thinking about possibly re-installing as I did not want to comb through code to see where Wordpress would have added the code mentioned. However, that appears to not have been the problem. The solution is here:

http://wordpress.stackexchange.com/questions/103456/javascript-on-registration-page/103459?noredirect=1#103459

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.