2

I've developed a html contact form. How do I capture the data which is entered in the form using JavaScript? (I can't use jQuery)? I think I need use document.GetElementById(), but how? And do I need to use an event such as onBlur to capture it when a user leaves the field, radio button, or checkbox?

/*Borders of fields for validation and indication*/
input:invalid{
    box-shadow: 0 0 2px .5px red;
}
textarea:invalid{
    box-shadow: 0 0 2px .5px red;
}
/*Spacing around fields this is in place of <br>*/
label{
    display: block; 
    padding-top: 5px
}
<!DOCTYPE html>
    <html>
    <head>
      <title>Contact Me</title>
      <link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
    </head>
    
    <body>
    
    <form id="contactus">
     <fieldset>
      <label for="name">Name:</label>
       <input id="name" type="text" name="name" autofocus required>
      <label for="email">Email:</label>
       <input id="email" type="email" name="email" required>
      <label for="phone">Phone:</label>
       <input id="phone" type="tel" name="phone" required>
      <label for="status">Status:   
       <select id="status" name="status" required>
        <option value="client">Client</option>
        <option value="partner">Partner</option>
        <option value="vendor">Vendor</option>
       </select>
      </label>
      <label for="subscribe">
       <input id="subscribe" type="checkbox" name="subscribe" value="check" checked> 
      Send me your newsletter</label>
      <label for="sales">
       <label for="support">
        <input id="slsSupport" type="radio" name="slsSupport" value="sales" checked>Sales
        <input id="slsSupport" type="radio" name="slsSupport" value="support">Support
       </label>
      </label>
      <label for="msg">Message:</label>
       <textarea id="msg" name="msg" rows="10" cols="30" required></textarea>
      </fieldset>
      <fieldset>
      <button type="submit">Send</button>
      <button type="reset">Reset</button>
      </fieldset>
    </form>
    <script src="contactform_Lab8.js"></script>
    
    </body>
    </html> 
TylerH
  • 20,799
  • 66
  • 75
  • 101
Bigboy6
  • 109
  • 2
  • 3
  • 13
  • 1
    Is this what you're looking for? - http://stackoverflow.com/questions/11563638/javascript-get-input-text-value – wavemode Mar 27 '15 at 23:50
  • Always Google before asking :) – Timmah Mar 27 '15 at 23:50
  • @wavemode That's the part he knows about. What he doesn't understand is how to run it with an event handler. – Barmar Mar 27 '15 at 23:51
  • Rather than using getelementById, look into jQuery, which will give better cross-browser compatibililty. To get the idea of using jQuery to get a value, look at .[val()](https://api.jquery.com/val/) ,which includes example code. You can also easily handle the events with jQuery. – Reg Edit Mar 27 '15 at 23:52
  • The simple answer is that you have to write an event handler that gets the value when the user does something. What that something is is entirely up to you -- what do you want todo with the value, and when do you want it to happen? – Barmar Mar 27 '15 at 23:52
  • When a user enters data into the fields how do I capture that data using javascript and placing it in vars so I can use it in my javascript. I also want to do that with the radio buttons and checkbox. I hope this clarifies what I am looking for. – Bigboy6 Mar 27 '15 at 23:53
  • It sounds like you need to read some basic Javascript tutorials. They should explain the basics of binding event handlers. – Barmar Mar 27 '15 at 23:53
  • 1
    For a better UI, I would go for `change` and `input` events instead of `blur` etc. – Roko C. Buljan Mar 27 '15 at 23:59
  • Oh so I could use `change` to capture the data and use `input` to validate the data to provide instant feedback if value is invalid – Bigboy6 Mar 28 '15 at 00:05
  • @Bigboy6 exactly which will make things more *responsive*. You're building a JS validation system? Again, what are you trying to build? – Roko C. Buljan Mar 28 '15 at 00:09
  • It is a school project so for this part of the project I am just trying to get the values in the js. I will then be validating the value and then submitting them to the server – Bigboy6 Mar 28 '15 at 00:21
  • The objective of this lab will be to capture the onsubmit event and read the values of the inputs with JavaScript. An event handler must be attached to the form. For this lab, the event handler must prevent the form from being submitted. For each input, code must be written to access the value. I recommend using document.getElementById() to get the input elements, although you may use other methods. Bear in mind that radio buttons, checkboxes, and selects require different approaches to determine the value. You may want to change the HTML from the prior lab as you work on this lab. – Bigboy6 Mar 28 '15 at 00:22

2 Answers2

4

it is just the value attribute

//the specific input
var inputID = document.getElementById('inputID');

//add a listener to the object for blur
inputID.addEventListener('blur',function(){
    //the value attribute is the way to get what the user entered.
    console.log(inputID.value);
});

EDIT

For a more re-usable approach. Give all of the elements in the form the same class that you want to add the same blur listener to. Then loop through all of those elements and add the listener and handler.

var inputClass = document.getElementsByClassName('formInput');

for (var i = 0, ii = inputClass.length; i < ii ; i++) {
   inputClass[i].addEventListener('blur', doSomething);
}

function doSomething() {
    var inputField = this;
    console.log(inputField.value);
}

example: http://codepen.io/ScavaJripter/pen/33d9336b618f3162a9dfb16379ef4fcc/

Sam Eaton
  • 1,795
  • 1
  • 14
  • 19
  • 1
    or perhaps using a more scalable approach with function methods and form action elements iterators. – Roko C. Buljan Mar 27 '15 at 23:54
  • @Roko C. Buljan: I definitely agree, but milk before meat. – Sam Eaton Mar 27 '15 at 23:57
  • So I would place onblur="The var goes in here?" in the html and then this would allow the var in js to pick up the value? – Bigboy6 Mar 28 '15 at 00:02
  • @Bigboy6 can you please explain what are you going to build with that JS? What you need it for exactly? – Roko C. Buljan Mar 28 '15 at 00:04
  • 1
    I wouldn't use the onblur handler at all. You don't need to put javascript in your html tags. You can just give your HTML input an id and then in your javascript you can attach a listener that listens for a blur event. – Sam Eaton Mar 28 '15 at 00:05
  • Ohh see when I look on W3 I see they place the OnChange in the html w3schools.com/jsref/tryit.asp?filename=tryjsref_onchange @scavaJripter – Bigboy6 Mar 28 '15 at 00:35
  • 1
    This page talks about the old way of doing it, which is what you're talking about: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Older_way_to_register_event_listeners – Sam Eaton Mar 28 '15 at 00:38
  • So this is failing. Is this when I need to use a function to get each of the values. @scavaJripter – Bigboy6 Mar 28 '15 at 00:45
  • ` var name = document.getElementById('name'); var email = document.getElementById('email'); var phone = document.getElementById('phone'); var status = document.getElementById('Status'); var subscribe = document.getElementById('subscribe'); var slsSupport = document.getElementById('slsSupport'); var msg = document.getElementById('msg'); //add a listener to the object for onchange name.addEventListener('onchange'{ console.log(inputID.value); });` – Bigboy6 Mar 28 '15 at 00:48
  • 1
    if you are adding an event listener, you don't need the "on" before the event name. so change onchange to just change. – Sam Eaton Mar 28 '15 at 00:54
  • I do like the function method and form action elements as I feel I will be needing in the future @RokoC.Buljan – Bigboy6 Mar 28 '15 at 00:55
1

There are many ways to do this depending on what you want. Heres an example of A. alerting the value of the name field onblur B. Preventing the form from submitting unless the name is charles (final validation)

window.onload = function ()
{
  var name =document.getElementById("name");
  name.addEventListener("blur", alertVal);
  function alertVal(){
  alert(name.value);
  }
  var form = document.getElementById("contactus");
  form.addEventListener("submit",function(e){
  e.preventDefault();
  if(name.value == "charles"){
    alert("Success submitting form");
    form.submit();
    }
    else{
    alert("name must be charles");
    }
  });
 
}
/*Borders of fields for validation and indication*/
input:invalid{
    box-shadow: 0 0 2px .5px red;
}
textarea:invalid{
    box-shadow: 0 0 2px .5px red;
}
/*Spacing around fields this is in place of <br>*/
label{display: block; padding-top: 5px}
<!DOCTYPE html>
<html>
<head>
  <title>Contact Me</title>
  <link rel="stylesheet" type="text/css" href="contactform_Lab8.css">
</head>

<body>

<form id="contactus">
    <fieldset>
        <label for="name">Name:</label>
            <input id="name" type="text" name="name" id="name" autofocus required>
        <label for="email">Email:</label>
            <input id="email" type="email" name="email" required>
        <label for="phone">Phone:</label>
            <input id="phone" type="tel" name="phone" required>
        <label for="status">Status:         
            <select id="status" name="status" required>
                <option value="client">Client</option>
                <option value="partner">Partner</option>
                <option value="vendor">Vendor</option>
            </select>
        </label>
        <label for="subscribe">
            <input id="subscribe" type="checkbox" name="subscribe" value="check" checked> 
        Send me your newsletter</label>
        <label for="sales">
            <label for="support">
                <input id="slsSupport" type="radio" name="slsSupport" value="sales" checked>Sales
                <input id="slsSupport" type="radio" name="slsSupport" value="support">Support
            </label>
        </label>
        <label for="msg">Message:</label>
            <textarea id="msg" name="msg" rows="10" cols="30" required></textarea>
        </fieldset>
        <fieldset>
        <button type="submit">Send</button>
        <button type="reset">Reset</button>
        </fieldset>
</form>
<script type="contactform_Lab8.js"></script>

</body>

</html>
kurt
  • 1,146
  • 1
  • 8
  • 18