I am trying to count the number of links in a textarea so I can limit the user to no more than three links. The code below is what I have so far, but it's not working. I am thinking the html is encoded and that is affecting it somehow ...or maybe not. If so, can I decode it? Any ideas? Thanks so much.
$(document).ready(function() {
    $('#box-text').keyup(function() {
            var links = $('#box-text a');
            var total_links=0;
 开发者_运维知识库           for(var i = 0; i < links.length; i++) {
                total_links++;
            }
            alert("links =  " + total_links);
    });
});
I'd prefer to let the DOM API do the work here, rather than a regex or manual string parsing.
$('#box-text').bind('keyup paste change', function() {
    var linksLength = $('<div />').html($(this).val()).find('a').length;
    if (linksLength > 3) {
        // Too many links, warn user!
    }
});
jsFiddle.
Be sure to validate this on the server too.
You will have to match the value of the textarea with a Regular Expression like this:
$(document).ready(function() {
    $('#box-text').keyup(function() {
            matches = $('#box-text').val().match(/<a[^>]*>(.*?)<\/a>/gi);
            total_links = matches.length;
            alert("links =  " + total_links);
    });
});
jsFiddle
If is #box-text is a textarea, you cannot get links from $('#box-text a').
You can do something like,
$(document).ready(function() {
    $('#box-text').keyup(function() {
            var text = $(this).val();
            var dummy = $('<div>'+text+'</div>');
            var total_links = $('a', dummy).length;
            alert("links =  " + total_links);
    });
});
Hope this helps. Happy Coding.
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论