1

This is a possible duplicate, but those answers did not work for me

I have two jQuery event handlers.

The first one is used to dynamically populating second dropdown based on the option selected in the the first dropdown.

The second one is for dynamically calculating number of words left to type in a text area.

Both these events get fired as I expected when they are used individually. When I combine these two together, dropdown population event works fine, but nothing happens in the word calculator.

  $(function(){ // document is ready

              //This is calculating no of words
              $("#description").on("keyup",function(){
                 dynamic_word_counter($(this),255);
              });
              

              //This will populate second dropdown based on first one
                  $("#branch_id").on("change",function(){
                     var val=$("#branch_id").val();  
                     $.ajax({
                        type: "GET",
                        url: "loan_request_assign.php", //same file
                        data: "branch_id=" + val, //get value of first dropdwon
                        success: function(html) {

                            $("#staff_name").html(html);//insert options to second dropdown
                            //console.log(html);
                        } 
                         
                         
                     });
                    
                    
                }); 
                
         });

There is main.js file and I inserted dynamic_word_counter function in it. Above contents have been put inside of <script> tags of the same HTML file.

For more information:

main.js file

$(function(){
    function dynamic_word_counter(element, limit) {
    //source:-http://spyrestudios.com/building-a-live-textarea-character-count- limit-with-css3-and-jquery/
    var text = $(element).val();
    var text_length = $(element).val().length;
    if (text_length > limit) {
        $(element).val(text.substr(0, limit));
        $("#message").html(0);
    } else {
        $("#message").html(limit - text_length);
    }



}
});

I am using jQuery .on, but the problem still exists. How do I rectify my issue?

P:S HTML part

<form id="branchform" action="loan_request_assign.php"  method="POST" class="form">
     <div class="formBlock"> 
                    <label for="branch_name">Branch Name<span class="required">*</span></label>
                    <select id="branch_id" name="branch_name" class="textInput">  
                     //User will select a branch name
                        <option value="">Select</option>
                        <?php
                        $branches = Branch::find_by_sql("SELECT * FROM branch");                    
                        foreach ($branches as $branch) {
                            echo "<option value='$branch->id' ";
                            if (isset($_POST["branch_name"]) && $_POST["branch_name"] == $branch->id)
                                echo "selected ";
                            echo ">$branch->branch_name</option>";
                        }
                        ?>
                    </select>
                </div> 
                
        
                
                 <div class="formBlock">
                        <label for="staff_name">Staff Name <span class="required">*</span></label> 
                        <select id="staff_name" name="staff_name" class="textInput" >
                            <option value="">Select</option>
                            
                            <!--dynamically populating staff names using ajax (based on `branch name)-->`
                        </select>
                </div>
                
                <div class="formBlock">
                    <label for="your_comments" class="label">Description</label>
                    <p class="message"><span id="message">255</span><span> characters left</span></p>
                    <textarea id="description" placeholder="Description must be less than 255 characters" name="description" class="textArea"><?php echo isset($_POST["description"])?$_POST["description"]:NULL;?></textarea>
                </div>
</form>

PHP code used in ajax

<?php
if(isset($_GET["branch_id"])){
    $branch_id=$_GET["branch_id"];
    $sql="SELECT id,staff_firstname,staff_lastname FROM staff ";
    $sql.="WHERE branch_id =$branch_id";            
    $staff_names=  Staff::find_by_sql($sql);
    if(!empty($staff_names)){
         foreach ($staff_names as $staff_name) {
        echo "<option value='$staff_name->id'>".$staff_name->staff_firstname." ".$staff_name->staff_lastname."</option";       
           
    }
    }else{
        echo "<option value=''>No Staff Found</option>";
    }   
       
    
}
?>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
gihanmu
  • 136
  • 1
  • 12
  • `$(function(){ // document is ready` you don't have a closing of it. – Jai May 10 '14 at 10:30
  • @jai - Sorry, in my original file there is one. I have forgotten it when I am pasting it here.Edited now, but it is not my problem. Tks – gihanmu May 10 '14 at 10:35
  • if you place a console.log in the dynamic_word_counter function - is the console.log fired? – Sten Muchow May 10 '14 at 10:43
  • @StenMuchow - I have individually tested both these events. Yes it works without any problem, the problem that I am facing is dynamic_ word_counter_ function attached to keyup event does not get fired due to ajax call – gihanmu May 10 '14 at 10:46
  • so u r telling me the console.log statement you placed at the top of that function is never called? – Sten Muchow May 10 '14 at 10:47
  • @StenMuchow - No I put a simple message in console.log and it gets printed. It means that keyup event gets fired, but the function is not called. is not it? – gihanmu May 10 '14 at 10:52

2 Answers2

1

Take ' dynamic_word_counter' definition out of function enclosure. So that is is accessible.
Or
Set it on 'window' object. i.e. in main.js file,

change

$(function(){
    function dynamic_word_counter(element, limit) {
    //source:-http://spyrestudios.com/building-a-live-textarea-character-count- limit-with-css3-and-jquery/
    var text = $(element).val();
    var text_length = $(element).val().length;
    if (text_length > limit) {
        $(element).val(text.substr(0, limit));
        $("#message").html(0);
    } else {
        $("#message").html(limit - text_length);
    }



}
});

to

window.dynamic_word_counter = function (element,limit) {
//source:-http://spyrestudios.com/building-a-live-textarea-character-count- limit-with-css3-and-jquery/
    var text = $(element).val();
    var text_length = $(element).val().length;
    if (text_length > limit) {
        $(element).val(text.substr(0, limit));
        $("#message").html(0);
    } else {
        $("#message").html(limit - text_length);
    }
};
IsmailS
  • 10,797
  • 21
  • 82
  • 134
  • I really did not get you. It should get fired on keyup event – gihanmu May 10 '14 at 10:58
  • 2
    What he is saying is that the if the function lives inside another doc.ready function then its in accessible as it lives inside that closure. So if you place it on the nasty dirty disgusting window object then it will be accessible. – Sten Muchow May 10 '14 at 11:04
1

As this function is only being fired from an event it doesn't need to be placed inside a document.ready function. You can place it on the (yuck) global context and then the document.ready that is fired and places the event listeners on the scope will then have access to the function - its irrelevant to place a function that will never get fired in a document.ready function.

  function dynamic_word_counter(element, limit) {
    //source:-http://spyrestudios.com/building-a-live-textarea-character-count- limit-with-css3-and-jquery/
    var text = $(element).val();
    var text_length = $(element).val().length;
    if (text_length > limit) {
        $(element).val(text.substr(0, limit));
        $("#message").html(0);
    } else {
        $("#message").html(limit - text_length);
    }
  } 
Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
  • yes I removed jQuery document.ready from dynamic_word_counter function and now it exists in the global context. But still my words are not calculated. If I start typing on the text area first without selecting dropdown values it works, but in my html file dropdowns come before text areas – gihanmu May 10 '14 at 11:16
  • can you add the html structure as well, so we can see what is happening? – Sten Muchow May 10 '14 at 11:32
  • 1
    Also I am not sure what part of the DOM you ajax is replacing, but when the html is replaced in the success method of the ajax - you could try to rebind the event handler that the for the key down event. – Sten Muchow May 10 '14 at 11:40
  • html contents in #staff_id get replaced by ajax response. – gihanmu May 10 '14 at 11:44
  • 1
    i made a plunkr for it and it seems to work find for me... i removed the php junk to get something that is testable. http://plnkr.co/edit/ZrbOMNz1Olb3t0IgqxH1?p=preview – Sten Muchow May 10 '14 at 11:50
  • Yes your plunkr is working perfectly, but something is wrong with my code. But I know the logic is correct. I will go through all related codes update you. Thanks man for your time :) – gihanmu May 10 '14 at 12:03
  • the only thing i did was copy paste everything from your code and remove the php - so check out the html that the ajax returns. No worries - appreciate a good JS riddle... – Sten Muchow May 10 '14 at 12:09
  • sorry for the delay. Up voted and accepted. Highly appreciate your commitment. – gihanmu May 10 '14 at 12:14
  • Good to hear what was the problem? – Sten Muchow May 10 '14 at 14:52