简体   繁体   中英

Jquery: Change input type from button to submit

I have an animated search form as below.

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

When the search button is first clicked, it toggles out the text area where a user can type in what they want to search. When they click the search button again however, it should submit the search form (ie the input type should change from button to submit).

I've read a few posts on SO already, however these are from a few years ago & I'm not sure if they are still relevant. Is it not possible to change an input's type?

I think it is possible, because type is an attribute. Follwing small code line should help:

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

Maybe there is a way with less risk. The way is to add an 'onclickEvent' that called a submit function:

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

Something like this should do it:

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

It's not complete, but should get you closer to what you want :)

hmm... I think that with the latest jQuery, you can even replace on('click' function(){}) with .click( function(){} );
(The old version of .click() did not have the live / on bindings)

You can remove the type attribute and set it again as 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');
});

Working fiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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