Use jQuery to find the label for a selected contro

2019-03-14 10:04发布

问题:

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 :)

回答1:

Use the attribute selector [] like [for='+ this.id +'], where this.id is the ID of the currently focused 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" >



回答2:

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();


回答3:

$("#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.



回答4:

try this:

$('input[type=text]').focus(function(){
     alert($('label[for=' + $(this).attr('id') + ']').html());
});


回答5:

$('#ctl00_WebFormBody_txtPriceAdjustment').click(function() {
  alert($('#ctl00_WebFormBody_lblProductMarkup').text());
});


回答6:

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">