1

I am trying to reset fields (selects and textboxes) in a partial. Here is what I have so far:

var $inputs = $('#StudentTable :select');
$inputs.each(function () { 
  if ($(this).name = "TeachingAsstSelect") { 
    $('select[name="TeachingAsstSelect"]').each(function () { 
      $(this).text(""); 
    }) 
  } 
  else { 
    $(this).val("Select");
  } 
});

Here "TeachingAsstSelect" is being cleared, but other selects are not reset. Am I missing something? More importantly, Am I doing it the right way?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user793468
  • 4,898
  • 23
  • 81
  • 126

2 Answers2

1

For jQuery objects you should use attr() method, name is one of the DOM Element properties.

Change this:

  if ($(this).name = "TeachingAsstSelect") { 

to:

  if ($(this).attr('name') == "TeachingAsstSelect") { 

also note that for comparison you should use == operator, currently you are setting the value.

Ram
  • 143,282
  • 16
  • 168
  • 197
1

If you are trying to test equality of a string, you should use == or ===. See here form more on that: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Also, as @Raminson suggests, try use the attr() method instead.

if ($(this).attr('name') == "TeachingAsstSelect") { 

Or better yet, nesting .each() twice like that may not perform as well as other solutions.

I also notice that you are testing name in your if condition then using a jquery selector to match again on [name="TeachingAsstSelect"]. What about simplifying like this:

var $teachingAsstInputs = $('#StudentTable :select[name="TeachingAsstSelect"]');
$($teachingAsstInputs).text(""); 

var $otherInputs = $('#StudentTable :select').not('[name="TeachingAsstSelect"]');
$($otherInputs).val("Select"); 
Community
  • 1
  • 1
shanabus
  • 12,989
  • 6
  • 52
  • 78