开发者

Get Text of checkbox with Jquery

开发者 https://www.devze.com 2023-02-21 04:25 出处:网络
<input type=\"checkbox\" 开发者_JAVA技巧name=\"PrePayment\">Pre-Payment<br /> How would I get the text \"Pre-Payment\" from this using Jquery?
<input type="checkbox" 开发者_JAVA技巧name="PrePayment">Pre-Payment<br />

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

Thanks!


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


Maybe:

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

Try it here.


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


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


I had a similar problem to this - another way you could make this work (with HTML5) is to use data attributes.

As an example, you'd set a data attribute as follows:

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

You could then read this data attribute by using the following jQuery:

$(input).data('text');

The benefit of doing it this way is that you can have a seperate value parameter if required.

0

精彩评论

暂无评论...
验证码 换一张
取 消