user2775888
user2775888

Reputation: 39

better options for writing this jquery

I have a html file like the following one,

<i class=‘icon-calendar icon-large' data-placement='top' data-toggle='popover' type='button'>
  <div class='head hide'>Calendar</div>
    <div class='content hide'>
      <form action="#" data-remote="true" id="calendar_form" method="post">
        <div style="...">
          <input type="hidden" />
          <input type="hidden" />
        </div> 
            <table border='0px'>
             <tbody>
               <tr>
                <td colspan='2'>
                  <button class='btn btn-default btn-block' id='submit' type='submit'>Convert</button>
                </td>
             </tbody>
            </table>
         </form>
        </div>
       </i>

<li class="..." id="calendar_example"><label class=" label" for="...">...</label>
  <input class="..." id="calendar_example_1" name="[calendar_example][0][calendar_example_1][0]" type="text" />

I'm trying to use Jquery to write the function as when click button where id is submit, i can pass value from the popover to the field with id calendar_example_1, my code, the working one to find the field, is

 $(function(){
   $('body').on('click','#submit', function(){
    var calendar_name = $(this).parent().parent().parent().parent().parent().parent().siblings().find('#calendar_example_1').attr('name');
    return false;
  });
 });

by using .parent() multiple times, i don't think this is a good way to write this code. As i'm new to jquery, i can't find any better solution yet that works the way i want. Anyone can give me some suggestion?

EDIT: the outside form is nested.

Upvotes: 0

Views: 39

Answers (2)

piry
piry

Reputation: 148

You can use

$('#submit').click(function(){
var calendar_name = $('#calendar_example_1').attr('name');
});

Upvotes: 2

jmore009
jmore009

Reputation: 12923

you can just do this instead:

var calendar_name = $(this).closest("i.icon-calendar").siblings("li#calendar_example").find('#calendar_example_1').attr('name');

Upvotes: 2

Related Questions