繁体   English   中英

jQuery:将输入类型从按钮更改为提交

[英]Jquery: Change input type from button to submit

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

<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的一些帖子,但是这些帖子是几年前的,我不确定它们是否仍然有用。 不能更改输入的类型吗?

我认为这是可能的,因为type是属性。 跟随小代码行应该有帮助:

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

也许有一种方法可以降低风险。 方法是添加一个调用提交功能的“ onclickEvent”:

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

这样的事情应该做到:

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

它还不完整,但是应该使您更接近想要的东西:)

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

您可以删除type属性并将其再次设置为Submit。

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');
});

工作提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM