Rubel Ctg Rubel Ctg - 2 months ago 6
jQuery Question

how work id^=value in javascript

$("[id^='Qty-']").each(function() {

itemElementId = $(this).attr('id');
var productId = 0;
productId = itemElementId.replace("Qty-", "");

postArr[index] = { ProductId: productId, Qty: $(this).val() }
index++;
});


I can't understand $("[id^='Qty-']") meaning. why use this. please help me

Answer

Some JQuery basics:

The selector $("[id^='Qty-']") will search for all the elements having attribute Id having value starting with Qty-

here's an example how this selector is looking for id values Qty- and displaying the content of td

$(document).ready(function(){
 $("[id^='Qty-']").each(function(){
alert($(this).html());
 });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<table>
<tr>
  <td id="Qty-1">Qty1</td>
  <td id=Qty-2>Qty2</td>
</tr>
</table>
</div>

For more information and learning, please refer this link on attribute selectors. http://api.jquery.com/category/selectors/attribute-selectors/

Hope this helps..