0

Suppose to have an array:

array: ['hi,'by','miao']

Suppose to pass this array to one html page and I want put the second element in my html code:

<input type="button" id='{array[1]}'>....

But it doesn't work. Can anyone help me?

2
  • I know Javascript and HTML, and nowhere have I seen the syntax id='{array[1]}' before. I know it is possible to set the id using jQuery, is that what you are trying to do? Commented Nov 4, 2015 at 16:34
  • 1
    If you want the id to be literarily "{array[1]}", your code should work. But if you want that id to be "by", you'll have to actually set the id of the element: document.querySelector('input[type="button"]').id = array[1]; Basic html/javascript doesn't support syntax that will automatically fill values from javascript into html. You'd have to use a framework for that kind of coding. Commented Nov 4, 2015 at 16:39

2 Answers 2

1

You are missing a close quote after the hi:

array: ['hi','by','miao']
Sign up to request clarification or add additional context in comments.

Comments

1

First of all, there's the missing quote, as @erognaut and @unenthusiasticuser have pointed out.

As far as I know, I don't think it's possible to inject JS variables into HTML like you're trying to do there. It is possible with PHP or a server-side language, though.

Or, like @jBot-42 said, you may want to change the id using JS or jQuery using a script, but not like that. For example:

<input type="button" data-id='array_elem' />

<script>
    var array = ['hi','by','miao'];
    // uses jQuery
    $("input[data-id='array_elem']").attr("id", array[1]);
</script>

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.