[javascript] jQuery를 사용하여 입력 필드 유형 변경

$(document).ready(function() {
    // #login-box password field
    $('#password').attr('type', 'text');
    $('#password').val('Password');
});

이것은 일반 텍스트 필드 의 #password입력 필드 (로 id="password") 를 변경 type password한 다음 “암호”텍스트를 채 웁니다.

그래도 작동하지 않습니다. 왜?

형식은 다음과 같습니다.

<form enctype="application/x-www-form-urlencoded" method="post" action="/auth/sign-in">
  <ol>
    <li>
      <div class="element">
        <input type="text" name="username" id="username" value="Prihlasovacie meno" class="input-text" />
      </div>
    </li>
    <li>
      <div class="element">
        <input type="password" name="password" id="password" value="" class="input-text" />
      </div>
    </li>
    <li class="button">
      <div class="button">
        <input type="submit" name="sign_in" id="sign_in" value="Prihlásiť" class="input-submit" />
      </div>
    </li>
  </ol>
</form>



답변

이 조치는 브라우저 보안 모델의 일부로 방지 될 수 있습니다.

편집 : 실제로, Safari에서 지금 테스트하면 오류가 발생 type property cannot be changed합니다.

편집 2 : jQuery에서 직접 오류가 발생한 것 같습니다. 다음의 간단한 DOM 코드를 사용하면 정상적으로 작동합니다.

var pass = document.createElement('input');
pass.type = 'password';
document.body.appendChild(pass);
pass.type = 'text';
pass.value = 'Password';

편집 3 : jQuery 소스에서 직접, 이것은 IE와 관련이있는 것 같습니다 (그리고 버그 또는 보안 모델의 일부 일 수 있지만 jQuery는 구체적이지 않습니다).

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


답변

훨씬 더 쉽습니다 … 모든 동적 요소 생성이 필요하지 않습니다. 하나는 ‘실제’비밀번호 필드 (type = “password”)와 하나는 ‘가짜’비밀번호 필드 (type = “text”)로 두 개의 별도 필드를 만들어 가짜 필드의 텍스트를 밝은 회색으로 설정하고 초기 값을 ‘비밀번호’로 설정합니다. 그런 다음 아래와 같이 jQuery를 사용하여 몇 줄의 Javascript를 추가하십시오.

    <script type="text/javascript">

        function pwdFocus() {
            $('#fakepassword').hide();
            $('#password').show();
            $('#password').focus();
        }

        function pwdBlur() {
            if ($('#password').attr('value') == '') {
                $('#password').hide();
                $('#fakepassword').show();
            }
        }
    </script>

    <input style="color: #ccc" type="text" name="fakepassword" id="fakepassword" value="Password" onfocus="pwdFocus()" />
    <input style="display: none" type="password" name="password" id="password" value="" onblur="pwdBlur()" />

따라서 사용자가 ‘가짜’비밀번호 필드를 입력하면 비밀번호가 숨겨지고 실제 필드가 표시되며 초점이 실제 필드로 이동합니다. 가짜 필드에 텍스트를 입력 할 수 없습니다.

사용자가 실제 비밀번호 필드를 벗어나면 스크립트가 비어 있는지 확인하고, 그렇다면 실제 필드를 숨기고 가짜 비밀번호를 표시합니다.

IE는 두 입력 요소 사이에 공백을 두지 않도록주의하십시오. IE는 공백을 렌더링하고 공백을 렌더링합니다. 사용자가 입력 / 종료하면 필드가 움직이는 것처럼 보입니다.


답변

원스텝 솔루션

$('#password').get(0).type = 'text';


답변

요즘에는 사용할 수 있습니다

$("#password").prop("type", "text");

그러나 물론, 당신은 정말로 이것을해야합니다

<input type="password" placeholder="Password" />

IE 이외의 모든 것. IE의 해당 기능을 모방하기 위해 자리 표시 자 shim이 있습니다.


답변

더 많은 브라우저 간 솔루션 … 이것의 요점이 누군가를 도울 수 있기를 바랍니다.

이 솔루션은 type속성 을 설정하려고 시도 하고 실패하면 <input>요소 속성과 이벤트 핸들러를 유지하면서 새 요소 를 작성합니다 .

changeTypeAttr.js( 깃 허브 요점 ) :

/* x is the <input/> element
   type is the type you want to change it to.
   jQuery is required and assumed to be the "$" variable */
function changeType(x, type) {
    x = $(x);
    if(x.prop('type') == type)
        return x; //That was easy.
    try {
        return x.prop('type', type); //Stupid IE security will not allow this
    } catch(e) {
        //Try re-creating the element (yep... this sucks)
        //jQuery has no html() method for the element, so we have to put into a div first
        var html = $("<div>").append(x.clone()).html();
        var regex = /type=(\")?([^\"\s]+)(\")?/; //matches type=text or type="text"
        //If no match, we add the type attribute to the end; otherwise, we replace
        var tmp = $(html.match(regex) == null ?
            html.replace(">", ' type="' + type + '">') :
            html.replace(regex, 'type="' + type + '"') );
        //Copy data from old element
        tmp.data('type', x.data('type') );
        var events = x.data('events');
        var cb = function(events) {
            return function() {
                //Bind all prior events
                for(i in events)
                {
                    var y = events[i];
                    for(j in y)
                        tmp.bind(i, y[j].handler);
                }
            }
        }(events);
        x.replaceWith(tmp);
        setTimeout(cb, 10); //Wait a bit to call function
        return tmp;
    }
}


답변

이것은 나를 위해 작동합니다.

$('#password').replaceWith($('#password').clone().attr('type', 'text'));


답변

jQuery를 사용하는 궁극적 인 방법 :


원래 입력 필드를 화면에서 숨겨 두십시오.

$("#Password").hide(); //Hide it first
var old_id = $("#Password").attr("id"); //Store ID of hidden input for later use
$("#Password").attr("id","Password_hidden"); //Change ID for hidden input

JavaScript로 새 입력 필드를 즉석에서 생성하십시오.

var new_input = document.createElement("input");

숨겨진 입력 필드에서 새 입력 필드로 ID 및 값을 마이그레이션하십시오.

new_input.setAttribute("id", old_id); //Assign old hidden input ID to new input
new_input.setAttribute("type","text"); //Set proper type
new_input.value = $("#Password_hidden").val(); //Transfer the value to new input
$("#Password_hidden").after(new_input); //Add new input right behind the hidden input

와 같은 IE의 오류를 해결하려면 다음과 같이 type property cannot be changed유용합니다.

숨겨진 입력에서 동일한 이벤트를 트리거하려면 클릭 / 초점 / 변경 이벤트를 새 입력 요소에 연결하십시오.

$(new_input).click(function(){$("#Password_hidden").click();});
//Replicate above line for all other events like focus, change and so on...

오래된 숨겨진 입력 요소는 여전히 DOM 안에 있으므로 새 입력 요소에 의해 트리거되는 이벤트와 반응합니다. ID가 바뀌면 새로운 입력 요소는 이전 입력 요소처럼 작동하고 이전 숨겨진 입력 ID에 대한 함수 호출에 응답하지만 다르게 보입니다.

조금 까다 롭지 만 작동합니다! 😉