简体   繁体   English

Javascript:在HTML表单隐藏输入字段中设置值

[英]Javascript : Set values in HTML Form hidden input fields

Using javascript / jquery. 使用javascript / jquery。 I want to do this for every field that starts with 我想为每个开头的领域做到这一点

query. 查询。

queryForm['Foo'].value = queryForm['query.Foo'].value;
queryForm['Bar'].value = queryForm['query.Bar'].value;
queryForm['Baz'].value = queryForm['query.Baz'].value;

queryForm.submit();

And only if the queryForm['Foo'] exists. 并且只有queryForm ['Foo']存在。

Context: (You don't need to know this to answer my question, but it nice to know the context) 上下文:(你不需要知道这个来回答我的问题,但很高兴知道上下文)

Above question is because of a fix / hack. 上面的问题是因为修复/黑客攻击。 Because I put the original Model in the ViewModel. 因为我将原始模型放在ViewModel中。 Now Query is in the QueryViewModel. 现在Query在QueryViewModel中。

@model QA.ViewModels.QueryViewModel
@using QA.ViewModels
@using QA.Enums
@{ 
    var query = Model.Query;
}
<div class="form-group">
    @Html.Required(model => query.Foo, "Describe the facts and circumstances that are relevant to the query", true, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-9">
        @Html.EditorFor(model => query.Foo, new { htmlAttributes = new { @class = "form-control qa-tinymce-content" } })
        @Html.ValidationMessageFor(model => query.Foo, "", new { @class = "text-danger" })
        @Html.Hidden("Foo")
    </div>
</div>

Reading closely at what you did here: you put the old ViewModel in a new ViewModel and you do not want to rename the fieldnames in the partials. 仔细阅读你在这里所做的事情:你将旧的ViewModel放在一个新的ViewModel中,你不想重命名部分中的字段名。

Then why don't you add the needed fieldnames to the new ViewModel? 那你为什么不把所需的字段名添加到新的ViewModel?

public Query Query { get; set; }

#region Variabeles in Query you do not wish to rename in the partial views.

public string Foo {
    get { return Query.Foo; }
    set { Query.Foo = value; }
}

#endregion 

Your hack could be easily done with simple javascript like the following (not tested) : 您可以使用以下简单的javascript(未经测试)轻松完成您的hack:

for (let propertyName in queryForm){
 if(!queryForm.hasOwnProperty(propertyName) || propertyName.indexOf("query.") !== 0){
   continue;
 }
 let shortPropertyName = propertyName.substring(6);
 if(!queryForm.hasOwnProperty(shortPropertyName)){
   continue;
 }
 queryForm[shortPropertyName].value = queryForm[propertyName].value;

 //if you want to delete the 'long' property:
 // delete queryForm[propertyName];
}
//// (use let or var at your preference)

But, you should really ask yourself why you would want to do such things ! 但是,你应该问自己为什么要做这样的事情!

IMHO, you would better go with a proper and tidy model for your view . 恕我直言,你最好选择一个适当而整洁的模型供你观看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM