I have 2 forms in my html code, but when I go to press the button of form2, the value of form1 is sent
function chk() {
var text = document.getElementById('text').value;
console.log(text);
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="form1">
<input type="text" id="text" value="Hi">
<input type="submit" id="submit1" onclick="return chk()">
<label for="submit1">Hi</label>
</form>
<form id="form2">
<input type="text" id="text" value="bonjour">
<button id="submit2" onclick="return chk()">btn</button>
<label for="submit2">bonjour</label>
</form>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Ids should be unique on a page. You can use a name
for the input elements instead.
function chk(formId) {
var text = document.getElementById(formId).querySelector('input[name=text]').value;
console.log(text);
return false;
}
<form id="form1">
<input type="text" name="text" value="Hi">
<input type="submit" id="submit1" onclick="return chk('form1')">
<label for="submit1">Hi</label>
</form>
<form id="form2">
<input type="text" name="text" value="bonjour">
<button id="submit2" onclick="return chk('form2')">btn</button>
<label for="submit2">bonjour</label>
</form>
Method 2
the id “text” is used twice in your code, which can lead to confusion, you should try changing it to “text1” and “text2”
And use the one you need in your function.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0