按钮更改为输入电子邮件onclick jquery

时间:2018-03-09 09:39:54

标签: javascript jquery input

我想问一下点击后如何将按钮更改为电子邮件输入字段。按钮的div是:

HTML

<button class="read-more-button email-button" id="news-button" onClick="addInputField()">Enter your email</button>

功能

function addInputField(){
    var element = document.createElement("input");
    element.setAttribute("type", "email");
    element.setAttribute("value", "");
    element.setAttribute("name", "Email");
    document.body.appendChild(element);
    document.getElementById("news-button").innerHTML = element.value; 
 }

但我从属性element.setAttribute("value", "");

中获取空值

如何在点击按钮后将按钮更改为电子邮件输入字段并获取字段的值?

1 个答案:

答案 0 :(得分:0)

使用jQuery,您可以使用replaceWith()函数

$('#news-button').click(function(){
      $(this).replaceWith( "<input id='emailAddress' type='email'>" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="read-more-button email-button" id="news-button">Enter your email</button>