How to get input via a popup and place text in a variable via javascript/jquery

时间秒杀一切 提交于 2019-12-21 04:28:22

问题


I have a button on my page. When clicked a popup box should appear allowing the user to enter text. When OK/Submit is pressed, my jscript will then perform some functions using that inputted data. Very straightforward, but I just can't figure out how to do this.

Thanks!


回答1:


in it's simplest form, you could use prompt(question, default): (taken from w3schools: http://www.w3schools.com/js/tryit.asp?filename=tryjs_prompt)

function myFunction(){
    var x;
    var name=prompt("Please enter your name","Harry Potter");
    if (name!=null){
       x="Hello " + name + "! How are you today?";
      alert(x);
   }
}

anything else would require lots of javascript & CSS to create layers with buttons and click events on those buttons




回答2:


Paste this code inside your head tags between script tags

HTML

<button id="button">Get Text</button>​

JS

window.onload=function()
{
    var el=document.getElementById('button');
    el.onclick=function(){
        var my_text=prompt('Enter text here');
        if(my_text) alert(my_text); // for example I've made an alert
    }
}

DEMO.



来源:https://stackoverflow.com/questions/11363732/how-to-get-input-via-a-popup-and-place-text-in-a-variable-via-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!