window.location is not working second time

时间:2016-10-20 13:18:58

标签: javascript php

I am using the following code in a form with a captcha. If the captcha is correct, then $success = 1, else $success=2. If captcha is not filled, then $success=1.

id=validation is mentioned with the captcha which is at the very bottom of the page and id=success is mentioned with a div element which is at the very top of the page.

Problem :

First test :
1) captcha is correct -> hit submit -> page comes to the top

Second test :
1) captcha is not correct or not filled -> hit submit -> page comes to the bottom
2) captcha is correct -> hit enter -> page stay in bottom (whereas it should go to the top)

Java Script :

var myVariable = <?php echo(json_encode($success)); ?>;
if (myVariable == 2) {
    window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#validation"
};
if (myVariable == 3) {
    window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#validation"
};
if (myVariable == 1) {
    window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#success"
};

1 个答案:

答案 0 :(得分:1)

Try this:

<script type='text/javascript'>
var myVariable = <?php echo(json_encode($success)); ?>;
if (myVariable == 2 || myVariable == 3) {
window.location.href = (""+window.location.href).replace(/#[A-Za-z0-9_]*$/,'')+"#validation"
};
if (myVariable == 1) {
window.location.href = (""+window.location.href).replace(/#[A-Za-z0-9_]*$/,'')+"#success"
};
</script>

I changed window.location to window.location.href and took the same result in one if statement.