Javascript输入值不能由用户更改

时间:2013-05-04 22:39:58

标签: javascript submit validation dom-manipulation

我对Javascript相对较新,并且在更改值方面遇到一些麻烦。

这是我的Javascript:

function printResults(results, numMeals){
    calories=Math.round(results);
    protein= Math.round(results/4*.4);
    carbs=Math.round(results/4*.3);
    fats=Math.round(results/9*.3);
    document.getElementById("calories").innerHTML="Total Calories: " + ('<input type="text" id= "totalCal">');
    document.getElementById("totalCal").value=calories;
    document.getElementById("protein").innerHTML="Grams of Protein: " + ('<input type="text" id="totalProtein">');  
    document.getElementById("totalProtein").value=protein;  
    document.getElementById("carbs").innerHTML="Grams of Carbs: " + ('<input type="text" id="totalCarbs">'); 
    document.getElementById("totalCarbs").value=carbs;  
    document.getElementById("fats").innerHTML="Grams of Fat: " + ('<input type="text" id="totalFats">'); 
    document.getElementById("totalFats").value=fats;
    calories= Number(document.getElementById("totalCal").value);
    protein= Number(document.getElementById("totalProtein").value);
    carbs= Number(document.getElementById("totalCarbs").value);
    fats= Number(document.getElementById("totalFats").value);
    document.getElementById("search").innerHTML= ('<a class="btn" href="search/'+calories+'/'+protein+'/'+carbs+'/'+fats+'/'+numMeals+'">Find Meals</a><br>');}

它编辑了这些html输入字段:

    <div class="span2" style="text-align:left">
    <span id="calories"> Total Calories: -</span><br>
    <span id="protein"> Protein: -</span><br>
    <span id="carbs"> Carbs: -</span><br>
    <span id="fats"> Fats: -</span><br>
    <span id="search"></span><br>
    </div>

这适用于设置初始值,但是,当我手动编辑文本字段的值时,它不会在提交时更改值。例如,如果基于计算将原始卡路里设置为2000,然后我将文本字段编辑为2500,则我的搜索仍然会产生2000的值。

1 个答案:

答案 0 :(得分:1)

是的,不是更改innerHtml的{​​{1}},而是将其更改为#search<a>,处理<button>事件并获取事件中的值。否则,您将在更改值之前生成搜索链接,因此它包含旧值。

此外,没有理由动态生成输入,在html中定义输入,只根据需要更改click

作为旁注,我真的建议调查jQuery,因为它使这些事情变得不那么冗长。

相关问题