For example, if i had a form like this:
<form id="form1">
<input type="text" name="item">
</form>
<button onclick="outputItem"></button>
How would I output the input from the form?
You can write a function in which you can use querySelector() to get the element to get the value of the input:
function outputItem(){
var v = document.querySelector('#form1 > input[name=item]').value;
console.log(v);
}
<form id="form1">
<input type="text" name="item">
</form>
<button onclick="outputItem()">Print</button>
<form id="form1">
<input type="text" name="item" id="item">
</form>
<button onclick="outputItem()">ShowMe</button>
<span id="response"></span>
<script>
function outputItem() {
var item = document.getElementById('item').value;
document.getElementById('response').innerHTML = item;
}
</script>
Try above one.
Before clicking on the button Try it you have write some text into the input. Otherwise, it can get an error - undefined.
function outputItem() {
var x = document.getElementsByName("item")[0].value;
document.getElementById("demo").innerHTML = x;
}
<form id="form1">
<input type="text" name="item">
</form>
<button onclick="outputItem()">Try it</button>
<p id="demo"></p>
var input = document.getElementByName('item');