-1

I'm pretty new to both javascript and php and am having trouble getting something done.

I have an array form variable in PHP:

        <input type='hidden' id='results[]' name='results[]' value=''></input>

I want to put values in it through javascript and don't know how.

I'm trying something like the following:

                $("#results[index]").attr("value", "string");

What am I doing wrong?

Wanda Embar
  • 35
  • 1
  • 6
  • 3
    Possible duplicate of [What is the difference between client-side and server-side programming?](http://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Jared Smith Mar 09 '17 at 19:14
  • 1
    `results[]` and `results[index]` are not the same ID. Give a real ID to each input. – ceejayoz Mar 09 '17 at 19:15
  • But if I don't know how many items I'll have, how can I do this in advance? – Wanda Embar Mar 09 '17 at 19:16
  • The `name` attribute is used in PHP to process form fields, not the ID. So give your elements normal IDs and make sure they're unique – j08691 Mar 09 '17 at 19:32
  • @WandaEmbar You're adding these via some sort of logic or loop, right? Keep track of the number you've output, and just do like `results_1`, `results_2`, and so on. – ceejayoz Mar 09 '17 at 21:58
  • https://www.w3schools.com/jquery/jquery_ajax_get_post.asp –  Mar 09 '17 at 22:57

1 Answers1

1

That's not PHP, that's HTML.

First, remove those brackets from the id as that might not even be valid (but is likely confusing the issue):

<input type='hidden' id='results' name='results[]' value=''></input>

And set the value with val():

$("#results").val("string");

Everything that's happening here is client-side in HTML and JavaScript, PHP isn't involved here at all.

David
  • 208,112
  • 36
  • 198
  • 279
  • You're right. I'm using php though to get the result variables to another page. I want to put more than one variable in, that's why I made it an array. How can I do this? – Wanda Embar Mar 09 '17 at 19:18
  • @WandaEmbar: This is only a single `input` element, so it's only going to have a single value. That value can be some sort of serialized string of an array, which you could de-serialize in your PHP code if you like. There may be other ways to achieve what you're trying to do, but you aren't specifying anything about that in the question. – David Mar 09 '17 at 19:19
  • A serialized string! Thanks so much David. I could work with that! :) – Wanda Embar Mar 09 '17 at 19:20
  • 1
    @WandaEmbar If you want to have more than one value, you need to write more than one ``. – Álvaro González Mar 09 '17 at 19:40
  • Thanks Alvaro. The problem is that I don't know beforehand how many results I'll have. However, I'm working with a long string with delimiters now and the gorgeous explode method is putting it in an array for me. It's working like a charm. I appreciate all the help all of you gave! – Wanda Embar Mar 09 '17 at 19:45