Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to get the text attribute of a checkbox

I'm adding a check box to a page using the following statement;

<script language="C#" runat="server">
    protected void Page_Load ( object src, EventArgs e ) 
    {
        if (!IsPostBack)
        {
         CheckBox XChkBox = new CheckBox(); //instance of System.Web.UI.WebControls.CheckBox
         XChkBox.ID = "someId"
         XChkBox.Text = "someText"
         somePlaceHolder.Controls.Add(XChkBox);
        }
    }
</script>

I need to get the Text attribute of that check box on click. I tried $(this).attr('Text'); inside $('input[type=checkbox]').click(function(){}); but it returns undefined.

Where am I going wrong? Please suggest.

cheers

like image 464
Arnkrishn Avatar asked Dec 31 '09 03:12

Arnkrishn


People also ask

Does checkbox have value attribute?

Note: Unlike other input controls, a checkbox's value is only included in the submitted data if the checkbox is currently checked . If it is, then the value of the checkbox's value attribute is reported as the input's value.

How can checked checkbox in jQuery?

To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);

What is the value of checkbox in JavaScript?

If a checkbox is marked or checked, it indicates to true; this means that the user has selected the value. If a checkbox is unmarked or not checked, it indicated to false; this means that the user has not selected the value.


2 Answers

ASP .NET renders the Text property of the ASP:CheckBox server control, as a label element just after the <input type="checkbox" /> on the generated markup at the client, it looks something like this:

<input id="someId" type="checkbox" name="someId" />
<label for="someId"> someText </label>

You can get the text of the label by:

$("input:checkbox").click(function() {
  var $label = $(this).next('label');
  alert($label.text());
});
like image 156
Christian C. Salvadó Avatar answered Nov 02 '22 16:11

Christian C. Salvadó


The CheckBox control renders the Text inside a <label> element. The text is not part of the HTML checkbox. If you want to get the text from jQuery, you have to get it from the <label>.

Also, the <label> it generates doesn't actually have an ID. If your CheckBox is named checkBox1, then the HTML it outputs will be <label for="CheckBox1">, and the text is inside that element. I believe the correct jQuery syntax would be:

$('label[for="checkBox1"]').html()
like image 35
Aaronaught Avatar answered Nov 02 '22 15:11

Aaronaught