2013-01-21 43 views
0

是否有可能在<select>获取先前选定的值或以某种方式防止默认值?比如我有获取先前选定的值或防止默认选择

<select id="select_site" name="sites" selectedindex="0"> 
<option value="">Please select site</option> 
<option value="4">first</option> 
<option value="5" selected="selected">second</option> 
<option value="8">third</option> 
</select> 

所以,如果用空值选择的选项,我需要恢复之前选择的second值。

+0

您可以跟踪之前选择的值。 .. –

+0

@FelixKling如何? – Kin

回答

1

可以绑定change事件处理函数的元素和存储在一个变量的新值。如果该值是一个空字符串,将其设置为无论是在变量:

$('#select_site').change(function() { 
    if (this.value === '') { 
     this.value = $(this).data('previous_value'); 
    } 
    else { 
     $(this).data('previous_value', this.value); 
    } 
}).triggerHandler('change'); // <- trigger change event to get initial value 

DEMO

0

不,你不能这样做,因为更改事件是在选择集中之后触发的,而不是在选择更改之前触发。 “before beforechange”事件中没有本地,但是您可以在选择更改后删除空值,使其不再可用。

代码做到这一点:

$('select').change(function (event) { 
    $this = $(this); 
    if ($this.val() !== '') { 
     $this.children('option:first').remove(); 
    } 
}); 
+0

但是如何检测女巫值是之前? – Kin

+0

@Kirix除非您以JavaScript方式存储之前的值,否则您无法进行此操作。 –

+0

我不需要删除值,我只需要返回到前一个 – Kin

1

没有JS需要:

<select id="select_site" name="sites" selectedindex="0"> 
    <optgroup label="Please select site"> 
    <option value="4">first</option> 
    <option value="5" selected="selected">second</option> 
    <option value="8">third</option> 
    </optgroup> 
</select> 

演示:http://jsbin.com/obeker/1/

REF:https://developer.mozilla.org/docs/HTML/Element/optgroup

+0

不坏:)..... –

+0

多一个 - 如果选定的值为NULL,我需要返回以前的值! – Kin

+0

@Kirix 1)不需要大喊,2)你不能用上面的代码选择'null'。 – Yoshi