1

We have a table with data. My goal is to pass an argument from parsed JSON value to another javascript function - named newStory(value['stories']) from onclick method.

Tried a lot of different methods with no success..

json[key]['date'] = '<span class="' + styleBlock + '">' + value['date'] + '</span>'; 
json[key]['category'] = '<span class="' + styleCatDefault + '">' + value['category'] + '</span>';
json[key]['subcategory'] = '<span class="' + styleSubcatDefault + '">' + value['subcategory'] + '</span>';       
json[key]['stories'] = '<span><a href="#" onclick="newStory(value['stories'])">' + value['stories'] + '</a></span>';

Any help appreciated!

Edit:

Line with many quotes finally worked:

json[key]['stories'] = '<span><a href="#" onclick="newStory(' + "'" +value['stories'] + "'" + ')">' + value['stories'] + '</a></span>';
6
  • 1
    You just need to concatenate it's value in to the string properly, as you are in other places in the code sample. Better still, forget the inline click handler and use an unobtrusive, delegated one instead. Commented Feb 11, 2020 at 16:11
  • You could also escape the single quotes. Commented Feb 11, 2020 at 16:12
  • No, I can't. Undefined otherwise Commented Feb 11, 2020 at 16:22
  • I would suggest storing that value (or a reference to it) within the element. As the click event gets first at a later time and most likely value is no longer set, you get the undefined error. Commented Feb 11, 2020 at 23:42
  • To do this, I would try something like <a href="#" data-value="' + value['stories'] + '" onclick="newStory(this.attributes[\'data-value\'].value)" >' + value['stories'] + '</a>' Commented Feb 11, 2020 at 23:43

1 Answer 1

1

Just add value in string like this:

var str = `${jsvar}`
json[key]['stories'] = `<span><a href="#" onclick="newStory(${value['stories']})">` + value['stories'] + '</a></span>';

Or

json[key]['stories'] = `<span><a href="#" onclick="newStory(${value['stories']})">${value['stories']}</a></span>`;
Sign up to request clarification or add additional context in comments.

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.