NoGood777
NoGood777

Reputation: 5

Why does the page scroll up when I submit a form?

I have made the following form. When I select any of the options, the page automatically scrolls up. Any ideas how do I fix it?

Here is HTML code:

 <form method="get" action="">
    <select id="training_session" name="lang" onchange=this.form.submit()>
    <option value=""<?php if($_GET['lang'] === '') echo 'selected' ?>>[All languages]</option>
    <option value="English" <?php if($_GET['lang'] === 'English') echo 'selected' ?>>English</option>
    <option value="Portuguese"<?php if($_GET['lang'] === 'Portuguese') echo 'selected' ?>>Portuguese</option>
    <option value="French"<?php if($_GET['lang'] === 'French') echo 'selected' ?>>French</option>
    <option value="Italian"<?php if($_GET['lang'] === 'Italian') echo 'selected' ?>>Italian</option>
    <option value="Japanese"<?php if($_GET['lang'] === 'Japanese') echo 'selected' ?>>Japanese</option>
    </form>
    <noscript><input type="hidden" value="filter"></noscript>

Upvotes: 0

Views: 1636

Answers (3)

Arttu Kuoppala
Arttu Kuoppala

Reputation: 1

You can use an id tag inside the action parameter. If you use php to manipulate the inputs, your php has to be inside that same particular file.

<form method="get" action="#training_session">
    <select id="training_session" name="lang" 
</form>

So set the action to an id you want the user to jump after submitting the form.

Upvotes: 0

Lo&#239;c
Lo&#239;c

Reputation: 11943

As you are submitting the page, it reloads at the top.

Here is a workaround :

First get the scroll position before submitting and submit it with the form :

 <form method="get" action="">
    <select id="training_session" name="lang" onchange="document.getElementById('sc_top').value=document.body.scrollTop;this.form.submit()">
    <option value=""<?php if($_GET['lang'] === '') echo 'selected' ?>>[All languages]</option>
    <option value="English" <?php if($_GET['lang'] === 'English') echo 'selected' ?>>English</option>
    <option value="Portuguese"<?php if($_GET['lang'] === 'Portuguese') echo 'selected' ?>>Portuguese</option>
    <option value="French"<?php if($_GET['lang'] === 'French') echo 'selected' ?>>French</option>
    <option value="Italian"<?php if($_GET['lang'] === 'Italian') echo 'selected' ?>>Italian</option>
    <option value="Japanese"<?php if($_GET['lang'] === 'Japanese') echo 'selected' ?>>Japanese</option>
    </select>
    <input type='hidden' name='scrollTop' id='sc_top'/>
    </form>
    <noscript><input type="hidden" value="filter"></noscript>

Then edit your body tag to set this position again when page is loaded :

<body onload="document.body.scrollTop = <?=intval($_GET['scrollTop']);?>">

Upvotes: 1

Quentin
Quentin

Reputation: 943635

The page isn't scrolling up.

onchange=this.form.submit()

The form is submitting, and the page is reloading.

The new version of the page loads from the top.

Upvotes: 2

Related Questions