1

Pls see the following html code

<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>

and the jquery code

$( "input[id*='product']" ).val( 'test' );

the result will display 4 textbox with the value of 'test' as default, but now i like to display 4 textbox with the value of the product name, means first textbox will display 'Samsung', 2nd textbox will display 'Apple' & so on, so what command should i put in the jquery code ? pls advise.

3 Answers3

4

Just use .val(fn):

$("input[id^='product_']").val(function() {
        return this.name;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>

For each input element it will invoke the function that will return the value to set.

Bonus

To make it even more concise you could consider a helper function, e.g.:

jQuery.prop = function(name) {
    return function() {
        return this[name];
    }
};

Then, the code becomes:

$("input[id^='product_']").val($.prop('name'));
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

Try this:

$("input[id*='product']").each(function() {
  $this = $(this);
  $this.val($this.attr("name"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="product_code1" name="Samsung"><br>
<input id="product_code2" name="Apple"><br>
<input id="product_code3" name="Huawei"><br>
<input id="product_code4" name="Motorola"><br>
joshhunt
  • 5,197
  • 4
  • 37
  • 60
1
$("input[id*='product']").each(function () {
    var $this = $(this);
    $this.val($this.prop("name"));
});

JSFiddle

user2466202
  • 1,205
  • 10
  • 8