1

Here's my case:

I'm trying to get value from form's input that has name="data[type][answer]", something like:

<form id="form" method="POST" >
<input type="hidden" name="data[type][answer]" value="Hello from Space">
</form>

So, my code for function should look like:

 function queryForm(key) {
   return $('#form input[name=' + key + ']').val();
 }

I'm getting input[name=order[type][answer]] which is not working and I'm aware why.

Is there a way how to write this thing differently or is there any other way how to get the value? By the way, I need the name exactly in this form: name="data[type][answer]"

Any advice or solution would be nice!

3
  • Try this function queryForm(key) { return $('#form input[name=' + key + ']')[0].val(); } Commented Jul 27, 2018 at 16:26
  • @Stranger your solution raises a script error, I think. Commented Jul 27, 2018 at 16:52
  • Possible duplicate of How do I select an element with special characters in the ID? Commented Jul 27, 2018 at 17:00

2 Answers 2

1

You just need quotes around the value for name. Then you have to select the first result from the returned and wrap it again with jquery to be able to call .val():

function queryForm(key) {
    return $("#form input[name='" + key + "']").first()
      .val();
}
 
console.log(queryForm('data[type][answer]'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <html>
    <head></head>
    <body>
    <form id="form" method="POST" >
    <input type="hidden" name="data[type][answer]" value="Hello from Space">
    </form>
    </body>
    </html>

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

1 Comment

A couple of tips to make this a little easier: Use double quotes instead of escaping single quotes. Use .first() instead of using [0] and wrapping the result with another jQuery call.
0

All you just need to do is ...

function queryForm(key) {
   return $('#form input[name="' + key + '"]').val();
}

note the double quote (") around key.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.