Reputation: 1
I have apiece of code where i am changing the ID of the form like this;
$("form").prop('id','FormApplied');
before the above formID was Form1
i have two functions
$(document).on('submit','#FormApplied',function(e) {
$(document).on('submit','#Form1',function(e) {
it is always firing the Form1, even i had changed the formID, how can i fix that because both functions have separate logic written
Thanks
Upvotes: 0
Views: 303
Reputation: 6568
It doesn't trigger both functions
function changeValue(){
$('#formId').prop('id', 'formId2');
console.log('form Id changed');
}
$(document).on('submit','#formId',function(e) {
console.log('submitted');
});
$(document).on('submit','#formId2',function(e) {
console.log('submitted 2');
});
function restoreId(){
$('#formId2').prop('id', 'formId');
console.log('form Id restored');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='formId'>
<input type='hidden' value=0 id='hiddenInput'/>
<input type='button' value='click to change the id ' onclick='changeValue()'/>
<input type='button' value='click to restore the id ' onclick='restoreId()'/>
<input type='submit' value='submit' />
</form>
Upvotes: 0
Reputation: 23863
When you apply an event listener to a form element, the event doesn't know about what selector was used (In this case you are selecting the element by ID.)
There are several choices.
You could use one event handler and then use that to decide which logic to use, but that has the bad effect of mixing logic (what to do when the button is pressed) with presentation logic (the ID of the button).
You could set a data-*
property on the element and select off that, but think even that is a bit more awkward.
Instead, I would use two buttons, and just toggle the visibility based upon the rules
function showButton(butNumber) {
document.getElementById("but1").style.display = "none";
document.getElementById("but2").style.display = "none";
document.getElementById("but" + butNumber).style.display = "";
}
showButton(1);
document.getElementById("but1").addEventListener("click", function() {
console.log("Button 1");
showButton(2);
});
document.getElementById("but2").addEventListener("click", function() {
console.log("Button 2");
showButton(1);
});
<form>
<button type="button" id="but1">Button 1</button>
<button type="button" id="but2">Button 2</button>
</form>
Upvotes: 1