循环遍历表单并从对象填充

时间:2014-07-16 15:50:24

标签: javascript jquery

我有一个表单和一个javascript对象。

<form id="myForm">
    <input type="text" name="title">
    <input type="text" name="image">
</form>

var myObject = {title: 'this is the title', image: 'image.jpg'}

有没有办法运行表单输入,并且任何输入名称都与对象中的键匹配,设置值?

请注意,我希望遍历表单而不是对象,因为对象中包含许多与表单无关的其他数据(示例中未显示)。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

$("#myForm input:text[name]").each(function() {
    var name = $(this).attr("name");
    for (var key in myObject) {
        if (key == name) {
            $(this).val(myObject[key])
            break;
        }
    }
});

答案 1 :(得分:0)

有了这个,你永远不会循环对象,但是你必须为每个属性编写一个if子句:

var myObject = {title: 'this is the title', image: 'image.jpg'}

$('#myForm input').each(function()
{
    if($(this).attr('name') === 'title')
    {
        $(this).val(myObject.title);   
    }
});