views:

42

answers:

2

I'm trying to set the select option back to the "choices" every time I finish adding a new row. How can I do it here? Please help. Btw, adding new row(s) works just fine. Here is what I've got so far:

$(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>
+4  A: 

You can set it back by using .val(value) to set the value, like this:

$("#a").val('None');

Overall it'll look like this:

$(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');
  });
});
Nick Craver
awesome! that's so simple, and it works. thanks.
DGT
+1  A: 

Here's a generic approach that will allow for you to reset a number of values:

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.
  });
});

You could put the setDefaultValues() code inside the click function, but I put it and the getDefaultValues() code in functions to make it more obvious.

HTML (example)

<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">

This code in action.

Gert G