1

I tried all of the alternative examples I could find and couldn't get this to work. I may have it implemented incorrectly. Any help is greatly appreciated.

My issue:

I have a function that is meant to slideDown an alert if specific values in the are in the textarea.

This function works if the user types in the textarea, but the values are usually passed in from another page. How can I make it run without requiring that they interact with the text area?

Here's my example on JSFiddle: Example

And here is the HTML/JS code for easy reading:

HTML

<!doctype html>
 <html>
<head>
    <title>Alert Test</title>
</head>
<body>
    <div class="controls">
        <textarea name="q" class="span12"  id="textarea" rows="5">one:</textarea>
    </div>
    Test alert:
    <div class="alert alert-error" id="alert" name="alert" style="display: none;">
        This is a test alert.
        <a href="#" class="close" data-dismiss="alert">&times;</a>
    </div>
</body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="textAreaReader.js"></script>
</html>

JS:

$(document).ready(function(){
$('#textarea').on('change keyup paste', function() {
var lines = $('#textarea').val();
var fields = ["one", "two", "three"];
var leng;
for (var i=0; i < fields.length; i++) {
  if (lines.indexOf(fields[i] + ':') !== -1){
    leng = 1;
  }
}
if (leng == 1){
    $("#alert").slideDown("fast"); //Slide Down Effect
  }else{
     $("#alert").slideUp("fast");  //Slide Up Effect  
  }
});
});
2
  • What do you mean by the values in the textarea are "passed in from another page"? Do you have a script that updates the textarea? Commented May 14, 2015 at 14:18
  • The site I have is an internal company search site. We give the users the option to go to a separate page an save their searches or extract some content based on the searches in specific formats. Since they ran the search on the initial page, the one I need to make the JS run gets the search passed in. Hope this makes sense. Commented May 14, 2015 at 14:21

1 Answer 1

5

Assigning the function to a variable lets you pass it to the textarea handler and run it on page load.

$(document).ready(function () {
    var slide = function () {
        …
    };
    $('#textarea').on('change keyup paste', slide);
    setTimeout(slide, 500);
});

Sample.

Sign up to request clarification or add additional context in comments.

3 Comments

Beat me to it lol. I would be careful with timeouts, though, because they can slow your page down.
@GreeKatrina Perhaps you're thinking of setInterval. setTimeout in this instance will have no adverse effects
Thank you! I knew I had something wrong. Much appreciated and answer accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.