notify
notify

Reputation: 59

Append data to <script>

I have a row that I am cloning sometimes.

<script id="SubRow10" type="text/template">
  <select id="SubSelect10" class="form-control" name="SubcategorySelect" required>
    <option value="m,2">Op1</option>
    <option value="m,3">Op2</option>
    <option value="m,5">Op3</option>
    <option value="m,6">Op4</option>
  </select>
</script>

I have a form to add an option to "#Subselect10" But when I do this:

$('#SubSelect10').append('<option value="m,8">Op5</option>');

It does not work, but when I do this:

$('#SubRow10').append('<option value="m,8">Op5</option>');

It works, but it won't add it to the Select menu.

Can someone lead me in the right direction?

Here is a JSFiddle

Upvotes: 2

Views: 50

Answers (2)

Patrick Roberts
Patrick Roberts

Reputation: 51766

Do this:

var template = $('#SubRow10');

template.html($(template.html()).append('<option value="m,8">Op5</option>'));

console.log(template.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script id="SubRow10" type="text/template">
  <select id="SubSelect10" class="form-control" name="SubcategorySelect" required>
    <option value="m,2">Op1</option>
    <option value="m,3">Op2</option>
    <option value="m,5">Op3</option>
    <option value="m,6">Op4</option>
  </select>
</script>

The problem is that <script> tags do not render their contents as HTML, but as text, even if the type is not text/javascript. In order to circumvent the problem, you need to parse the contents as HTML before injecting another <option>.

Upvotes: 1

Aurora0001
Aurora0001

Reputation: 13547

Presumably the issue is that your string, "<option value="m,8">Op5</option>" contains a double quote, so JavaScript treats it as two different separate parameters to the function. Try either escaping the double quotes in the string (use \" instead) or use single quotes to wrap the string, e.g.

$("#SubRow10").append('<option value="m,8">Op5</option>')

Upvotes: 0

Related Questions