I have the below java script function in which I want to redirect the page to another page. I verified that ‘Got’ message is shown by the alert function. So, the function is invoked properly. However, the page redirection with window.location.href does not work. Moreover, the alert function that prints the content of option, vDaeId, dgpId does not executed (I dont see a pop up in the browser). Could you please tell me what’s wrong with this piece of code? Thanks. I am using firefox btw.
function goToPMDisplayer(){
alert('Got ');
var option=document.getElementById("D1").value;
var vDaeId=document.getElementById("D2").value;
var dgpId=document.getElementById("dgpids").value;
var str= option + " "+ vDaeId + " "+ dgpId
alert(str);
window.location.href="display.jsp?option="+option + "&vdaeid=" + vDaeId + "&dgpid=" + dgpId
}
That tells us that the code is failing by throwing an exception. My guess would be that you don’t have at least one of the elements you’re relying on having (
D1,D2, ordgpids). Sodocument.getElementByIdreturnsnull, and when you try to access.valueon it, you get an exception.Note that the strings you use with
getElementByIdmust beidvalues, notnames. So you must haveid="D1"on one element,id="D2"on another, andid="dgpids"on another. Also note thatidvalues can be case-sensitive, and that they must be unique on the page. (Most browsers will give you the first one in document order if you mess up that last rule, but…)I assume that you’re not calling
goToPMDisplayeruntil the page is fully loaded, but if you’re calling it during page load, make sure you’re not calling it until after the elements exist (e.g., put the call to it lower in the document than the elements).For problems like this,
alert-style debugging went out some years ago. Here in 2012, we use proper debuggers. There’s one built into all major browsers these days, even IE. You can set break points, walk through code, inspect the current state of the DOM… In short, no need to fumble about in the dark; you can shine light on what’s happening.In a comment on the question, you’ve said
With all due respect, I just don’t see how that can be. I suspect the
idvalues are slightly different, or that they don’t haveidvalues at all, but rather they havenamevalues.Here’s a complete, working example: Live copy | source