Robert Achmann
Robert Achmann

Reputation: 2035

Set text of Html.LabelFor dynamically

C#, MVC 5 Razor, jQuery 2.1.1

If this is a duplicate, please point me in the right direction because I can't find it.

The code:

 @Html.LabelFor(model => model.BillState, 
     new { @class = "control-label col-lg-2 col-md-2" })

produces...

<label class="control-label col-lg-2 col-md-2" for="BillState">Province</label>

Note: No ID. No Special class.

So how do I change its text in jQuery in the client on the change of another fields text (ie Country is USA, so change it to 'State')?

Do I need to add an ID attribute to the label so that this is easier, or is there some tricky way to do this without adding IDs?

Upvotes: 2

Views: 8872

Answers (2)

Hatjhie
Hatjhie

Reputation: 1365

you can use the attribute for. For example,

$("label[for*='BillState']").text("State");

Please let me know if the code above suits your requirement.

Thanks.

Upvotes: 5

Sirhc
Sirhc

Reputation: 538

To keep things simple you could just give it an id by passing it as one of the htmlAttributes to the helper.

@Html.LabelFor(model => model.BillState, 
     new { @class = "control-label col-lg-2 col-md-2", @id = "lbl_billState" })

and in your script.

$("#lbl_billState").text("text here");

Upvotes: 1

Related Questions