开发者

window refresh after change in selection in javascript

I have a selection box which is holding 3 (1,2,3) values in option. By default this is showing value 1开发者_Python百科 but whenever I change this value 2, my page should be refreshed and selection option should keep value 2 also. How will I do it in javascript and html? I know the designing of selection box.


You'll want to put your select element in a form whose action is directed at the current page. Now the trouble is that simply changing the value of a select element does not automatically submit a form. In order to make it do this, you will need to attach some Javascript to the element's onchange event like this:

<form id="formtest" method="post" action="">
    <select id="test" name="myValue" onchange="this.form.submit();">
        <option>test</option>
        <option>test2</option>
    </select>
</form>

So now, assuming you're using PHP, you will have access to the variable on your server during this form submission by doing this:

$_POST['myValue']

And the code in your view/html can look like this:

<form id="formtest" method="post" action="">
    <select id="test" name="myValue" onchange="this.form.submit();">
        <option<?php echo isset($_POST['myValue']) && $_POST['myValue'] == 'test' ? ' selected' : '' ?>>test</option>
        <option<?php echo isset($_POST['myValue']) && $_POST['myValue'] == 'test2' ? ' selected' : '' ?>>test2</option>
    </select>
</form>

This can all be made much more dynamic, of course, but the basic idea is there for you to digest. Of course it would've been much more helpful if you had shared with us what server scripting language you use and which (if any) Javascript libraries you use.


Better to use server side language.

Or

on selecting an option

redirect to the same page with selected value append to that url

window.location.href= index.html?selectedoption=2

get this value from url

http://www.netlobo.com/url_query_string_javascript.html http://www.codeproject.com/KB/scripting/GetURLParameters.aspx

based on this value keep the select box values selected

You can get help of hidden fields also to attain this


Why not use cookies?

On the onChange event for the select box, create a function that first saves the value of the box to a cookie and then refresh the page.

Then, on the body "onLoad", check for the existence of the cookie and set the select box to that value.

You'll probably want to add a reset button that clears out the cookie or set the cookie to expire at the end of the session so the select box's state doesn't persist across multiple uses of the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜