根据选择选项显示警告

时间:2015-04-20 16:06:29

标签: javascript php html

这是我的HTML:

<div id="hiddenDiv" style="display: none;">
<h1 id="welcomehowareyou">How are you today, ?</h1>
<select name="mood" id="mood">
<option value="" disabled selected>How are you?</option>
<option value="m1">I'm doing great, thanks!</option>
<option value="m2">I'm fine, but could be better.</option>
<option value="m3">I feel absolutely terrible today.</option>
<!--<input type="submit" value="Done!"/>-->
</select>
<p></p>
</div>

如何在选择选项时显示不同的警报(无论PHP或JavaScript是否最简单)?

此外,当他们点击确定选项时,如何将其重定向到其他链接?

3 个答案:

答案 0 :(得分:2)

请参阅fiddle

您必须使用<select>的onchange侦听器。因此,<select>应如下所示

<select name="mood" id="mood" onchange="myFunction()">
<option value="" disabled selected>How are you?</option>
<option value="m1">I'm doing great, thanks!</option>
<option value="m2">I'm fine, but could be better.</option>
<option value="m3">I feel absolutely terrible today.</option>
<!--<input type="submit" value="Done!"/>-->
</select>

,使用的脚本如下

function myFunction() {
    var x = document.getElementById("mood").value;
    alert(x);
}

这适用于纯Javascript。不需要jQuery。

<强>更新

正如@LyeFish在他的评论中所提到的,你可以将其编码为fiddle中的那个..

此处<select>如下

<select name="mood" id="mood" onchange="myFunction(this.value)">
    <option value="" disabled selected>How are you?</option>
    <option value="m1">I'm doing great, thanks!</option>
    <option value="m2">I'm fine, but could be better.</option>
    <option value="m3">I feel absolutely terrible today.</option>
</select>

,这个javascript将是

function myFunction(val) {
    alert(val);
}

更新2

function myFunction(val) {
        alert(val);
        window.location.href = "http://google.co.in/";
    }

答案 1 :(得分:1)

您可以在JavaScript function中致电onchange evenet,如下所示

<div id="hiddenDiv" >
        <h1 id="welcomehowareyou">How are you today, ?</h1>
        <select name="mood" id="mood" onchange="alert(this.value);window.location = 'http://www.google.com';">
            <option value="" disabled selected>How are you?</option>
            <option value="m1">I'm doing great, thanks!</option>
            <option value="m2">I'm fine, but could be better.</option>
            <option value="m3">I feel absolutely terrible today.</option>
        </select>
    </div>
    <!--
        You can write JS function to do as per your requirement and call the function in onchange event.
        Here it is alerting the selected value and redirecting to http://google.com. 
        You can redirect to different website also using conditional statement.
    -->

答案 2 :(得分:-1)

您需要检测select的更改事件,然后查看选定的选项。

就像那样:

$('#mood').on('change', function() {
   //alert( this.value ); // or $(this).val()
    switch(this.value){
        case "m1":
            alert("option 1");
            break;
        case "m2":
            alert("option 2");
            break;
        case "m3":
            alert("option 3");
            break;
    }
    });

https://jsfiddle.net/2qpwhz6h/