0

I am trying to pass a variable inside a JavaScript function. The problem I'm failing to figure out how to escape string to send that variable inside a double quote. There are tons of answers on this but I couldn't use them correctly.

for (var k = 0; k < districts[division].length; k++) {
    $('#district_list').append('<li class="byebooklist"><a href="javascript:getUniversity(' + districts[division][k] + ');">' + districts[division][k] + '</a></li>');
}

How to pass the parameter to the getUniversity() function inside a double quote?

2 Answers 2

4

Just try with escaped quotes:

$('#district_list').append(
  '<li class="byebooklist"><a href="javascript:getUniversity(\''+districts[division][k]+'\');">'+districts[division][k]+'</a></li>'
);
//                                                           ^^                          ^^ 
Sign up to request clarification or add additional context in comments.

Comments

3

To fix this you need to wrap the value in the function argument in quotes, but you'll need to escape them, using \':

for (var k = 0; k < districts[division].length; k++) {
  $('#district_list').append('<li class="byebooklist"><a href="javascript:getUniversity(\'' + districts[division][k] + '\');">' + districts[division][k] + '</a></li>');
}

However, you can both avoid the problem and improve the logic by not putting any JS in the href at all and instead using an unobtrusive event handler. As you've tagged the question with jQuery, here's how you can do that:

var html = districts[division].map(function(div) {
  return '<li class="byebooklist"><a href="#" data-division="' + div + '">' + div + '</a></li>';
}).join('');
$('#district_list').append(html);

$(document).on('click', '.byebooklist a', function(e) {
  e.preventDefault();
  getUniversity($(this).data('division'));
});

Comments

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.