0

现在我有一个输入文本、收音机和一个提交按钮..

让我说我url = image-search.php

<form>
<input type="text" name="name"><br>
<input type="radio name="arrange" value="horizontal"><br />
<input type="radio name="arrange" value="vertical"><br>
<input type="submit" name="submit"><br>

当我单击按钮时..它重定向同一页面但url = image-search.php?name=ss&arrange=horizontal

这个页面仍然有按钮..

问题是..在我点击第一页的按钮后=image-search.php

我希望用户输入值保留在名称的输入文本中..

以及如何根据用户选择使复选框被选中?

4

2 回答 2

3

如果在提交表单时页面重新加载,您可以使用 php 为表单字段设置默认值

<form>
<input type="text" name="name" value="<?php echo isset($_GET["name"])?$_GET["name"]:""; ?>"><br>
<input type="radio" name="arrange" value="horizontal"<?php echo (isset($_GET["arrange"])?($_GET["arrange"]=="horizontal"?" checked='checked'":""):""); ?>><br />
<input type="radio" name="arrange" value="vertical"<?php echo (isset($_GET["arrange"])?($_GET["arrange"]=="vertical"?" checked='checked'":""):""); ?>><br>
<input type="submit" name="submit"><br>
</form>
于 2013-04-25T17:18:05.333 回答
0

Here is the answer to your question.. hope this will help everyone.. @Macke - your approach for setting values after submission is really good, but when we have lot of elements on form.. let's say 1000 - it become pain in AS*..

Add this script tag in your HEAD tag of the page -

<script language="javascript" type="text/javascript">
    var obj = JSON.parse('<?= json_encode($_REQUEST) ?>');
    console.log(obj);

    function __setPostBackValue(element){
        if(obj.length <= 0) return;
        var type = element.type;
        var fval;
        console.log('Processing...'+ element.name);
        try{
            eval('fval = obj'+'.'+element.name);
        }
        catch(ex){

        }
        if(type == 'text'){
            element.value = fval; 
        }
        if(type == 'checkbox'){                    
            if(fval != undefined)
                element.setAttribute("checked","on");                        
        }
        if(type == 'radio'){                    
            if(fval != undefined && element.value == fval)
                element.setAttribute("checked","on");                        
        }

    }

</script>

and at the bottom of the page, yes at the bottom of the page (before body ends) add another script tag -

<script language="javascript" type="text/javascript">
            var fields = document.getElementsByTagName('input');
            for(var i=0;i<fields.length;i++){
                __setPostBackValue(fields[i]);
            }
        </script> 

What it does ? When you submit your form, var obj = JSON.parse('<?= json_encode($_REQUEST) ?>'); this creates local JSON Object usable by Javascript - and the script we added at the end of the page.. loop through all elements and call __setPostBackValue function. Where we are setting the values of the elements by Javascript.

This is little bit tricky but it works..!!

PS: I had no radio button in my page, but if you have you can add it easily.

-Paresh Rathod

于 2014-07-31T17:08:42.647 回答