Selecting element with variable that has been made using substring

时间:2016-08-31 17:08:21

标签: jquery substring selector

I have an array and I want to remove last symbol that is '0'. That's why I use substring to remove it and I'm trying to use this variable as a jQuery selector. But it doesn't select the element when I've used substring.

My code is:

  
var key = 'director_front_passport0';
   
var document_name = key.substring(0,key.length - 1);
console.log(document_name); //returns director_front_passport

$('#' + document_name).append('<label class="error file_error">test</label>');
//I want to select element with id=director_front_passport

      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" name="director_front_passport" id="director_front_passport" />

How should I select elements with definite id if I've used substring?

1 个答案:

答案 0 :(得分:1)

Your code works if you append to a div. You cannot append to an input field

Try after :

var response = {
  errors: {
    'director_front_passport0': "error1",
    'director_back_passport0': "error2",
    'director_address_document0': "error3"
  }
}

$.each(response.errors, function(key, value) {

  var files_array = ['director_front_passport0', 
                     'director_back_passport0', 
                     'director_address_document0'];
  if ($.inArray(key, files_array) !== -1) {

    var document_name = key.substring(0, key.length - 1);
    console.log(document_name); //returns for example director_front_passport

    $('#' + document_name).after('<label class="error file_error">test</label>');
    //I want to select element with id=director_front_passport

  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="file" id="director_front_passport" /><hr/>
<input type="file" id="director_back_passport" /><hr/>
<input type="file" id="director_address_document" />