Search code examples
jqueryajaxlaravelajaxform

Running Loop on field names in AJAX


I am getting a correct result if I mention each field name in ajax, how can I get the same result using a loop.

without loop:

$("[name='efirst']").val(data.teacher.efirst);
$("[name='esecond']").val(data.teacher.esecond);
.
.

Fields:

<input type="text" name="efirst" id="efirst">
<input type="text" name="esecond" id="esecond">

I am also getting a correct result if I run loop on ID, but how can I achieve same on, NAME instead of ID.

loop on id:

teacher.forEach(item => { $("#"+item[0]).val(item[1]); });

Solution

  • To make it readable you can use es6 template literal

    teacher.forEach(item => { $(`[name=${item[0]}]`).val(item[1]); });
    

    read template literals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals