Home Ask Login Register

Developers Planet

Your answer is one click away!

user2986673 February 2016

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

Answers


Mi-Creativity February 2016

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>


Nenad Vracar February 2016

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>

Post Status

Asked in February 2016
Viewed 3,767 times
Voted 8
Answered 2 times

Search




Leave an answer


Quote of the day: live life