最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - html5 basic alert and textbox - Stack Overflow

programmeradmin0浏览0评论

I am a newbie in HTML5 and javascript. I want an alert box to display data(firstname and lastname). Data must be taken from textboxes on the form. My code is below, but the alertbox doesn't work.

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp" method="get">
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>

</form>
<script>
function display_alert()
  {
   alert(fname +lname);
  }
</script>

<input type="button" onclick="display_alert()" value="Display alert box">

</body>
</html>

I am a newbie in HTML5 and javascript. I want an alert box to display data(firstname and lastname). Data must be taken from textboxes on the form. My code is below, but the alertbox doesn't work.

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp" method="get">
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>

</form>
<script>
function display_alert()
  {
   alert(fname +lname);
  }
</script>

<input type="button" onclick="display_alert()" value="Display alert box">

</body>
</html>
Share Improve this question edited Jan 3, 2013 at 9:17 Rikesh 26.5k14 gold badges81 silver badges89 bronze badges asked Jan 3, 2013 at 9:10 user1942359user1942359 1,6393 gold badges14 silver badges8 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

You need to give ids to inputs tags

   <form>
        <input id="a" type="text"/>
        <input id="b" type="text"/>
        <input type="button" onclick="display_alert();" />
    </form>

and then use them inside your js code:

<script lang="javascript">
    function display_alert() {
        var fn = document.getElementById('a');
        var ln = document.getElementById('b');
        alert(fn.value + ' ' + ln.value);
    }
</script>

You can use jQuery.

html:

First name: <input type="text" id='fname' /><br>
Last name: <input type="text"  id='lname'/><br>
<input type="button" onclick="display_alert();" value="Display alert box">

script:

function display_alert() {
    fname = $('#fname').val();
    lname = $('#lname').val();
    alert(fname+' '+lname);
}​

demo

Jquery might be useful for the future.

You need to get values using getElementsByName function in your script.

Try changing your script with below one.

<script> 
  function display_alert()
  {
     var fname = document.getElementsByName("fname")[0].value;
     var lname = document.getElementsByName("lname")[0].value;
     alert(fname + ' ' + lname); 
  }
</script>

Note: Just for your information, there is no relation with HTML5 to this.

发布评论

评论列表(0)

  1. 暂无评论