简体   繁体   中英

In Javascript how can I make an Alert and modify html based on the contents of a form

I need to take the contents of form fields (client, phone number) validate them (most likely using regex) and concatenate them into an alert and a modify some html so on form submit I get

<p>John smith
99999999
2 wilerby dr
morrowie city
morrowie </p>

and alert("form data") ..

I tried with something like var field1 = document.forms[0].elements[0].value , but not sure how to address the fields.

Edit :

<form id="form1" action="form_action.asp">
    <fieldset>
    <table cellpadding="3" border="0">
        <th> Order Details </th>
        <tr>
            <td>Client Name:</td>
            <td><input id="clientname" type="text" name="clientname" value="" maxlength="20"></td>
        </tr>
...

Edit 2

var name = document.getElementById('clientname').value;

function buttontest()
    {
    alert(clientname);
    }

using this script I keep getting a [object HTMLInputElement] alert, the script is external and the script tag is in the header.

You should use DOM selectors alike document.getElementById('elementId').value .

Please read the resembling documentation about such browser APIs: https://developer.mozilla.org/en-US/docs/Web/API/document

Try add an ID to those fields, and use getElementById() . Example.

var val = document.getElementById('id_field').value;
document.getElementById('id_tag').innerHTML = val;
var clientName = document.getElementById('clientname').value;
alert(clientName);

if you already know the sequence no of the element that you want to address then only you can use the syntax you specified ie as follows:

document.forms[form_index].elements[form_element_index].value

form_index ->the index of the particular form where the element is.

form_element_index ->the index of the element in the particular form.

So you could use:

alert(document.forms[form_index].elements[0].value);

NB- form_index will be 0 only if the form you refer to is the first form in your document.

Otherwise

If you don't know either the sequence no of the form or the sequence no of the element in the form you should use the id attribute to refer to it(No need of any reference to the form where the element is) which is the usual approach and I personally suggest you to use this.

So in your code use the following:

alert(document.getElementById('clientname').value)

您应该使用document.getElementById('ID') ,可以访问www.w3schools.com了解更多详细信息。

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