简体   繁体   中英

Alert textbox is empty when checkbox is checked

This might be a bit confusing but bear with me. I need 2 textbox and 1 checkbox. When the checkbox is checked, it needs to check whether the textboxes are filled or not. If the textboxes are filled in, it will do nothing.

I'm really struggling with this so I would really appreciate it. If you don't understand what I even said, here's the question that I need to solve.

*In page order.html, create a checkbox with label “same as delivery address” somewhere appropriate near the fields for billing address. When this checkbox is checked, the fields for billing address will be filled with the delivery address automatically. If the delivery address is not completed when this checkbox is checked, display an alert or inline message: “Please enter your delivery address first”. *

I've managed to do the duplicate part with these codes.(address and post codes are separated)

function copy() {
var daddress = document.getElementById("daddress");
var baddress = document.getElementById("baddress");
baddress.value = daddress.value;
var dpost = document.getElementById("dpost");
var bpost = document.getElementById("bpost");
bpost.value = dpost.value;  
}

But I cannot figure out the part after this.

Here's the code for the checkbox

<input id="duplicate" type="checkbox" name="duplicate"
value="Duplicate" onClick="copy();"/>Same as delivery address
<p id="dalert"><b><i>Please  enter your delivery address first</i></b><p>

In this case you could use a textarea for the address:

<textarea id="delivery-address"></textarea>

Then you would use JavaScript to get the contents of it with:

var deliveryAddress = document.getElementById("delivery-address").value.trim();

To check if they entered an address, you would use:

if (deliveryAddress === "") { ... }

In most cases, the address would be broken up into several inputs, often two lines for the street address, an input for city, state and postal code.

An alert is displayed like so:

alert('Some text');

You can use an if statement to check whether there's any input before setting them.

if (daddress.value && dpost.value) {
    baddress.value = daddress.value;
    bpost.value = dpost.value;
} else {
    alert('Please enter your delivery address first!');
    e.preventDefault(); // Stops checkbox from becoming checked.
}

JSFiddle

Edit: Forgot to mention that to use e.preventDefault() , you need to change your function to accept the e parameter ( function copy(e) {...} ) and pass event in your onclick event ( onclick="copy(event)" ). You'll see those in the JSFiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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