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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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.