【问题标题】:Jquery: Change input type from button to submitJquery:将输入类型从按钮更改为提交
【发布时间】:2014-04-09 14:03:28
【问题描述】:

我有一个如下的动画搜索表单。

<form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">

<div id="searchtext">
    <input type="text" value="" size="25" name="s" id="s" placeholder="<?php esc_attr_e('Search', 'reverie'); ?>">
</div>

<div id="submitsearch">
    <input type="button" id="searchsubmit" value="" class="button postfix">
</div>

jQuery("#submitsearch").click(function () {
   jQuery("#searchtext").animate({width:'toggle'},500);
      jQuery(this).toggleClass("closed");
}); 

当第一次点击搜索按钮时,它会切换出用户可以输入他们想要搜索的内容的文本区域。然而,当他们再次单击搜索按钮时,它应该提交搜索表单(即输入类型应该从按钮更改为提交)。

我已经阅读了一些关于 SO 的帖子,但是这些都是几年前的,我不确定它们是否仍然相关。不能改变输入的类型吗?

【问题讨论】:

  • 为什么不在按钮上设置一个“状态”属性来跟踪当前步骤?第一次单击它会将状态设置为“提交”。第二次单击时执行 form.submit()。更改 type 属性对我来说听起来不太好。

标签: php jquery html


【解决方案1】:

应该这样做:

$('.button').on('click', function(){
  $("#searchtext").animate({width:'toggle'},500);
  $(this).attr('type', 'submit');
});

它不完整,但应该让你更接近你想要的:)

hmm...我认为使用最新的 jQuery,您甚至可以将 on('click' function(){}) 替换为 .click( function(){} );
(旧版本的 .click() 没有 live / on 绑定)

【讨论】:

    【解决方案2】:

    我认为这是可能的,因为type 是一个属性。以下小代码行应该会有所帮助:

    $('#searchsubmit').removeAttr("type").attr("type", "submit");
    

    也许有一种风险较小的方法。方法是添加一个调用提交函数的'onclickEvent':

     $('#searchsubmit').on('click', function () {
        $(this).parents("form:first").submit();
    });
    

    【讨论】:

    • 为什么要先去掉类型?你不能简单地替换/更改类型属性吗?
    • @Steven 我这样做只是为了安全。如果你愿意,你可以忽略它
    【解决方案3】:

    您可以删除类型属性并再次将其设置为提交。

    jQuery("#submitsearch").click(function () {
    jQuery("#searchtext").animate({
        width: 'toggle'
    }, 500);
    jQuery(this).toggleClass("closed");
    var btn = document.getElementById('searchsubmit');
    btn.removeAttribute('type');
    btn.setAttribute('type', 'submit');
    });
    

    工作fiddle

    【讨论】:

    • 为什么要混合使用 DOM 和 jQuery?为什么不直接使用 jQuery?
    • 使用 jquery attr 函数不会覆盖它.. 检查这个小提琴jsfiddle.net/Karim_AG/mSzY5/1
    • 类型仍然是button
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多