Call Javascript function within Bootstrap button - javascript

I have a javascript code which I would like to put it in a function called SleepTime so I can pass in value and then call this function when I click on a button in an html page. Here's my code.
<script>
function SleepTime(value) {
$(document).ready(function () {
$("#ajaxSubmit").click(function (){
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
});
});
}
</script>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#progressBarCenter" id="ajaxSubmit" onclick="SleepTime(2000);" > Execute Script</button>
I get an error when I ran the above code. It said the function is undefined but I did define it?? How do I call this function so I can pass in the value??
tks

try this , the correct way of doing this , hope this helps:-
$(document).ready(function () {
$("#ajaxSubmit").click(function (){
var sleepTime =$(this).attr('sleepTime');
setTimeout(function() {
//$('#progressBarCenter').modal('toggle');
console.log('will get printed after 2 seconds')
}, sleepTime);
});
});
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#progressBarCenter" id="ajaxSubmit" sleepTime=2000 > Execute Script</button>

There are two things you miss-used here:
Please do not use $(document).ready() inside another function,
SleepTime(), as $(document).ready() is supposed to be executed
after DOM elements already loaded.
You call function SleepTime() one in you attribute onclick(), and you defined click() event listener inside function SleepTime(), this as far as I concern, it never be executed.
The correct way is as below:
$(document).ready(function() {
function SleepTime(value) {
alert(value);
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
}
$('#ajaxSubmit').click(function() {
SleepTime(2000);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<div class="container">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#progressBarCenter" id="ajaxSubmit"> Execute Script</button>
</div>

you can do one of these solutions
First One, using a java script function
-remove data-toggle="modal" data-target="#progressBarCenter"
-remove document ready, and click event listener from the function
-then call function on onclick
<script>
function SleepTime(value) {
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
}
</script>
<button type="button" class="btn btn-primary" id="ajaxSubmit" onclick="SleepTime(2000);" > Execute Script</button>
Second One, Using a JQuery event
-remove data-toggle="modal" data-target="#progressBarCenter"
-remove the function and put the code inside jQuery event listener
-remove onclick attribute from html
<script>
var value = 2000;
$(document).ready(function () {
$("#ajaxSubmit").click(function (){
setTimeout(function() {
$('#progressBarCenter').modal('toggle');
}, value);
});
});
</script>
<button type="button" class="btn btn-primary" id="ajaxSubmit" > Execute Script</button>

Related

Button inside a form is not accessible

I'm trying to trigger the click event of a button inside a form using jQuery.
$(".switchLang").on("click", function(e) {
console.log("Clicked!")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-inline" action="">
<button type="button" class="btn mr-3 btn-link transparent switchLang">${{index.keys.lng}}$</button>
<button type="button" class="btn mr-3 btn-outline-light">${{index.keys.login}}$</button>
<button type="button" class="btn btn-primary">${{index.keys.getStarted}}$</button>
</form>
The function above is not invoked!
After research, I tried many solution but nothing's work. Like adding e.preventDefault(); inside the function also remove .click and replaced with .on and so on, but nothing works!
I have referred to this question: here.
Thanks.
Solved
I double checked my code. the html is written inside script of type text/template and this template is rendered before the jquery code. Thanks.
You could try
$(document).on("click",".switchLang",function (e) {
console.log("Clicked!")
});
Try this might help
$(document).on('click', '.switchLang', function (e) {
console.log("Clicked!")
});
You need to wait for the document to be ready before adding the click handler, like so:
$(document).ready(function () {
$('.switchLang').on('click', function (e) {
console.log("Clicked!")
});
});

Why is the Jquery code fired more than once

I have a button that opens a modal from another page. One the modal is open if .myBtn is clicked the modal closes as expected and I get a click alert but when the open modal is pressed again I get 2 click alerts as the modal closes. Why is this and how can I keep all the elements in the dom 'working' but avoid the script being fired more than once? Many thanks.
Html
<button id="edit_credit" data-modal="myModal" class="btn btn-small btn-blue credit_btn">Open Modal</button>
Jquery
$(document).ready(function() {
//Open Modal
$('.credit_btn').on('click', function() {
$('.modal-container').load('modal_test.php',
function() {
$('#myModal').modal({show:true});
}
);
$(document).on("click", ".myBtn", function(){
alert('click');
});
});
});//End of doc
Modal_test.php (partial)
<button type="submit" id="btn" data-dismiss="modal" value="submit" class="btn btn-blue pull-right myBtn">
Save</button>
<button type="button" class="btn btn-red pull-left" data-dismiss="modal">Close</button>
</form>
</div><!-- /.modal-footer -->
Because of (see comments):
$('.credit_btn').on('click', function() {
// Everytime you click on .credit_btn
// ...
// You bind that event again (and again and again)
$(document).on("click", ".myBtn", function(){
alert('click');
});
});
You can safely bind that once outside your click-event-handling
$(document).ready(function() {
//Open Modal
$('.credit_btn').on('click', function() {
$('.modal-container').load('modal_test.php',
function() {
$('#myModal').modal({show:true});
}
);
});
$(document).on("click", ".myBtn", function(){
alert('click');
});
});
(although I would rename that class from 'myBtn' to 'closeModal' or something like that, be specific when you code ;) )

Different values for innerHTML in debug and console log

I'm encountering a typical situation while accessing the innerHTML property using jQuery. I've fetched the target button using the jQuery attribute selector.
Below is the snippet of jQuery attribute selector.
jQuery('button[type="button"][class="btn btn-primary"]').each(function () {
var btn = jQuery(this);
console.log(btn);
if (btn[0].innerHTML === "OK") {
console.log("ok");
jQuery(this).click();
}
});
Following is the screenshot of the console log of the target button. It's innerHTML property is set to OK.
Following is the screenshot of the value of the innerHTML while debugging the target button object. In this case the value is "".
Ideally, the values of the innerHTML should be the same for both the cases.
EDIT
Why does this behavior differ that the ideal one? For both of the cases, the value of the innerHTML should be the same.
Also, there were multiple buttons. I have taken screenshots of different buttons. Thus their ID's are different. But still, the behavior is same.
Try something like this.
function SomeEvent($ele) {
alert($ele.html());
return false;
}
function invokeBtnEvents() {
$("[data-action=some-event]").off(); // clear old events
$("[data-action=some-event]").on("click", function() {
var $this = $(this);
return SomeEvent($this);
}) // define event(s)
return false;
}
$(document).ready(function() {
invokeBtnEvents();
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event" class="btn btn-primary">Button 1</button>
<button data-action="some-event" class="btn btn-primary">Button 2</button>
<button data-action="some-event" class="btn btn-primary">Button 3</button>
<button data-action="some-event" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>
Your issue
What you are doing that I think is your main issue is the $.each() method.
Store the buttons in a variable,
let $button = $("button"); // this returns an array of all the buttons on the DOM
You can then use the $.each() method to get the clicked element
$.each($button, function(index, btn){
const $this = $(btn);
$this.off();
$this.click(function(){someEvent($this)});
});
I would not invoke button clicks like this because every time you click a button, this each loop gets ran. It will then send all of the buttons to that action unless you parse by an ID or something (you are using the innerText).
If you use the code in my snippet, only the clicked button will be triggered.
An alternative approach to my first snippet is using something like a dispatcher.
function DoActionOneClick($ele){
alert("Action 1 " + $ele.html());
}
function DoDefaultClick($ele){
alert("Default Action " + $ele.html());
}
function DispatchEvent(action, $ele){
switch(action){
case "some-event-1":
DoActionOneClick($ele);
break;
default:
DoDefaultClick($ele);
break;
}
}
function invokeActions(){
$("[data-action]").off();
$("[data-action]").on("click", function(){
// get this
var $this = $(this);
// get action
var action = $this.data().action;
DispatchEvent(action, $this);
});
}
$(document).ready(function(){
invokeActions();
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-12">
<br />
<button data-action="some-event-1" class="btn btn-primary">Button 1</button>
<button data-action="some-event-2" class="btn btn-primary">Button 2</button>
<button data-action="some-event-2" class="btn btn-primary">Button 3</button>
<button data-action="some-event-2" class="btn btn-primary">Button 4</button>
</div>
</div>
</div>

button causing page to reload

I am using html and jquery on my page.
In my html i have one button which when clicked will fire one function.
When page loads i call main function in document ready. Here is my code
<script>
$(document).ready(function () {
main();
});
function main(){
//some code goes here
}
function search(){
//some logic
}
</script>
<div>
<button id="btnSearch" onclick="search()" >Search</button>
</div>
But when i click on button then it goes inside main function and executes code inside it. Why? It should only call function search and nothing else. What am i doing wrong?
by default BUTTONS are of type SUBMIT, try this instead
<button type="button" id="btnSearch" onclick="search()" >Search</button>
This is working fine for me. See demo
$(document).ready(function () {
main();
});
function main(){
//some code goes here
alert('main');
}
function search(){
//some logic
alert('search');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="btnSearch" onclick="search()" >Search</button>
</div>

Fire button click event when there are multiple classes on an element

How would I fire a button click event when a particular button is pressed (in this case the accept button).
I've tried the following but with little success:
Javascript
$('.notification-expand .Request .active-item > .accept-button').click(function () {
alert("hello");
});
HTML
<div class="notification-expand Request active-item" style="display: block;">
<div class="notification-body"></div>
<br>
<p>
<button type="button" class="btn btn-success accept-button btn-sm">Accept</button>
</p>
<div class="row">
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-warning barter-button btn-sm">Barter</button>
</div>
<div class="col-xs-6 expand-col">
<button type="button" class="btn btn-danger reject-button btn-sm">Reject</button>
</div>
</div>
</div>
Fiddle here
You have error in your selector , it should look like this:
$('.notification-expand.Request.active-item .accept-button').click(function () {
alert("hello");
});
You need to concatenate all classes without spaces to catch your target button
$('button.accept-button', '.notification-expand.Request.active-item').click(function () {
alert("hello");
});
See the updated snippet
Notice the syntax of ".className1.className2" instead of ".className1 .className2"
should be something like:
$('button.accept-button').click(function(){ ... });
there is really no need to go down the whole list if this is the whole code
----edit----
so when there are more items but only 1 active(i guess) then just target the active-item class:
$('div.active-item button.accept-button').click(function(){ ... });
try
$('.accept-button', $('.notification-expand.active-item')).click(function () {
alert("hello");
});
or
$('.notification-expand.active-item')).find('.accept-button').click(function () {
alert("hello");
});
Just give the button an id and reference back to that.
HTML
<button id="btnSubmitData"> Ok Button </button>
JQuery Code
$('#btnSubmitData').click(function(){ ... });
You can also have multiple button Ids bind to the same event:
$('#btnAccept, #btnReject, #btnWarning').click(function () {
alert("hello");
});
Take a look at the updated Working Fiddle.

Categories