Set or remove attribute depending on value of another element

1,079 views
Skip to first unread message

Daniel Lidström

unread,
Feb 3, 2012, 5:32:47 AM2/3/12
to knock...@googlegroups.com
Hello,

I'd like to be able to set or remove an attribute from an input element depending on the value of another input element. The use case is the following: if the user enters a value for the number of strikes in a bowling game, then he must *also* enter a value for the number of misses. I am using ASP.NET MVC with unobtrusive jQuery validation, so the attribute I want to set is data-val-required. Here's my attempt so far:

Strikes input element:
<input type="number" value="" name="HomeTeam.Serie1.Game1.Strikes" id="HomeTeam_Serie1_Game1_Strikes" data-val-range-min="0" data-val-range-max="12" data-val-range="The field X must be between 0 and 12." data-val-number="The field X must be a number." data-val="true" data-bind="value: team_1_player1_strikes0, valueUpdate: 'afterkeydown'" class="valid">

Misses input element:
<input type="number" value="" name="HomeTeam.Serie1.Game1.Misses" id="HomeTeam_Serie1_Game1_Misses" data-val-range-min="0" data-val-range-max="12" data-val-range="The field Miss must be between 0 and 12." data-val-number="The field Miss must be a number." data-val="true" data-bind="enable: team_1_player1_strikes0, css: { 'input-validation-error': team_1_player1_strikes0 }, attr: { 'data-val-required': team_1_player1_strikes0 ? 'Number of misses required' : '' }" disabled="" data-val-required="Ange">

The important part is of course the data-bind attributes. The strikes input element will set the team_1_player1_strikes0 observable value when anything is entered. I would want the misses element to add data-val-required attribute when this happens, and remove the attribute when the strikes input element is cleared. My attempt doesn't work, obviously. How can I achieve this?
Thanks in advance!

Casey Corcoran

unread,
Feb 3, 2012, 11:55:00 AM2/3/12
to knock...@googlegroups.com
Looks like this will do the trick: attr:{'data-val-required':isRequired}

Where isRequired is an observable Boolean value. When set to false the
attribute is removed from the element.

Daniel Lidström

unread,
Feb 6, 2012, 8:19:38 AM2/6/12
to knock...@googlegroups.com
Thank you Casey! That would work for me.
Reply all
Reply to author
Forward
0 new messages