Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to find the label for a selected control or textbox

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

like image 374
Darren Avatar asked Sep 17 '11 13:09

Darren


People also ask

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.

How can show textbox value in jQuery?

To get the textbox value, you can use the jQuery val() function. For example, $('input:textbox'). val() – Get textbox value.

Which jQuery function is used to get the text content of an element?

jQuery text() Method The text() method sets or returns the text content of the selected elements. When this method is used to return content, it returns the text content of all matched elements (HTML markup will be removed).


2 Answers

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" >
like image 182
Roko C. Buljan Avatar answered Nov 13 '22 21:11

Roko C. Buljan


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(); 
like image 23
Tom Avatar answered Nov 13 '22 19:11

Tom