-1

I'm trying to set a value to input element(s) that match the ID.

But the jQuery.each is picking up only the first/one input element.

I'm trying to perform a ajax post and i need both these ID to have the same value.

HTML

@Html.HiddenFor(u => u.TransID)   
//<input id="TransID" name="TransID" type="hidden" value="0">

@Html.DropDownListFor(u => u.TransID, Model.TransModes)
//<input id="TransID" name="TransID" value="0">

Script

$("#TransID").each(function () {
    $(this).val("2")
    alert($(this).val()); 
});

Cheers

Marc Audet
  • 46,011
  • 11
  • 63
  • 83
Searching
  • 2,269
  • 1
  • 17
  • 28

1 Answers1

10

An id must be unique in HTML. If you want to name several elements the same then use class instead.

<input class="TransID" name="TransID1" type="hidden" value="0">

<input class="TransID" name="TransID2" value="0">

Script

$(".TransID").each(function () {
    $(this).val("2")
    alert($(this).val()); 
});
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
  • 2
    You type too fast, man :P – MightyPork Aug 07 '13 at 22:19
  • 1
    Your names also need to be unique otherwise you are going to override one of them when the form is submitted. – prodigitalson Aug 07 '13 at 22:19
  • If the alert is just for debugging `$(".TransID").val("2");` is enough. – Marcel Gwerder Aug 07 '13 at 22:21
  • 2
    @prodigitalson, [that is actually incorrect](http://zzzzbov.com/blag/querystring-hell). If you're submitting multiple fields with the same key the query string (or form encoding) will have the key listed multiple times (e.x. `?foo=bar&foo=baz`). A correct query string parser will be able to get all the values correctly. – zzzzBov Aug 07 '13 at 22:21
  • @MightyPork ... yeah, but unfortunately I always produce too many typos ... :-/ and -->prodititalson: of course, the names must be unique otherwise you will not be able to get anything sensible on the receiving end! – Carsten Massmann Aug 07 '13 at 22:22
  • @prodigitalson, i should also mention that duplicate keys *must* be supported to handle ` – zzzzBov Aug 07 '13 at 22:22
  • Thanks for the hack. As much as i hate doing this i needed it. – Searching Aug 07 '13 at 23:03