将选择选项设置回默认选中

时间:2010-07-23 00:43:47

标签: javascript jquery

每次添加新行时,我都会尝试将select选项设置回“选项”。我怎么能在这里做?请帮忙。顺便说一句,添加新行可以正常工作。这是我到目前为止所得到的:

$(document).ready(function() {
   $('#Add-btn').live('click',function() {
      $("#tabName tr:last").before("<tr><td class='greyed'><input type='hidden' name='allele' value='" + a + "'>" + a + "</td><td><input type='button' class='delete' value='Remove'></td></tr>");
   });
});

HTML:

<table id="tabName">
...
<select size='1' id="a" name='a'>
   <option value="None" selected>choices</option>
   <option value='1'>first</option>
   <option value='2'>second</option>
</select>
...
</table>
<div>
   <input id="Add-btn" class="button" type="button" value="Add" />
   <span></span>
</div>

3 个答案:

答案 0 :(得分:4)

您可以使用.val(value)设置值,如下所示:

$("#a").val('None');
总的来说,它看起来像这样:

$(document).ready(function() {
  $('#Add-btn').live('click',function() {
    $("#tabName tr:last").before("<tr><td class='greyed'><input type='hidden' name='allele' value='" + a + "'>" + a + "</td><td><input type='button' class='delete' value='Remove'></td></tr>");
    $("#a").val('None');
  });
});

答案 1 :(得分:2)

这是一种通用的方法,可以让你重置一些值:

<强>的jQuery

$(document).ready(function(){
  var DefaultValuesElements=$(":input").not("#resetvalues");  // The elements you want to reset (in this example, all input values, except for the button with the ID resetvalues

  function getDefaultValues() {
    DefaultValuesElements.each(function() {  // Loop through the elements you want default for
      $(this).attr("defaultvalue",$(this).val());  // Grab the value and save them into a custom attribute ("defaultvalue")
    });
  }

  function setDefaultValues() {
    DefaultValuesElements.each(function() {  // Loop through the elements you want to reset the values for
      $(this).val($(this).attr("defaultvalue"));  // Overwrite the current value with the saved default value
    });
  }

  getDefaultValues();  // Grab the values

  $("#resetvalues").click(function() {  // Belongs to the example below. Whenever the button is pressed...
    setDefaultValues();  // Reset the elements to their default values.
  });
});

您可以将setDefaultValues()代码放在click函数中,但我将它和getDefaultValues()代码放在函数中以使其更明显。

HTML(示例)

<select size='1' id="a" name='a'>
 <option value="None" selected>choices</option>
 <option value='1'>first</option>
 <option value='2'>second</option>
</select>

<input type="input" name="whatever" value="test">

<input type="button" id="resetvalues" value="Reset values">

code in action

答案 2 :(得分:0)

我知道这已经得到了解答,但我只想为像我这样的类似用例做出贡献,我想在用户按下esc时将默认值放回到选择框中。这也可以防止.change事件触发选择元素。

所以根据这里提出的想法和here,这是另一个好的答案:

var KEYCODE_ESC = 27;
// when esc is pressed while scrolling through the options
// reset value of select to default (first) value
$('select').keyup(function(e) {
    if (e.keyCode == KEYCODE_ESC) {
        console.log('esc key pressed on select element'); 
        $(this).val($(this).children('option:first-child').text());
    } 
});