当前位置: 动力学知识库 > 问答 > 编程问答 >

Beginner Javascript Form

问题描述:

I have a simple form that i am trying to submit, but i cannot manage to get any values from it.

I have seen multiples examples but none of them seem to be working.

This is my html:

<form name="myForm" action="grade.html" method="get">

<label>Name:</label> <input type="text" name="fname">

<br>

<p>Is the Earth Round or Flat?</p>

<input type="radio" name="earth" value="round">Round<br>

<input type="radio" name="earth" value="flat">Flat

<p>What month is the Earth closest to the sun?</p>

<select name="sf">

<option value="jan" >January</option>

<option value="feb" >February</option>

<option value="jul" >July</option>

</select>

<br>

<hr>

<input type="submit" name="sub" value="Submit">

</form>

This is my javascript in the grade.html. Here I get nothing shown on the document.write() function.

 var grade = 0;

var form = document.forms[0];

//var x = document.forms["myForm"]["fname"].value;

//var e = document.forms["myForm"]["earth"].value;

//var s = document.forms["myForm"]["sf"].value;

document.write(form);

document.write(form.elements[0]);

I don't know what i am doing wrong, but none of them are working.

网友答案:

The grade.html page in itself has no form, so the javascript there does nothing.

网友答案:

If you're doing this in JavaScript, one way is to bind to the "submit" event for your form.

<form name="myForm" onsubmit="processForm()">
    ...
</form>

function processForm() { 
    document.write(document.forms[0].earth.value);
}

The JavaScript code (above) should be in the same file as the form, or included as a script from that file.

Here's an example fiddle: http://jsfiddle.net/53bvke8w/1/

分享给朋友:
您可能感兴趣的文章:
随机阅读: