Sagar Singh Sagar Singh - 7 months ago 20
Javascript Question

how to get multiple input values with same id

I have a tag plugin which creates hidden input value as the user enter desired name in the input

for e.g

If i enter hello then plugin will create this hidden input

<input id="nameinput" name="tag[27]" value="63" data-tag-id="63" type="hidden">


& if i enter hello1

<input id="nameinput" name="tag[61]" value="22" data-tag-id="22" type="hidden">


now i want to get their value only and want to submit through jquery ajax
by comma separated like this-> 63, 22 as the user can enter maximum 8 tags

i tried using
$("#nameinput").val();
but it didn't work

Answer

You can select them by custom attribute this way:

var tags = []
$('[data-tag-id]').each(function () {
    tags.push($(this).val())
})
alert(tags.join(','))}

But it's bad to have multiple elements with same id.