Reputation: 57
How can I archive to get wildcard form name or ID?
I need to get form ID and both form are identical i only want Last digit in form ID for example in form1 I need 1 Please advice
<script>
$(document).on('submit', '[id^=addformj]', function(event){
event.preventDefault();
var formid=//I need to get form id here
alert('You have submited form ' + formid);
}
</script>
HTML is like this
<form id="form1">
<input id="value1">
</form>
<form id="form2">
<input id="value2">
</form>
I want to alert 1 if form ID 1 is submitted and 2 if Form ID 2 is submitted
<script>
$(document).on('submit', '[id^=addformj]', function(event){
event.preventDefault();
var formid=//I need to get form id here
alert('You have submited form ' + formid);
}
</script>
Upvotes: 1
Views: 174
Reputation: 2818
The form element can be accessed via the this
keyword. Here's an example:
$(document).on('submit', '[id^=form]', function(event) {
event.preventDefault();
console.log('The form: ', this);
var formid = this.id;
// Change substring start value based on length of the formid prefix.
alert('You have submited form ' + formid.substr(4));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
<input id="value1">
<input type="submit">
</form>
<form id="form2">
<input id="value2">
<input type="submit">
</form>
Upvotes: 2
Reputation: 63550
Why not use a data attribute instead? Much more convenient.
$('form').on('submit', handleSubmit);
function handleSubmit(e) {
e.preventDefault();
const id = $(this).data('id');
console.log(id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form data-id="1">
<input value="value1">
<button type="submit">Submit</button>
</form>
<form data-id="2">
<input value="value2">
<button type="submit">Submit</button>
</form>
Upvotes: 1