I am having trouble trying to figure out how to do this. I want to, using fields in a form as variables call a JavaScript function.
I have this:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
from an example but what I need is this, but doesn't work:
<form onsubmit="myFunction(this.num_cluster)">
Num. Cluster: <input type="text" id="num_cluster">
<input type="submit">
</form>
Cloud someone help me ? Thanks :)
Change id to name - after that you can access value of input field
function myFunction(form, event) {
event.preventDefault();
alert(form.num_cluster.value);
}
<form onsubmit="return myFunction(this, event)">
Num. Cluster: <input name="num_cluster" type="text">
<input type="submit">
</form>
As problem is little more interesting - we can extend our method onsubmit
function s(form, event) {
event.preventDefault();
var values = Array.prototype.slice.call(form.elements) // as form elements are not an array
.filter(function(element) {
return element.type !== 'submit'; // I don't need submit button
})
.map(function(element) {
return (element.name + ': ' + element.value); // get name and value for rest form inputs and assign them to values variable
});
alert('values => ' + values.join(', ')) // finish
}
<form onsubmit="return s(this, event)">
<p>Foo:
<input type="text" name='foo' />
</p>
<p>Bar:
<input type="text" name='bar' />
</p>
<p>Baz:
<select name='baz'>
<option value="lorem">lorem</option>
<option value="ipsum">ipsum</option>
</select>
</p>
<p>
<input type="submit" />
</p>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With