开发者

JavaScript alert doesn't show

I am trying to built a select option menu. If the user chooses the first (default) option, the alert window should be shown, but it isn't shown. Need help, thanks!

Here is my html code

    <select name="sets" id ="selectset">
        <option value="General">Select Set</option>
        <option value="The Happy Couple">Ceremony</option>
        <option value="Ceremony">Ceremony</option>
        <option value="Lunch">Lunch</option>
        <option value="Garden">Garden</option>
        <option value="Longname">This is max length</option>
      </select>
     <input type="button" class="form_button" id="movetoset" value="  Move Marked to Set">

Here is my javascript code

    $('#movetoset').click(function() {开发者_开发知识库      

              if(document.getElementById("selectset").value == "General"){
                  alert("Please choose a set");
              }
    }


Why aren't you using jQuery for getting the value of the select as well?

http://jsfiddle.net/davelnewton/CUGva/


change html code to

<input type="button" class="form_button" onclick="checkFunct()" id="movetoset" value="  Move Marked to Set">

and add javascript

function checkFunct() {
    if(document.getElementById("selectset").value == "General"){
              alert("Please choose a set");
          }
  }


You need to ensure that the JavaScript code you posted is either:

  • In the document ready (or onload) handler, and/or
  • After the HTML in the page source

Otherwise when you try to select the button by its ID the button element won't have been parsed yet so it won't be found and no click handler will be attached.

Try this:

$(function() {
   // other document ready processing (if any) here

   $('#movetoset').click(function() {
      if($("#selectset").val() == "General"){
         alert("Please choose a set");
      }
   }

   // other document ready processing (if any) here
});

(Noting that $(function() {}); is short-hand for $(document).ready(function(){});)

And as long as you're using jQuery, why not use its .val() function?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜