I want a bit of jQuery code that will allow me to find the label for a control when I click on the textbox... so in my HTML I have this:
<label id="ctl00_WebFormBody_lblProductMarkup" for="ctl00_WebFormBody_txtPriceAdjustment">This Is My Label Value</label>
<input type="text" style="width:29px;" onclick="alert('label value here');" title="Here is a title" id="ctl00_WebFormBody_txtPriceAdjustment" maxlength="3" name="ctl00$WebFormBody$txtPriceAdjustment">
So, when I click on my textbox, I want (for example) to do an alert... with the text that is within my label - so in this case it would alert "This is my label value"
Hope that makes sense :)
Use the attribute selector []
like [for='+ this.id +']
, where this.id
is the ID of the currently focus
ed label
$('input').on("focus", function() {
var labelText = $('label[for='+ this.id +']').text();
console.log( labelText );
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="inp">This Is My Label Value</label>
<input id="inp" type="text" >
In a HTML code like this one:
<label for="input-email">Email</label>
<input type="text" name="input-email" value="" />
You can find the label content like this:
$('label[for="input-email"]').html();
$("#ctl00_WebFormBody_txtPriceAdjustment").bind("click",function(){
alert($("label [for=" + this.id + "]").html());
});
or possibly
alert($(this).closest("label").html());
depending on your markup you may just be able to select the next or previous siblings too.
try this:
$('input[type=text]').focus(function(){
alert($('label[for=' + $(this).attr('id') + ']').html());
});
$('#ctl00_WebFormBody_txtPriceAdjustment').click(function() {
alert($('#ctl00_WebFormBody_lblProductMarkup').text());
});
To do it with javascript
<script type="text/javascript">
function displayMessage()
{
alert(document.getElementById("ctl00_WebFormBody_lblProductMarkup").innerHTML);
}
</script>
<label id="ctl00_WebFormBody_lblProductMarkup" for="ctl00_WebFormBody_txtPriceAdjustment">This Is My Label Value</label>
<input type="text" style="width:29px;" onclick="displayMessage()" title="Here is a title" id="ctl00_WebFormBody_txtPriceAdjustment" maxlength="3" name="ctl00$WebFormBody$txtPriceAdjustment">