fugu
fugu

Reputation: 6568

Add html attribute to string

I am appending some html to a div using jQuery, where both rowString and inputString are defined previously:

$("#filterContainer").append(
            rowString +
            `<label class='filterLabel' for=${filter}>${filter}</label>` +
            "<i class='fas fa-minus-circle removeFilter float-right'></i>" +
            inputString +
            "</div>"
        );

rowString looks like this:

let rowString = "<input id='autocomplete' type='search' class='form-control' name='filters[location]' >"

And I am trying to inject a value into this. I've tried rowString.val('myvalue'), but it fails with Uncaught TypeError: string.val is not a function.

How can I add an html attribute such as value to a string?

Upvotes: 0

Views: 60

Answers (2)

Leandro Machado
Leandro Machado

Reputation: 1

$(rowString).val('myvalue')

And, change your append to this:

$("#filterContainer").append(`${rowString}<label class='filterLabel' for=${filter}>${filter}</label><i class='fas fa-minus-circle removeFilter float-right'></i>${inputString}</div>`);

Upvotes: 0

Taplar
Taplar

Reputation: 24965

$(rowString).attr('value', 'myvalue').prop('outerHTML')

You can parse it, set the value, and then get the outerHTML to get the HTML back.

let rowString = "<input id='autocomplete' type='search' class='form-control' name='filters[location]' >";

console.log(
  $(rowString).attr('value', 'myvalue').prop('outerHTML')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 4

Related Questions