2

I have is a hidden div. When a link is clicked, the div should be toggle with an input field and a dropdown select. How do I make this input field autofocus as soon as the div slides down?

This is my HTML for hidden DIV:

<div class="new-category-box">
    <div class="form-group">
        <input type="text" class="form-control" id="new_category" name="new_category" autofocus>
    </div>
    <div class="form-group">
        <select class="form-control" name="parentCategoryList">
            <option>-- Parent Category --</option>
            <option value="">Lorem ipsum</option>
            <option value="">Lorem ipsdffum</option>
        </select>   
    </div>      
    <div class="form-group">
        <button type="submit" class="btn btn-default">Add New Category</button>
    </div>  
</div>  

I went through this question. But now this DIV not toggle.

This is my Jquery:

$( "a.add_new_category" ).click(function() {
    $( ".new-category-box" ).slideToggle(function(){
            $("#new_category").focus();
        });
    );
});

Can anybody tell me what is wrong this code?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user3733831
  • 2,886
  • 9
  • 36
  • 68

2 Answers2

1

You have a few errors, they have been corrected:

$( "a.add_new_category" ).click(function() {
  $( ".new-category-box" ).slideToggle(function() {
    $("#new_category").focus();
  });
  // ); - extra stuff need to be removed!
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="new-category-box">
  <div class="form-group">
    <input type="text" class="form-control" id="new_category" name="new_category" autofocus>
  </div>
  <div class="form-group">
    <select class="form-control" name="parentCategoryList">
      <option>-- Parent Category --</option>
      <option value="">Lorem ipsum</option>
      <option value="">Lorem ipsdffum</option>
    </select>   
  </div>      
  <div class="form-group">
    <button type="submit" class="btn btn-default">Add New Category</button>
  </div>  
</div>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

You can use this:

<input type="text" name="fname" autofocus>
Himanshu gupta
  • 650
  • 5
  • 10
  • His question is precisely that condition: he wants the field to autofocus, but *only* when its parent div becomes visible with a toggle. So the `autofocus` doesn't help, because even when the div is hidden, the form behind the scenes is triggering autofocus, which causes weird behavior in phones etc (keyboard pops up, but there's no place to enter). – Khom Nazid Aug 28 '19 at 14:02