dev
dev

Reputation: 496

How to get same label or previous td inner tag class

I have the following html code like

<td>
    <input type='text' class='input_text' name='subject_text_".$i."[]' style ='height: 25px;'/>
</td> 
<td>
    <input type='file' id='file' class='input_file' name='subject_".$i."[]'/>
</td>

When I change the file I need to add the required property to the input text. I tried but I've not achieved it. I used the below code:

function input_file(){
    var file_name = $(this).val();
    if (file_name !='') {
        alert('file is selected');
        var class_name = $(this).attr('class');
        var value = $('.' + class_name).prev('td input.class');
        $('.value').prop('required',true);
    } else {
        alert('file not selected');
    }
}

$(document).on('change', '.input_file', $(this), input_file);

Upvotes: 2

Views: 170

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337656

The first issue is that the syntax of your delegate event handler is incorrect; there should be no $(this) in that call. Secondly the DOM traversal you're using isn't quite right. The td is a sibling of a parent to the file input, so prev() alone won't work. Finally the logic you use can be shortened just by setting the property to whether or not a file is selected. Try this:

function input_file() {
    $(this).closest('td').prev('td').find('input').prop('required', $(this).val() != '');
}

$(document).on('change', '.input_file', input_file);

Working example

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

find selector will not work inside prev selector argument. Here is what you need to do:

1) You need to first traverse to parent td. by using .closest('td') or .parent()

2) then to its previous sibling td . using .prev()

3) and then find required input element in it. using .find('input.class'):

function input_file(){
 var file_name =$(this).val();
 var inputclass =$(this)closest('td').prev('td').find(' input.class');
 if(file_name !=''){
      alert('file is selected');
      // code for file selected condition
      inputclass.prop('required',true);
  }else{
      alert('file not selected');
      // code for file not selected condition
      inputclass.prop('required',false);
  }
 }

Upvotes: 1

Related Questions