选择时隐藏DIV

时间:2013-03-21 02:54:07

标签: javascript jquery

我有2个选择。 如果用户在没有下拉选择的情况下提交表单,则会在DIV上显示一条消息。 当用户选择值时,有一种HIDE div(消失?)的方法?

SCRIPT:          

$(document).ready(function () {
$("#go").click(function () {

if (document.getElementById('sel').selectedIndex == 0)
$("#msg").html("Please select 1");


if (document.getElementById('sel2').selectedIndex == 0)
$("#msg2").html("Please select 2");

});
});

FORM:

<form id="form1">  
<div id="msg"></div>                  
<select id="sel">
<option value="">-- select --</option>
<option value="valor1">Valor 1</option>
<option value="valor2">Valor 2</option>
</select>

<div id="msg2"></div>
<select id="sel2">
<option value="">-- select --</option>
<option value="valor1">Valor 1</option>
<option value="valor2">Valor 2</option>
</select>

<input type="button" id="go" value="Go" />
</form>

3 个答案:

答案 0 :(得分:2)

你能做些什么利用jQuery中的change事件。这允许您监视特定元素(例如select元素)的更改。我做了fiddle for you。示例代码可以在这里看到:

$("#go").click(function () {
    if (document.getElementById('sel').selectedIndex == 0) $("#msg").html("Please select 1");
    if (document.getElementById('sel2').selectedIndex == 0) $("#msg2").html("Please select 2");
});

$('select').change(function() {
    if (document.getElementById('sel').selectedIndex != 0) $("#msg").fadeOut();
    if (document.getElementById('sel2').selectedIndex != 0) $("#msg2").fadeOut();
});

这应该是一个很好的起点。希望这有帮助!

答案 1 :(得分:1)

隐藏div的最佳方法是使用CSS属性显示并将其设置为none。在jQuery中,您可以使用hide方法执行此操作,也可以通过css方法手动执行此操作。

$('#msg').hide();
$('#msg2').css('display','none');

答案 2 :(得分:1)

$("#go").click(function () {

if ($('#sel').val() == '')
    $("#msg").text("Please select 1");


if ($('#sel2').val() == '')
$("#msg2").text("Please select 2");

});
$('#sel').change(function(){$('#msg').hide()})
$('#sel2').change(function(){$('#msg2').hide()})

并且正在使用jsfiddle:http://jsfiddle.net/RmYbH/2/