Reputation: 3784
I am dynamically adding a select box inside a div element with the following code:
$('#worker').html('<g:select class = "dropdown" name="worker" from="${workers}" optionKey="id" optionValue="name" />');
The problem with this code is that when the g:select
tag expands, it will generate the code as follows:
$('#worker').html('<select onchange="handleWorkerChange(this)" class="dropdown" name="worker" id="worker" >
<option value="2" >Worker1</option>
<option value="4" >Worker1</option>
<option value="18" >Worker1</option>
<option value="19" >Worker1</option>
</select>');
As you can see above, when expanding, the option tags are in new lines so this will cause syntax error in JavaScript. Is there a way so that the select gsp
tag will expand to a single line string so that the select box can be embedded dynamically in a div?
Upvotes: 0
Views: 112
Reputation: 1880
g:select
is also available just as a method within the GSP:
${select(from:aList,value:aValue)}
Taking advantage of this and the fact that then we are just dealing with a text (org.codehaus.groovy.grails.web.util.StreamCharBuffer
), we can remove the new line characters:
$('#worker').html('${ select(
class: 'dropdown',
from: workers,
optionKey='id',
optionValue: 'name',
name: 'worker'
).replace(System.getProperty("line.separator"), '') }');
This should result in the entire select be placed on a single line.
Initially, I wasn't sure myself exactly what was causing the select
being placed over several lines, so I went straight to the source: FormTagLib.
Snippet from FormTagLib:
writer << "<select "
// process remaining attributes
outputAttributes(attrs, writer, true)
writer << '>'
writer.println()
As you can see, it's just a simple println
method call:
Terminates the current line by writing the line separator string. The line separator string is defined by the system property line.separator, and is not necessarily a single newline character ('\n').
This is why it's important to use System.getProperty("line.separator")
.
Upvotes: 1
Reputation:
you cannot append
or html
grails code like that.
you muse use html code.
var youComboboxCode = "<select><option>aaaa</option><option>bbb</option></select>";
$('#worker').html(youComboboxCode);
i will share my code
var htmlcodeA = '';
if(data)
{
for (var i = 0; i < data.length; i++) {
htmlcodeA = htmlcodeA + "<option value="+data[i].id+">"+data[i].purchaseNo+"</option>";
}
}
$('#home').find('option').remove();
$('#home').html(htmlcodeA ).change();
Upvotes: 0