从json中填充html字符串中的值(在表单元素中)并使它们只读

时间:2014-07-03 14:08:38

标签: javascript jquery html json

我有一个像这样的HTML字符串:

<h5><span class="wp-step">Step 1 : </span> Service Info</h5><div class="wp-details"><h2>Procedure includes:</h2>
<p>
    <input type="checkbox" name="Procedure Includes" value="Microdermabrasion">Microdermabrasion<br>
    <input type="checkbox" name="Procedure Includes" value="Chemical Peels">Chemical Peels<br>
    <input type="checkbox" name="Procedure Includes" value="Botox">Botox<br>
    <input type="checkbox" name="Procedure Includes" value="Fillers">Fillers<br>
</p>


<h2>Customized For:</h2>
<p>
    <input type="checkbox" name="Customized For" value="For oily and combination skin">For oily and combination skin<br>
    <input type="checkbox" name="Customized For" value="For normal, dry skin">For normal, dry skin<br>
    <input type="checkbox" name="Customized For" value="For sensitive skin">For sensitive skin<br>
    <input type="checkbox" name="Customized For" value="For dull�visibly ageing skin">For dull�visibly ageing skin<br>
</p>



<h2>Duration of this procedure (including the preparation time)</h2>
    <input type="radio" name="Procedure Duration" value="0-30 mins">0-30 mins<br>
    <input type="radio" name="Procedure Duration" value="30-60 mins">30-60 mins<br>
    <input type="radio" name="Procedure Duration" value="60-90 mins">60-90 mins<br>
    <input type="radio" name="Procedure Duration" value="More than 90 mins">More than 90 mins<br>





<h2>What are the known possible side effects?</h2>
<p>
<textarea id="Side Effects" name="Side Effects" rows="10" cols="70"></textarea>
</p>


<h2>Any other details or restrictions to add?</h2>
<p>
<textarea id="More Details" name="More Details" rows="10" cols="70"></textarea>
</p>

其次我有一个json格式:

    {Procedure Includes: "Microdermabrasion",
 Customized For: "For oily and combination skin",
 Procedure Duration: "0-30 mins",
 Side Effects: "test",
 More Details: "test"} 

现在我需要将此字符串转换为只读的html字符串,其中包含相应的值。应检查相应的复选框,以及单选按钮和textareas等。

我尝试了几个循环,但都变得太复杂了。有没有一种标准方法来处理这个问题?

1 个答案:

答案 0 :(得分:0)

解析JSON,然后循环遍历该对象,然后遍历每个具有多个输入的字段并检查相应的输入,然后将数据放入只有一个<input><textarea>的字段中

var json; //Get the JSON somehow...
var info = JSON.parse(json); //...and parse it.

var procedureForm; //Our form
document.addEventListener("DOMContentLoaded", function() { //When the window loads...
    //Set procedureForm

    for (var name in info) { //Loop through the object

        //If the field with this name is a bunch of inputs...
        if (procedureForm[name].hasOwnProperty("length")) {
                //Loop through it...
                //If the input value matches, check the input
            }
        }

        //Otherwise...
        else {
            //Just put the data into the input/textarea 
            procedureForm[name].value = info[name];
        }
    }
});

这是小提琴:http://jsfiddle.net/NobleMushtak/P3v9Y/1/