如何在javaScript中将所需的表单字段留空

时间:2016-06-30 13:53:44

标签: javascript

<!DOCTYPE html><html lang="en">
<head>  
<meta charset="UTF-8">  
<title>Form</title>         
<script> 

    function billingFunction()
    {
        var shippingName = document.getElementById("shippingName");

        if(document.getElementById("same").checked )
        {
            document.getElementById("billingName").value= shippingName.value;
        }
        else
        {
            document.getElementById("billingName").removeAttribute("required");
        }
    }

</script>
</head>
<body>  

    <form>      
        <fieldset>
            <legend>Shipping Information</legend>             
            <label for ="shippingName">Name:</label>          
            <input type = "text" name = "Name" id = "shippingName" required><br/>
        </fieldset>

        <input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>        
        <label for = "same">Is the Billing Information the Same?</label>                        

        <fieldset>
            <legend>Billing Information</legend>              
            <label for ="billingName">Name:</label>       
            <input type = "text" name = "Name" id = "billingName" required><br/>
        </fieldset>

    <input type = "submit" value = "Verify"/>   
</form>
</body>
</html>

每当选中该复选框时,代码应自动将第一个字段中的值复制到第二个字段中。如果未选中该复选框,则第二个应为空白。根据我的代码,第一个要求是可以的,但是在取消选中时我无法将其变为空白。任何人都可以帮助PLZ。

3 个答案:

答案 0 :(得分:0)

您只需要修改else

else{
            document.getElementById("billingName").value="";
        }

JSFIDDLE

修改

您已将billing函数放入标题中。您必须跨越引用错误。

您可以将此结算功能放在window.onload内,或将此脚本放在结束body标记附近

window.onload= function(){
billingFunction;
} 

function billingFunction(){ //Rest of code}
带有window.onload的

JSFIDDLE

答案 1 :(得分:0)

document.getElementById("billingName").value = null;添加到else子句中。

Fiddle

答案 2 :(得分:0)

只需将值设置为else子句中的空字符串

即可
function billingFunction() {
    var shippingName = document.getElementById("shippingName");
    var billingName  = document.getElementById("billingName");

    if(document.getElementById("same").checked ) {
        billingName.value = shippingName.value;
    } else {
        billingName.removeAttribute("required");
        billingName.value = "";
    }
}