Search code examples
javascriptinnertext

I want to disable the button if specific text has been found in any label


I want to disable the button if specific text has been found in any label. The following code doesn't run because aTags[i].innerText is not equal to searchText all the time which is wrong because the label has inner text = "a" and the searchText variable have "a" as text - I need it to run in IE

<html>
    <script language="javascript">
        $(document).ready(function () {
            var aTags = document.getElementsByTagName("label");
            var searchText = "a";
            var found;

            for (var i = 0; i < aTags.length; i++) {
                if (aTags[i].innerText == searchText) {
                    document.getElementById('choose').disabled=true;
                    break;
                }
                else
                {
                    alert("failed")
                }  
            }
        });
    </script>

    <label> a </label> <br/>
    <label> b </label> <br/>
    <label> c </label> <br/>

    <input type='button' value='choose' id='choose' />    
</html>

Solution

  • Seems like there should be easier ways to do that with jQuery

    $(function () {
        var searchText = "a";
    
        $('#choose').prop('disabled', function() {
            return $('label').filter(function(_,el) {
                return $.trim( $(el).text() ) === searchText;
            }).length > 0;
        });
    });
    

    FIDDLE