简体   繁体   中英

HTML/JS - Populate a “confirm” popup with a value from an HTML field element

I have the following form fields to collect basic input from the user (a dollar amount).

        <tr><td><span class="qText" name="settlement">1. Amount:</span></td></tr> 
        <td><input type="hidden" class="qAns" name="settlement_t1_a">
            <input type="text" class="qAns" id="recovery_val" name="settlement_t1" oninput="formatValue('1');" required></td>

I'm trying to display a confirmation popup when the user clicks the submit button to say "verify amount is correct", and show the amount they entered in the above field "settlement_t1".

What am I doing incorrectly here?

<div class="submitDiv"><input type="submit" onclick="return confirm('Please confirm recovery amount is correct: $' + document.getElementsByName("settlement_t1")[0].value;" value="Submit Form"></div>

Everything works fine until I try to insert the element. As in, I can get it to prompt "Please confirm recovery amount is correct: $", but without the amount.

 function doConfirm() { return confirm('Please confirm recovery amount is correct: $' + document.getElementsByName("settlement_t1")[0].value); } function formatValue(value) { return value; }
 <form method="post"> <input type="hidden" class="qAns" name="settlement_t1_a" /> <input type="text" class="qAns" id="recovery_val" name="settlement_t1" oninput="formatValue('1');" required /> <div class="submitDiv"><input type="submit" onclick="return doConfirm()" value="Submit Form" /></div> </form>

A big part of the problem is that you are using inline event attributes, which is a 25+ year old legacy approach to event handling that just needs to die but doesn't because people see other people using it and they just copy it. Instead, separate your JavaScript from your HTML and set up events with .addEventListener() .

You are also adding a click event handler to a submit button, which triggers the submit event of the form when you should be adding your code to the submit event of the form instead.

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