I have a web app, backend using Django, frontend using HTML5.
I want to pass a variable from bootstrap table to the quotation in javascript.
<th class ='Format_issued' data-field="book.publisher" data-formatter="renderFormat">Material Format</th>
<script>
function renderFormat(value) {
return '<select style="width: 7em" name="Material_format" id="Material_format" >\n' +
' <option value="">--Select--</option>\n' +
' <option value="eText" {% if ' + value + ' == "eText" %} selected="selected" {% endif %}>eText</option>\n' +
' <option value="No Material" {% if value == "No Material" %} selected="selected" {% endif %}>No Material</option>\n' +
'
' </select>'
}
</script>
'value' is the variable that I want to pass.
But I have tried several method:
1 . use ' + value + ': ' <option value="eText" {% if ' + value + ' == "eText" %} selected="selected" {% endif %}>eText</option>\n'
2 . use value in my js quotation directly: ' <option value="No Material" {% if value == "No Material" %} selected="selected" {% endif %}>No Material</option>\n'
all could not pass the value variable.
How could I pass 'value'?
Always use javascript template literal when handling some complex string output. In your case, it's possible to combine template literals with JS ternary operator like this :
function renderFormat(value) {
return `<select style="width: 7em" name="Material_format" id="Material_format">
<option value="" ${(value === 'empty') ? 'selected="selected"' : ""}>--Select--</option>
<option value="eText" ${(value === 'eText') ? 'selected="selected"' : ""}>eText</option>
<option value="No Material" ${(value === 'No Material') ? 'selected="selected"' : ""}>No Material</option>
</select>`;
}
Test output :
console.log(renderFormat("No Material"));
// console.log(renderFormat("eText"));
// console.log(renderFormat("empty"));
// Output
<select style="width: 7em" name="Material_format" id="Material_format">
<option value="" >--Select--</option>
<option value="eText" >eText</option>
<option value="No Material" selected="selected">No Material</option>
</select>
NB : Do not mix Js template literals and Django template tags. Just a advice.
More about javascript ternary operator, and JavaScript template literals