从JavaScript下拉列表中选择某个特定值时发出警报

时间:2017-05-01 04:19:29

标签: javascript

以下是下拉数据..

<select size="1" name="Test_Data">
        <option selected value="Select One">Select One</option>
        <option value="Data1">IN-Data1</option>
        <option value="Data2">IN-Data2</option>
        <option value="Data3">IN-Data3</option>
        <option value="Data4">AUS-Data4</option>
        <option value="Data5">AUS-Data5</option>
        <option value="Data6">US-Data6</option>
        <option value="Data7">US-Data7</option>

当我从下拉列表中选择从IN开始的数据时,我想要提醒/弹出。

3 个答案:

答案 0 :(得分:1)

试试这个:

https://jsfiddle.net/mminetto/bggwnkwj/

var select = $('select[name="Test_Data"]');
select.on('change', function(){
    var options = select.children('option:selected');
  if(options.length > 0 && options[0].innerText.startsWith("IN")){
    alert(this.value);
    alert(options[0].innerText);
  }
});

答案 1 :(得分:0)

<select size="1" name="Test_Data" id="dropdown">
        <option selected value="Select One">Select One</option>
        <option value="Data1">IN-Data1</option>
        <option value="Data2">IN-Data2</option>
        <option value="Data3">IN-Data3</option>
        <option value="Data4">AUS-Data4</option>
        <option value="Data5">AUS-Data5</option>
        <option value="Data6">US-Data6</option>
        <option value="Data7">US-Data7</option>

在javascript中

    <script>
        $("#dropdown").change(function(){  
            if($(this).find("option:selected").text().startsWith("IN")){    
              alert("option with IN selected =>"+$(this).find("option:selected").text());
            }
        });
    </script>

答案 2 :(得分:-1)

试试此代码

<强> HTML

<select size="1" onChange="showAlert()" id="dataCountry" name="Test_Data">
        <option selected value="Select One">Select One</option>
        <option value="Data1">IN-Data1</option>
        <option value="Data2">IN-Data2</option>
        <option value="Data3">IN-Data3</option>
        <option value="Data4">AUS-Data4</option>
        <option value="Data5">AUS-Data5</option>
        <option value="Data6">US-Data6</option>
        <option value="Data7">US-Data7</option>
 </select>

<强>的JavaScript

<script>
function showAlert() {
var el = document.getElementById('dataCountry');  // get the index
var text = el.options[el.selectedIndex].innerHTML; // get the label
var n = text.search("IN");  //search number of IN
if(n>=0) {
alert(text);    
}
}
</script>