0

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?

1
  • 1
    Your rowString is just a string but your rowString.val(...) only works on jQuery objects. Create a jQuery object for it like Taplar does in his answer. Commented Jun 10, 2019 at 16:32

2 Answers 2

4
$(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>

Sign up to request clarification or add additional context in comments.

2 Comments

If I do $(rowString).val('myval').val() I get myval which is great. When I use $(rowString).val('myval').prop('outerHTML') I get the original string back (with no value)
Sorry, you actually have to use attr() in this case. Answer updated. @fugu
0
$(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>`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.