kabforks
kabforks

Reputation: 121

Finding input elements with jquery

I'm trying to show the difference in days between two input fields that contain dates. I am pretty much unable to alter the HTML so I have to do this with Javascript. The HTML is pretty ugly. I can only use jQuery 1.3.2.

HTML:

<div id="longUnreadableUnidentifiableId">
  <div class="dynamic">
    <div class="row">
      <span class="column">
        <input id="horribleHorribleLongIdTxtFrom" type="text">11/02/2002</input>
      </span>
      <span class="colum">
        <input id="horribleHorribleLongIdTxtUntil" type="text">16/12/2010</input>
      </span>
      <div class="diff"> [diff] </div>
    </div>
  </div>

<div id="longUnreadableUnidentifiableId2">
  <div class="dynamic">
    <div class="row">
      <span class="column">
        <input id="horribleHorribleLongIdTxtFrom" type="text">03/03/2003</input>
      </span>
      <span class="colum">
        <input id="horribleHorribleLongIdTxtUntil" type="text">16/12/2010</input>
      </span>
      <div class="diff"> [diff] </div>
    </div>
  </div>

When any one of the dates on a certain line change, the difference between them should show. I'm using moment.js for the date diff.

The following javascript tries to find the associated input field and alert the difference between them. However, I am having trouble finding the second input field (var until).

Javascript:

$('input[id*="txtFrom"]').live('change', function() { 
    var from = $(this);
    var until = from.parent(".row").find('input[id*="txtUntil"]');

    a = moment(from.val());
    b = moment(until.val());

    alert(b.diff(a, 'days'));
});

Does someone have a solution to this problem? Perhaps something more elegant?

Upvotes: 1

Views: 144

Answers (2)

Nono
Nono

Reputation: 7302

Some suggestions:

  1. Correct your html syntax, use

    <input id="horribleHorribleLongIdTxtFrom" type="text" value="11/02/2002"></input>
    

    instead of

    <input id="horribleHorribleLongIdTxtFrom" type="text">11/02/2002</input>
    
  2. your element id horribleHorribleLongIdTxtFrom coming twice in same page, you are breaking the html rule.

Upvotes: 1

cheesetor
cheesetor

Reputation: 91

Try using parents instead of parent. parent just checks the immediate parent, whereas parents checks all of them.

Upvotes: 3

Related Questions