Search code examples
jqueryjquery-selectors

jQuery select input element with name as array


I Googled this for half an hour and cant find the solution but I think this should be something really simple.

This is my code

<input name="order[name]" id="order[name]" type="text">

<script>
    $(document).ready(function(){
        $("#previewForm").click(function(){
            var orderName = $("input[type=text][name='order[name]']").val();
            $( "#contactCollected" ).text( orderName );
        });
    });
</script>

I want the user to preview the form that he just filled.

Replacing

$( "#contactCollected" ).text( orderName );

with

$( "#contactCollected" ).text( 'some text' );

works so I think it's the selector problem. I can provide more code if necessary.

EDIT: It appears this works as is, I'm not even sure where in the process I replaced one mistake with another one.

Thanks For all the folks in comments especialy @Barmar and @Jonathan.Brink .

I wouldn't delete the question because of the discussion on naming ID's in input elements but I'm not sure about the rules.

Thank you everyone for your time and I apologise once more for not trying out the jsfiddle right away.


Solution

  • Change your "type" from "text" to "input" and remove your explicit "type" declaration:

    <input name="order[name]" id="order[name]" />
    
    $("input[type=input][name='order[name]']")
    

    Past that, a note on characters to use for dom attributes:

    For pre-HTML5 you will have flaky behavior if you use bracket's in your attributes, such as id and name.

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    You may be able to get away with the brackets with an HTML5 doctype though:

    HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.

    For more details: What are valid values for the id attribute in HTML?

    I would recommend coming up with a different naming scheme for your id's, then your selectors will be more straightforward.

    Multi-attribute selector example: https://api.jquery.com/multiple-attribute-selector/