0

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?

4
  • 1
    Why not create a snippet with actual elements named the way you expect? Then we can test if your logic works Commented Aug 31, 2016 at 17:12
  • I'll edit code so you should test it with data. Commented Aug 31, 2016 at 17:13
  • Also, can you show us what your HTML elements look like? Commented Aug 31, 2016 at 17:14
  • I updated my code and added html. Commented Aug 31, 2016 at 17:17

1 Answer 1

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" />

Sign up to request clarification or add additional context in comments.

1 Comment

If I have input element, how should I select parent div - isn't it in this way -> $('#' + document_name).parents('div').append('<label class="error file_error">test</label>');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.