dharmendra chaudhary dharmendra chaudhary - 2 years ago 85
Javascript Question

How to get same label or previous td inner tag class

I have the following html code like

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

When I change the file I need to add the
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');
} else {
alert('file not selected');

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download