从对象获取值并设置复选框状态

时间:2020-09-22 21:02:48

标签: javascript jquery checkbox

在下面的示例中,我需要第一个复选框为checked,第二个和第三个复选框为unchecked

目前,我正在全部checked

let data = {"admin":"true","nts":"false","chat":"false"};

$('button').on('click', function(){
    $('.bcheck').each(function(){
            let x = $(this).attr('data-x');
            $(this).attr('checked', data[x]);
        });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='checkbox' class='bcheck' data-x='admin'>
<input type='checkbox' class='bcheck' data-x='nts'>
<input type='checkbox' class='bcheck' data-x='chat'>
<button>CLICK</button>

2 个答案:

答案 0 :(得分:2)

您在public void ConfigureServices(IServiceCollection services) { IAppSettings appSettings = new AppSettings(); Configuration.Bind("AppSettings", appSettings); services.AddAuthentication(AzureADDefaults.AuthenticationScheme) .AddAzureAD(options => { options.Instance = appSettings.Authentication.Instance; options.Domain = appSettings.Authentication.Domain; options.TenantId = appSettings.Authentication.TenantId; options.ClientId = appSettings.Authentication.ClientId; options.CallbackPath = appSettings.Authentication.CallbackPath; }); services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.UseTokenLifetime = false; options.Authority = options.Authority + "/v2.0/"; //Microsoft identity platform options.TokenValidationParameters.ValidateIssuer = true; // https://stackoverflow.com/questions/49469979/azure-ad-b2c-user-identity-name-is-null-but-user-identity-m-instance-claims9 // https://stackoverflow.com/questions/54444747/user-identity-name-is-null-after-federated-azure-ad-login-with-aspnetcore-2-2 options.TokenValidationParameters.NameClaimType = "name"; //https://stackoverflow.com/a/53918948/12300287 options.Events.OnSignedOutCallbackRedirect = context => { context.Response.Redirect("/UserAccess/LogoutSuccess"); context.HandleResponse(); return Task.CompletedTask; }; }); services.Configure<CookieAuthenticationOptions>(AzureADDefaults.CookieScheme, options => { options.AccessDeniedPath = "/UserAccess/NotAuthorized"; options.LogoutPath = "/UserAccess/Logout"; options.ExpireTimeSpan = TimeSpan.FromMinutes(appSettings.Authentication.TimeoutInMinutes); options.SlidingExpiration = true; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); // who are you? app.UseAuthorization(); // are you allowed? app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=UserAccess}/{action=Login}/{id?}"); }); } 对象中的值都是字符串。因此他们都将求值为data。丢掉字符串,使它们变成布尔值。

true
let data = {
  "admin": true,
  "nts": false,
  "chat": false
};

$('button').on('click', function() {
  $('.bcheck').each(function() {
    let x = $(this).attr('data-x');
    console.log(data[x]);
    $(this).attr('checked', data[x]);
  });
});

答案 1 :(得分:1)

字符串"false"不是虚假的(在控制台中尝试!!"false" === true)。您可以将字符串更改为常规布尔(false)吗?

编辑此操作即可完成

let transformedData = {};

const dataEntries = Object.entries(data).map((entry) => {
  return { [entry[0]]: !(entry[1] === "false") };
});

for (const entry of dataEntries) {
  transformedData = { ...transformedData, ...entry };
}