Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Text of checkbox with Jquery

Tags:

html

jquery

<input type="checkbox" name="PrePayment">Pre-Payment<br />

How would I get the text "Pre-Payment" from this using Jquery?

Thanks!

like image 937
slandau Avatar asked Apr 01 '11 20:04

slandau


People also ask

How to get text of checkbox using jQuery?

var text = $('input[type="checkbox"]'). text(); alert(text);

How check if checkbox is checked 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);


4 Answers

I'd recommend putting the text inside a <label> tag so that you could click on it (and so that screen readers and such could make sense of your form):

<input type="checkbox" name="PrePayment" id="pre-payment">
<label for="pre-payment">Pre-Payment</label>
<br />

Then, the whole thing becomes easy:

var text    = $('label[for=pre-payment]').text();
var or_this = $('#pre-payment').next('label').text();

I'd prefer the first option, label[for=...], as it is less fragile than the second

like image 70
mu is too short Avatar answered Oct 23 '22 03:10

mu is too short


Maybe:

$("input[name='PrePayment']")[0].nextSibling.nodeValue;

Try it here.

like image 30
karim79 Avatar answered Oct 23 '22 02:10

karim79


You should probably have a value attribute in the checkbox.

<input type="checkbox" name="PrePayment" value="Pre-Payment">Pre-Payment<br />

Then you can simply use the attr command:

$(input).attr('value');
like image 37
downed Avatar answered Oct 23 '22 02:10

downed


Check the below example and you get the script how to get label of checkbox in jQuery

<html>
 <body>
     <ul>
         <li>
             <input type="checkbox" name="mouse" value="1" id="mouse"  /><label for="mouse">Mouse</label>
            </li>
            <li>
             <input type="checkbox" name="keyboard" value="1" id="keyboard"  /><label for="mouse">Keyboard</label>
            </li>
            <li>
             <input type="checkbox" name="monitor" value="1" id="monitor"  /><label for="mouse">Monitor</label>
            </li>
        </ul>
    </body>
</html>

<script type="text/javascript">
 var label = jQuery('label[for=' + jQuery(this).attr('id') + ']').html();
 alert(label);
</script> 

Code taken from this link : http://chandreshrana.blogspot.in/2015/09/how-to-get-checkbox-label-text-jquery.html

like image 2
Chandresh Avatar answered Oct 23 '22 03:10

Chandresh