0

I searched a lot trying do solve this problem but I just found specific solutions, I wonder if there's a way to select the previous input text independent of the HTML structure.

Don't know if that is possible but would be nice to have a "generic" solution for this problem.

Is that is not possible, this is my case:

<ul>
<div class="inputMusics">
    <div class="music">
        <li>                
            <label>Artist:</label>
            <input class="artists" type="text" name="artistMusic[]" value="artist"/>
        </li>
        <li> 
            <label>Title:</label>
            <input class="title" type="text" name="titleMusic[]" value="title"/>
        </li>       
        <li> 
            <label>Album:</label>
            <input class="albuns" type="text" name="albumMusic[]" value="album"/>
        </li>           
    </div>
</div>  
<button id="addMusic" type="button"> + Add musics</button>   
<button id="removeMusic" type="button"> - Remove music</button>

$(".title").focus(function(){
// select the previous input    
}

Thanks!

carmolim
  • 137
  • 2
  • 11
  • But there is no element with the class of "title" in your HTML at the first place. And what exactly do yo mean by "previous input element"? What is the reference (i.e., previous relative to what?) And by selecting, do you mean focusing on the previous element, selecting the text in the previous element, a combination thereof...? – Terry Apr 30 '13 at 00:22
  • @Terry `titulo` is the equivalent of `title` in spanish, it's probably a simple oversight. – Ohgodwhy Apr 30 '13 at 00:29
  • sorry about that, @Ohgodwhy is correct... – carmolim Apr 30 '13 at 01:43

2 Answers2

0

Perhaps something like this jsFiddle? Based on this SO thread.

The jQuery

$('.title').focus(function() {
  alert($(':input:eq(' + ($(this).index() - 1) + ')').val());
});
Community
  • 1
  • 1
incutonez
  • 3,241
  • 9
  • 43
  • 92
  • strange, the alert is returning "1", I don't know why, the selection is correct.. I tested with 'console.log($(':input:eq(' + ($(this).index() - 1) + ')').prop('tagName'));' and it returned INPUT but, I don't know from where is this "1" coming from. – carmolim Apr 30 '13 at 01:36
  • Weird. FF is reporting "artist" when I click the title input box... what browser are you using? – incutonez Apr 30 '13 at 10:58
0
$('.titulo').focus(function(){
    $(this).closest('li').prev().find('input').val();
});

Where, the closest li would be the parent li, the previous element of the closest li is the previous li, and then we simply find the input and grab the val.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110