سؤال

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>
هل كانت مفيدة؟

المحلول

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

نصائح أخرى

The issue is that your label contains " a " (with the spaces), but you're comparing with "a" (no spaces).

If you want to ignore the spaces, you can use jQuery's $.trim(...) to trim the text off the innerText.

But as you're using jQuery, you can dramatically reduce that code:

$(document).ready(function() {
    var searchText = "a";
    var found = false;
    $("label").each(function() {
        found = $.trim($(this).text()) === searchText;
        if (found) {
            return false; // No need to keep looking
        }
    });
    $("#choose").prop("disabled", true);
});

Since you're already using jQuery, you can do what you like with much less complexity. This will work:

(function ($) {
    var searchText = "a";
    $('label').each(function(){
        if ($.trim($(this).text()) === searchText) {
            $('#choose').prop('disabled', true);
        } 
    });
})(jQuery);

You have to trim label's text. Try with:

if (aTags[i].innerText.trim() == searchText)

or without trim method:

if (aTags[i].innerText.replace(/^\s+|\s+$/g, '') == searchText)

If you want to match if a substring exists you can try with

aTags[i].innerText.indexOf(searchText) > -1

instead of

aTags[i].innerText == searchText
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top