简体   繁体   中英

get changing value from readonly textarea by javascript

I have a readonly textarea which its value keep changing. Now I want the page keeps updating its value and return the result if it matches with the provided string or not. Here is what I tried but it's not working

var string = "This is my house";

    $('#textarea').bind('input', function() { 

    if ($(this).val() === string.trim()) {
        $('#message').html('matching').css('color', 'green');       
    } else $('#message').html('not matching').css('color', 'red');
});

I think you can't listen to the input event as the textarea is readonly , what you can do though is trigger the input - or any other event - using .trigger() in same code that changes the text content of the textarea

JS Fiddle

 var string = "This is my house", ta = $('#textarea'), msg = $('#message'), newContent = 'just dummy text'; // replacement text, change it to see the result ta.on('input', function() { if ($(this).val() === string.trim()) { msg.html('matching').css('color', 'green'); } else { msg.html('not matching').css('color', 'red'); } }); $('#btn').on('click', function() { ta.text(newContent).trigger('input'); // trigger input event as text content is changed }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <button id="btn">Change it</button><br> <textarea readonly name="" id="textarea" cols="30" rows="5">This is my house</textarea> <hr><div id="message"></div> 

You could do something like this

 var string = 'This is my house'; var array = ['Lorem ipsum dolor sit amet', 'consectetur adipisicing elit', 'This is my house', 'quae aperiam solut']; var counter = 0; $('textarea').click(function() { if(array[counter] == string.trim()) { $('.result').text('Matching').css('color', 'green'); } else { $('.result').text('Not matching').css('color', 'red'); } $('textarea').text(array[counter]); counter = (counter + 1) % array.length; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea readonly placeholder="Click Me" class="textArea"></textarea> <div class="result"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM