I have the following script:
<script type= 'text/javascript'>
function displayPlayer() {
var input = document.getElementById("player_stuff").elements;
var position = input[0];
var player_id = input[1];
document.getElementById('disp_player').innerHTML = position + player_id
}
</script>
And a simple HTML form:
<form id = 'player_stuff' onsubmit = 'displayPlayer()'>
Player's Position:<br>
<input type="radio" name="position" value="p1" checked>Position One
<input type="radio" name="position" value="p2" checked>Position Two
<input type="radio" name="position" value="p3" checked>Position Three
<input type="radio" name="position" value="p4" checked>Positin Four
<br/>
Add by Player ID:<br>
<input type='text' name='player_id'>
<input type="submit" value="Submit Player" id='smit' >
</form>
<div id = 'roster'>
<h3>Current Roster</h3>
<p id= 'disp_player'></p>
</div>
The idea is that when I click on the Submit Player button, it will trigger the displayPlayer() function and add the position name and player ID to the
<p id= 'disp_player'></p>
tag.
What am I doing wrong, since nothing is showing up?
You can avoid submitting altogether by using the <button type="button">
, and then you can bind on the onclick
event of the button
. You can simplify things by avoiding the input list instead using querySelector
:
<form id = 'player_stuff'>
Player's Position:<br>
<input type="radio" name="position" value="p1" checked>Position One
<input type="radio" name="position" value="p2">Position Two
<input type="radio" name="position" value="p3">Position Three
<input type="radio" name="position" value="p4">Positin Four
<br/>
Add by Player ID:<br>
<input type='text' name='player_id'>
<input type="button" value="Submit Player" id='smit' >
</form>
<div id="disp_player"></div>
Then using querySelector
and querySelectorAll
document.getElementById('smit').onclick = function () {
var checkedPosition =
document.querySelectorAll("#player_stuff [name='position']:checked");
var playerId =
document.querySelector("#player_stuff [name='player_id']");
var position = checkedPosition[0].value;
var player_id = playerId.value;
document.getElementById('disp_player').innerHTML =
position + " " + player_id;
}
See the fiddle here.
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