Unread array with index set in input

Asked

Viewed 51 times

1

see below the following code:

<input type="text" id="task" name="task[]" value="100" />
<input type="text" id="task" name="task[]" value="110" />
<input type="text" id="task" name="task[]" value="120" />

And in jquery, I normally read the array:

$(function(){
var values = $("input[name='task\\[\\]']")
          .map(function(){return $(this).val();}).get();

alert(values);
});

Now, when including the manual Intel in the array, it looks like this:

<input type="text" id="task" name="task[1]" value="100" />
<input type="text" id="task" name="task[2]" value="110" />
<input type="text" id="task" name="task[3]" value="120" />

In this case, jquery no longer reads the array. What should be done to make it possible to read?

  • What’s wrong with php?

  • The problem seems to be with the regular expression you are using to recover the Inputs: name='task[]' (omitting the escapes: ). When you entered the number, it was no longer valid. Try replacing it with: $("input[name='task [. ]]"). If it works, watch out because the regular expression is still very specific, and it wouldn’t work with a larger two-digit array, like task[10] for example.

  • Hello Newton, in this case, could you suggest me another more appropriate regular expression?

  • This will take all inputs that start with task and have something next: $("input[name='task.*']")

1 answer

1

In this scenario I do not see sense the use of the index on the property name, since there is another problem in this HTML. You’re doing the same id for more than one element on your page. The id, as your name says, is a unique identifier, should not have more than one on the same page. It would make more sense for you to work in the following way:

<input type="text" id="task[1]" name="task[]" value="100" />
<input type="text" id="task[2]" name="task[]" value="110" />
<input type="text" id="task[3]" name="task[]" value="120" />

If you do not intend to work directly with ids, I also advise you to remove that information. If something is not going to be used, do not put this information unnecessarily trying to predict its future use, this is not something recommended (there is a principle that is spoken of this: YAGNI)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.