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

2020-02-26 14:58发布

问题:

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?

回答1:

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/



回答2:

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


回答3:

It worked finally , try finding the following:

   $("#confirm_button").each(function () 
   { this.type = "number"; });


回答4:

Here's a workaround:

$('<input name="confirm_button" id="confirm_button2" type="submit" value="Confirm" class="login_btn" />').insertAfter('#confirm_button');
$('#confirm_button').remove();


回答5:

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



回答6:

javascript:

function submit_button(){

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

  }

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

Jquery:

function submit_button(){

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

   }

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



回答7:

The workaround is to create an element of the correct type, and replace the currently exisitng one.

However, in your example, a <button> element could serve the purpose of submitting the form, render as a button, and not require any javascript to do so, eg:

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

And then to make the button enabled again:

$('confirm_button').removeAttr('disabled');