javascript onclick alert not working in chrome

前端 未结 5 697
青春惊慌失措
青春惊慌失措 2020-12-03 19:01

                        
    
提交评论

  • 2020-12-03 19:42

    If you want to use onClick for option element in Chrome, IE, etc., you must use short fix: set onChange attribute of select element to "this.options[this.selectedIndex].onclick()"

    0 讨论(0)
  • 2020-12-03 19:44

    Use onChange on the select instead of each option. here is the jsfiddle http://jsfiddle.net/tBjkg/

    <select name="history" id="history" onChange="alert(this.value);">
     <option value="history1">history 1</option>
     <option value="history2">history 2</option>
     <option value="clearhistory">Clear History</option>
    </select>
    

    The alert(this.value) is referring to the value of the option within the select that is currently selected.

    0 讨论(0)
  • 2020-12-03 19:48

    In some browsers,

    choosing same option second time,

    no onchange-event throws.

    This helps:

    <select onchange="alert/*orwhateveryoudowith:*/(this.value);/*but set:*/this.selectedIndex=0">
    <option disabled selected>Choose your Plan</option>
    <option value=1>Plan 1</option>
    <option value=2>Plan 2</option>
    <option value=3>Plan 3</option>
    </select>
    
    0 讨论(0)
  • 2020-12-03 19:59

    Although the selected solution works, but here is a more clearer and easy way to do this:

    <select name="history" id="history" >
    <option value="history 1">history 1</option>
    <option value="history 2">history 2</option>
    <option value="clearhistory">Clear History</option>
    </select>
    
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    $('#history').on('change', function() {
      if ( this.value == 'history 1')
      {
       alert('h1');
      // You can also do anything here
      }
      if ( this.value == 'history 2')
      {
       alert('h2');
      // You can also do anything here
      }
      if ( this.value == 'clearhistory')
      {
       this.form.submit();
      // You can also do anything here
      } 
      });
    });
    </script>
    
    0 讨论(0)
  • 提交回复
    热议问题