试图在表单提交上更改我的提交输入的值

时间:2014-06-26 15:29:44

标签: javascript php jquery

我的页面中有一个帖子列表,我还有一个表单来搜索帖子。

这是我的表格:

<form  action="" method="post">
  <input type="text" name="search"   onclick="if(this.value=='Search:')this.value=''" onblur="if(this.value=='')this.value='Search:'" value="Search:" />
  <input type="submit" value="Search" class="search"  name="sendForm" />
</form>

然后,当我的表单被提交了一些值时,我存储了一个带有我的sql条件语句的会话,我只得到了我的新闻列表,其标题就像我在输入中写的那样。

然后,如果我提交的表格没有任何价值,我会取消我的会话,我会再次获得所有新闻的列表。

这是我的php:

if(isset($_POST['sendForm'])){
    $search = $_POST['search'];
    if(!empty($search) && $search != 'Search:'){
    $_SESSION['where'] = "WHERE title LIKE '%$search%'";
    }
    else{
        unset($_SESSION['where']);
        header('Location: dashboard.php?exe=posts/index');
    }
 }

现在我需要在提交表单时更改输入值的值。

首先,我的提交值是&#34;搜索&#34;,当我点击它时,我想将此值更改为&#34;清除&#34;。  当我点击&#34;清除&#34;我想改为&#34;搜索&#34;试。

你知道我怎么能正确地做到这一点?

我一开始就尝试过这样做,但没有成功:

<input type="submit" value="Search"  onclick="if(this.value=='Search:')this.value='Clear"  name="sendForm" />

现在我尝试使用toogle,但它也无法正常工作。

$(".search").toggle(function (){
           $(this).val("Search");
        }, function(){
        $(this).val("Clear");
});

2 个答案:

答案 0 :(得分:1)

Demo

  1. toggle() - click已弃用 - Reference ,jQuery的当前toggle()隐藏了该元素。

  2. 如果需要,请使用preventDefault()来阻止表单提交。

  3. 检查此代码,

    var clear = true;
    $('.search').click(function(e){
        e.preventDefault();          //if required
        if(clear){
            $(this).val('Clear');
            clear = false;
        }
        else{
            clear = true;
            $(this).val('Search'); 
        }
    
    });
    

答案 1 :(得分:0)

如果您的表单在php文件中,您可以设置php变量(例如,$ submitValue =“Search”),然后将该值插入到表单代码中:

<input type="submit" value="<?= $submitValue ?>" class="search"  name="sendForm" />

您正在尝试更改提交按钮的值,对吗?