I want to get value of input which id name is "q" when I click the cancel button. I'm just a beginner and no idea how to get it. Thanks for your helps.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<div>
Cake
<div >
<button onclick="cancel(event)">Cancel</button>
</div>
</div>
<div for="">1000</div>
<div>
<input type="number" value="3" id="q">
</div>
<div >300</div>
</div>
<script>
function cancel(e) {
console.log(e.target.parentElement.parentElement.parentElement);
}
</script>
</body>
</html>
CodePudding user response:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<div>
Cake
<div >
<button onclick="cancel(event)">Cancel</button>
</div>
</div>
<div for="">1000</div>
<div>
<input type="number" value="3" id="q">
</div>
<div >300</div>
</div>
<script>
function cancel(e) {
console.log(document.querySelector('#q').value);
}
</script>
</body>
</html>
Since Id's should be unique on every page you can get it like this else you'd just go and do
function cancel(e) {
console.log(e.target.parentElement.parentElement.parentElement.querySelector('#q').value);
}
CodePudding user response:
To get an element with id
you can just use document.querySelector('#q')
like below
const valueOfInput = document.querySelector('#q').value;