I have this javascript:
$('#new_campaign_update').on('submit', function(event) {
debugger;
});
Is there a way I can find the button that submitted the form?
<%= form.submit 'Publish', class: 'button button-large button-primary accent-black', title: 'Publish this update now' %>
That is the button I clicked in order to submit the form can I find it on the event or something?
Yes you can with the event's currentTarget:
const buttons = document.querySelectorAll('input');
buttons.forEach(b => b.addEventListener('click', (e) => {
console.log(e.currentTarget);
e.currentTarget.style = "background-color:blue;";
}));
<input type="submit" id="a">
<input type="submit" id="b">
<input type="submit" id="c">
<input type="submit" id="d">
Assuming you have a form with id=new_campaign_update, and inside you have a single button with a class button-primary, the button will be accessible by $(this).find(".button-primary"), so you will access it like this:
$('#new_campaign_update').on('submit', function(event) {
const $button = $(this).find(".button-primary");
});
$(this) inside jQuery callbacks refers to the element that fired the callback. Inside the element you find the button with .find(".button-primary)"
Alternatively, if you have many buttons in a single form, you can add an onclick handler to the buttons themselves like this:
$('#new_campaign_update .button-primary').click(function() {
const $button = $(this);
}
Related
I have a Boostrap 5 form with validations and when I add the data-bs-target attribute to send button the modal is triggered even if the form has invalid entires.
I want to make the model triggered only when the form is successfully validated.
I tried it with javascript but my code didn't work
Below is my approach:
<div class="form-button mt-3">
<button id="submit" type="submit" class="site-btn " data-bs-toggle="modal" data-bs-target="">Send</button>
</div>
<script type="text/javascript">
(function() {
'use strict'
const forms = document.querySelectorAll('.requires-validation')
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.preventDefault()
event.stopPropagation()
}
form.classList.add('was-validated'),
document.getElementById('submit').dataset.target ='#confrimationModal';
}, false)
})
})()
</script>
You may programmatically open modal
const modal = new bootstrap.Modal(document.getElementById('confrimationModal'));
modal.show();
instead of
document.getElementById('submit').dataset.target ='#confrimationModal';
ref https://getbootstrap.com/docs/5.0/components/modal/#via-javascript
Do not call anything submit
Delegate
manually trigger the modal
Spelling (confirmationModal)
dataset.bsTarget to change data-bs-target
(function() {
'use strict'
document.addEventListener('submit', function(event) {
const tgt = event.target;
if (tgt.matches(".requires-validation") && !tgt.checkValidity()) {
event.preventDefault()
event.stopPropagation()
} else {
tgt.classList.add('was-validated');
document.getElementById('submitButton').dataset.bsTarget = '#confirmationModal';
}
})
})()
<div class="form-button mt-3">
<button id="submitButton" type="submit" class="site-btn" data-bs-toggle="modal" data-bs-target="">Send</button>
</div>
This is the div
<div class="col-lg-4 pre-scrollable" id="all-menus-div">
<h3 class="text-center">Tum menu listesi</h3>
<div class="list-group" id="all-menus-checkboxes" th:each="menu : ${allMenusList}">
<input th:id="${menu.id}" th:text="${menu.item}" th:value="${menu.item}" type="checkbox"/>
</div>
<button class="btn btn-success" disabled id="add-menus-to-role-btn" type="submit">Ekle</button>
</div>
<button class="btn btn-success" id="update-menus-for-role-btn" type="submit">Rolu guncelle</button>
</div>
it gets from model object.
This is the function of it for onchange:
$('#all-menus-checkboxes').on('change', function () { // on change of state
var addButton = document.getElementById('add-menus-to-role-btn');
lengthOfCheckedAllMenus = $('#all-menus-div :checked').length;
debugger;
console.log(" lengthOfCheckedAllMenus: " + lengthOfCheckedAllMenus);
addButton.disabled = lengthOfCheckedAllMenus <= 0;
});
it calls this function when I click the first checkbox only. And i can see only the log at this time. So, only button disabled becomes false only when i click the first one.
When i click others, nothing happens, no logs.
But when i click for example second one, then click first one, it shows 2 of them are selected.
Why is that?
Simple allMenuslist:
[MenuDTO{id=1, href='/check-deposit-money', menuName='Kontrol-Onay Ekranları', roles=[RoleDTO{id=1, name='ADMIN'}], iconName='null', item='Cüzdana Para Yükleme - Kontrol', className='null'}]
onchange event must to bind on the <input>.
bind event must to after <input> appended.
But your <input> like by dynamic generation, recommend use 'event delegation':
add class to <input>.
<input class="all-menus-checkboxes" />
use event delegation.
<script>
$('#all-menus-div').on('change', '.all-menus-checkboxes', function () { ... }
</script>
try this
$('#all-menus-checkboxes > input[type=checkbox]').on('change', function () { // on change of state
var addButton = document.getElementById('add-menus-to-role-btn');
lengthOfCheckedAllMenus = $('#all-menus-div :checked').length;
debugger;
console.log(" lengthOfCheckedAllMenus: " + lengthOfCheckedAllMenus);
addButton.disabled = lengthOfCheckedAllMenus <= 0;
});
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
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>
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>
Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.
I have 2 buttons on my page. Button 1 is executing a javascript function and another one is used for form processing. The problem is that button 1 is overriding the value and function of button 2.
Button 1 (not in a form) has the following html code:
<input id="show_hint" class="button" type="submit" value="Hint" onClick="location.href='#hint'" />
The javascript attached to it is:
// Button 1
$(function(){
var count = 3,
$btn = $('input[type="submit"]');
$btn.val($btn.val()+' ('+count+')')
$btn.click(function(){
$btn.val($btn.val().replace(count,count-1));
count--;
$('#hintscore')
.hide()
.css({
bottom: 30,
left: 300,
opacity: 1,
})
.show()
.stop()
.delay(200)
.animate({'bottom':75, opacity: 0},1000);
if(count==0) {
return !$btn.attr('disabled','disabled');
}
})
});
Button 2 (in a form) has this html code:
<input id="showmenu_win2" class="button" type="submit" value="Menu" />
The javascript attached to it is:
$('#form').submit(function() {
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "insert.php"
});
return false;
});
So these two are conflicting with each other and it has something to do with the type="submit". But how can I fix this?
Many thanks
This part of your JS:
$btn = $('input[type="submit"]');
is selecting both buttons and thus will attach the same behavior to both buttons.
Since you have an id on each button, you can select exactly the button you want by id:
$btn = $("#show_hint");
$btn = $('input[type="submit"]'); will select all the submit input elements in the DOM (so you are basically binding this event handler to both of your submit buttons when you call $btn.click(...).
Since you have IDs on each of your buttons you can change:
$btn = $('input[type="submit"]');
To:
$btn = $('#show_hint');
You can also find a root element to start your selector so that you are only selecting the button you want:
$btn = $('#ancestor-element').find('input[type="submit"]');
Or if you want to select all input[type="submit"] elements except the one in the form:
$btn = $('input[type="submit"]').not($('#form').find('input[type="submit"]'));
Change the button type to normal input button instead of submit. Change your script to bind your buttons to functions by selecting ID selector
In the below code $("#show_hint") will return an object of the input button with an id show_hint.
// Button 1
HTML
<input id="show_hint" class="button" type="button" value="Hint" onClick="location.href='#hint'" />
Script
$(function(){
var count = 3,
$("#show_hint").val($(this).val()+' ('+count+')')
$("#show_hint").click(function(){
$("#show_hint").val($(this).val().replace(count,count-1));
count--
// Your remaining code...
For the second button
HTML
<input id="showmenu_win2" class="button" type="input" value="Menu" />
Script
$('#showmenu_win2').click(function() {
$.ajax({
type: "POST",
data: $("#form").serialize(),
cache: false,
url: "insert.php"
});
return false;
});
You could replace the <input type="submit"> by a regular <button>. do achieve the same goal.
You could even create a <div> with an onclick event to mimic a button. You are not limited to input type="submit"
I am not sure this is the solution you want.My answer is to set show/hide button to type="button" while submit is type="submit".
Example
<button id="hide" type="button" >Hide</button>
<button id="show" type="button" >Show</button>