Alphy Alphy - 5 months ago 11
jQuery Question

Check number of elements jQuery

I would like to get the number of

textarea
elements in a given table cell. Using that I want to add remove functionality to one element at a time if and only if there are more than two, and also be able to undo the removed
textarea
if I click an 'undo' link. Below is a sample snippet:

<table class="result_table">
<tr valign="middle" align="center">
<td style="font-size:13px; " class="tbody_data side">Dissolution</td>
<td valign="middle" align="center" style="padding: 0px;" class="tbody_data">
<input type="hidden" value="2" name="tests[]">
<textarea style="border:none; vertical-align: middle;" class="det_st form-control">UV</textarea>
</td>
<td style="padding: 0px;" class="tbody_data">
<textarea style="border:none;" class="det_st form-control">USP 38 NF 33 Page 4635</textarea>
</td>
<td style="padding: 0px;" class="tbody_data">
<textarea style="border:none;" class="det_st form-control">Acid Stage Not more than 10.0% [n=6]
</textarea>
<textarea style="border:none;" class="det_st form-control">Buffer Stage Not Less than 70.0% [n=6]
</textarea>
</td>
<td style="padding: 0px;" class="tbody_data">
<textarea style="border:none;" class="det_st form-control"> Acid Stage 107.8% (RSD=5.2%; n=6) </textarea>
<textarea style="border:none;" class="det_st form-control"> Buffer Stage 102.2% (RSD=0.9%; n=6)</textarea>
</td>
<td style="padding: 25px; width:50px;" class="tbody_data side">
<select style="border:none; margin:15px; width:145px;" class="select" selected="selected">
<option value="COMPLIES">COMPLIES</option>
<option value="COMPLIES">COMPLIES</option>
<option value="DOES NOT COMPLY">DOES NOT COMPLY</option>
</select>
<select style="border:none; margin:15px; width:145px;" class="select" selected="selected">
<option value="COMPLIES">COMPLIES</option>
<option value="COMPLIES">COMPLIES</option>
<option value="DOES NOT COMPLY">DOES NOT COMPLY</option>
</select>
</td>
</tr>
</table>


$(document).on('mouseover', '.result_table tr td', function() {
$('textarea', this).dblclick(function() {
$(this).remove()
alert( $(this).length) //gives one even when a cell contains two teatareas
});
})


Suggestions welcome.

Answer

You can do something like this :

$(document).on('mouseover', '.result_table tr td', function() {
  $('textarea', this).dblclick(function() {
    var self = $(this);
    var nbelement = self.parent('td').find('textarea').length;
    if (nbelement >= 2) {
      self.remove()
    }
  });
})

https://jsfiddle.net/Tintin37/z5x4bsuc/

Comments