views:

44

answers:

4

Hopefully this one is not too hard to understand but I just want the label values to be inputs into a javascript function. Might be better to explain with code:

ASP.NET Label code:

<asp:Label ID="LabelCL" runat="server" Text="A single int filled in by DB"></asp:Label>

Page Source:

<span id="ctl00_cpMainContent_LabelCL">7</span>

What I would like to achieve but am not sure how to do:

<span id="ctl00_cpMainContent_LabelCL">     <script type="text/javascript">functionX(7)</script>    </span> 

So basically just wrap the output int in the following:

<script type="text/javascript">functionX( VALUE FROM LABEL TEXT)</script>

within the
<span></span>

+1  A: 

Try this:

<asp:Label ID="LabelCL" runat="server" Text="A single int"></asp:Label>
<button onclick="displayContent(<%= LabelCL.ClientID %>)">click me</button>
<script>
    function displayContent(obj) {
        alert(obj.innerText);
    }
</script>
Rubens Farias
+3  A: 

Try this

<asp:Label ID="LabelCL" runat="server" />

<script type="text/javascript">
    var value = document.getElementById("<%= LabelCL.ClientID %>").innerHTML;
    functionX(value);
</script>

If it is called just after render you can simply use LabelCL.Text, if you need the value after and if it can be edited you can do as the exemple above.

With jQuery you can use

$("[id$=LabelCL]")

to retrieve the element.

BrunoLM
Where does the ".ClientID" come from?
Greg McNulty
It is a property of the control, it is the ID which will be rendered on the page, to the final element (html element). `<%= LabelCL.ClientID %>` means get the control `LabelCL` and return it's ClientID
BrunoLM
+2  A: 
var span = document.getElementById('ctl00_cpMainContent_LabelCL'),
    text = span.firstChild;

functionX(text.textContent);

Working Demo

or if defined in the Page use script tags to render out the client id for the span using

<%= LabelCL.ClientID %>
Russ Cam
wow, awesome demo!
Greg McNulty
+1  A: 

You almost had it:

<asp:Label runat="server" Text="<script type='text/javascript'>document.write(functionX(7));</script>"/>
GoodEnough