Why can't I change the type of an input elemen

2020-02-26 15:20发布

I'm calling this function:

function submit_button(button_id){
    $('#' + button_id).attr('type', 'submit');
}

to make this button type = submit instead of button.:

<input  name="confirm_button" id="confirm_button" type="button" value="Confirm" class="login_btn" />

and I get this error (in firefox):

uncaught exception: type property can't be changed

Are there any work arounds?

7条回答
冷血范
2楼-- · 2020-02-26 15:23
function submit_button(button_id){
    $('#' + button_id).prop('type', 'submit');
}

Be aware that this changes the type but not the value, so the button will still read "confirm".

A fiddle to prove it : http://jsfiddle.net/qeUxP/

查看更多
Juvenile、少年°
3楼-- · 2020-02-26 15:26

javascript:

function submit_button(){

      var btn=document.getElementById('button_id');
      btn.setAttribute('type', 'submit');

  }

======================================================================

Jquery:

function submit_button(){

 $('#' + button_id).prop('type', 'submit');

   }

======================================================================

查看更多
萌系小妹纸
4楼-- · 2020-02-26 15:28

Why not just bind to the click event and call the form submit in your click handler?

查看更多
Melony?
5楼-- · 2020-02-26 15:30

It worked finally , try finding the following:

   $("#confirm_button").each(function () 
   { this.type = "number"; });
查看更多
Animai°情兽
6楼-- · 2020-02-26 15:34

Here's a workaround:

$('<input name="confirm_button" id="confirm_button2" type="submit" value="Confirm" class="login_btn" />').insertAfter('#confirm_button');
$('#confirm_button').remove();
查看更多
爷、活的狠高调
7楼-- · 2020-02-26 15:41

Why jQuery won't allow you to just change the type attribute?

Because it causes problems in Internet Explorer.

More info at: change type of input field with jQuery

"Straight from the jQuery source":

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";
查看更多
登录 后发表回答