Clicking a button to trigger a delayed click for another buttons - javascript

I'm trying to make a button that when it's being a click, it will trigger a click for another button too but with a delay for each of them. For example, if the Main Button is clicked, the Sub Button 1 will trigger a click, then Sub Button 2 will be clicked after 2 seconds and the Sub Button 3 will be clicked after 4 seconds.
The real scenario is a customer can select up to 3 products, the 3 products will be added to a cart if they click the main button because the add to cart button of those 3 products will be clicked too as they click the main button. The products page has an Ajax. If I click the main button, sometimes only 1 or 2 product(s) are being added. I'm trying to delay a click for each button.
$(".main-button").on("click",function(){
$(".container .row").each(function(i){
$rowNum = $(this).attr("id","row-" + i);
$rowNum.find("button").trigger("click").delay(5000).text("clicked");
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="main-button">Main Button</button>
<div class="container">
<div class="row">
<button class="sub-button">Sub Button 1</button>
</div>
<div class="row">
<button class="sub-button">Sub Button 2</button>
</div>
<div class="row">
<button class="sub-button">Sub Button 3</button>
</div>
</div>

$(".main-button").on("click",function(){
myLoop ($(".container .row").children().length)
});
var i = 1;
function myLoop (count) {
setTimeout(function () {
$('.container :nth-child('+i+')').children('button').text("clicked")
if (i < count) {
i++
myLoop(count);
}
}, 1000)
}
Try demo -
https://jsfiddle.net/jijomonkmgm/oL3bzp5r/

This isn't specifically what you asked for, but the outcome of the functionality that you seek will be the same.
In the comments, others and myself, talked about how you could choose to call your sub button functions within the main function itself, without having the logic of a chained button clicking functionality.
Before you can do that, you need to make sure that all of your sub functions are within the global scope so that you can access them in your main function.
Example:
subButtonOneFunction() {
//do something
}
subButtonTwoFunction() {
//do something
}
subButtonThreeFunction() {
//do something
}
$(".main-button").on("click",function(){
$.ajax({
type: 'POST',
url: '/path/to/your_page.php',
data: {
data : dataVar,
moreData : moreDataVar
},
success: function (html) {
subButtonOneFunction();
subButtonTwoFunction();
subButtonThreeFunction();
//and so forth
}
})
});
The sub button functions in this example is within reach of the main function, and so you will be able to call the sub functions within the main function.
Not knowing if there is more to your main function, other than the delayed, button clicking loop that you were attempting, I tried to provide an example of how an AJAX function works, plus adding a success function where you can call your sub functions.
Firstly, we declare the type. The type is the data type for the data the AJAX function will parse. Notable data types are POST and GET.
Secondly, we declare the url. The url is the page where your data will be parsed to. It can be your current page, or another page entirely.
Thirdly, we declare our variable names for our data that we wish to parse, and what their content is. The variables go by the same logic as any other variables that you know from JavaScript. So they can contain numbers, strings, arrays, whatever you normally know.
Taking one of the data variables from the AJAX example and giving it a value could be done like this:
Our AJAX example: data : dataVar
Literal example: data : $('input#SomeInputContainingValue').val()
our AJAX variable data will now contain the value of an input field that has the id SomeInputContainingValue.
Another example using the clicked elements value: data : $(this).val()
As you can see, the data is simply variables that you would declare as any other JavaScript variable. The difference here is that : is basically the syntax for = in the AJAX function's data array.
Lastly, we declare our success function in the AJAX function. What this does, is that it allows us to "do something" upon success. This is where you can call your sub functions for instance.
This would be a much cleaner approach, and will be much easier to look through when going over the application in the future, and doesn't look like a "hack" or other workarounds.

Related

How to properly pass values through in jquery / ajax calls

I've been creating a web app and one example of something it does is create golf rounds. Everything I've done works but I have been doing some testing and the way im passing variables through to my ajax call means the user could update anyone's round.
Currently I have a table that shows you your round and you can select the view button which will open a modal form to show details of that round.
This is my HTML
<button
type="button"
id="view-round"
class="btn btn-outline-primary btn-square btn-skew pull-right"
attr-id="39"
>View</button>
This is my jquery
$('body').on('click', '#view-round', function () {
var id = $(this).attr('attr-id');
$.post('/dashboard/pages/golf/round/ajax.php?action=load', {id: id}, function(response) {
//code in here
}
});
You can see from this that I'm passing through the round id via the attribute on the button "attr-id".
What I'm asking is can I put this variable somewhere someone couldn't edit it via the developer console etc.
I'm currently changing the ajax calls so that you can only update/look at your own records but really I'd like to stop it from being changed all together.

How to prevent repeatative submit while using ajax or javascript?

I have a controller in c# and inside the controller there is a save method. The save method saves/updates data that is submitted by submit button click and javascript. The problem is, if you click on the button multiple time, it should only process the very first click and rest of them should be identified as duplicate submit and should be discarded by controller. How to do this in c# mvc web application?
Disable the button after it's clicked. So it can just be clicked once.
Simple way
when button clicked disabled it then actived again after you got response result from ajax! u can also add loader that make ur web look so cool!
<button id="btnSend" onClick="send()">submit</button>
<script>
btnSend=document.getElementById("btnSend");
function send(){
btnSend.disabled=true;
//set disabled button here
$.ajax({ type: "GET",
url: "http://www.google.de",
async: false,
success : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
},
fail : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
}
});
}
</script>
I would also disable the button on the client side. But you could also check if the submitted data is different from the stored data. If no changes were made you could just return without further saving logic.
Should it be possible to just save the data once? Maybe a redirect to a different view after saving could be a possible solution in special cases.

jQuery Form won't hide and function return undefined

I'm having a problem with one the buttons. It doens't work properly.
When I click "Add Run" button and then "Home" button almost nothing work. The form that is dynamically created doesn't hide and search input doesn't show, and function return undefined.
$("#home").on("click", function () {
$("#search").show();
$("#addForm").hide();
$("#noPrevious").hide();
complete()
console.log(complete())
});
But on the other hand, some things work, they hide or show. For example, after refresh, when I click "All my Runs" it displays text, which will hide after clicking on "Home" button, and on top of that, search input field shows up. I don't understand this. Does anybody know what's wrong?
Thanks in advance.
Here is CodePen and GitHub. The problem is at the top of .js file.
https://codepen.io/ovy1448/pen/gZrKOX
https://github.com/ovy1448/MyRun/blob/master/js/main.js
Your problem is that you are not initializing your values properly. For example, in the case of bookmarks your code presumes that localStorage has a value with that key. However, that is not necessarily the case. You would need to have a default value for bookmarks. A helper function could be useful here:
function getBookmarks() {
var bookmarks = localStorage.getItem("bookmarks");
if (!bookmarks) bookmarks = [];
return bookmarks;
}
and then replace all occurrences of localStorage.getItem("bookmarks") to getBookMarks() in your code, except the one in the function above. Pay attention to other initializations as well.
EDIT
If you want to parse JSON inside the function, you can do it like so:
function getBookmarks() {
var bookmarks = localStorage.getItem("bookmarks");
if (!bookmarks) return [];
return JSON.parse(bookmarks);
}

Loader with python & flask

I make a premise: I'm working on a school project and the technologies that I can use are: python, flask, bootstrap, JavaScript and JQuery.
I have a button (that I will call to "Update Product") that "onclick" must enable one of these buttons:
https://www.w3schools.com/howto/howto_css_loading_buttons.asp, the "Update Product" button must be hidden and must call a function in python (example: updateProducts ()).
At the end of this function (the function returns ok or ko), I return the message (using flash), but I do not know how to hide the Loading button and show the "Update Product" button again.
Can you help me?
Here is one way.
When you render the template in python you could pass a variable to control the visibility of the button.
render_template('page.html', visible=True)
Then, on your page perhaps something like this (found at Hiding a button in Javascript and adapted)
<script>
var hidden = {{ visible|safe }};
function action() {
if(hidden) {
document.getElementById('button').style.visibility = 'hidden';
} else {
document.getElementById('button').style.visibility = 'visible';
}
}
You can also change the variable with an onclick function on then page itself.
Your button to call a python function could look something like this.
<input type="button" id="toggler" value="Toggler" onClick="/funcionName" />
Remember to use the #app.route("/functionName") before the python function.
Hope this is close to what you wanted.
Here are the steps to achieve this.
Add loading button with hidden class.
When you click update Product button, following things should happen.
$(".update_button").on("click", function(e){
$(".loading_button").show(); // show loading button
$(".update_button").hide(); // hide update button
$.ajax({}) // send ajax request to update product, on success, hide loader and show update button
});

C# MVC Razor: Javascript binding to a partial view

Previous question for context: C# MVC 5 Razor: Updating a partial view with Ajax fails
Now that I have successfully managed to refresh my partial view, I find myself having another difficulty which I don't really know how to deal with. You see, the table I am displaying also displays two buttons per line:
<td class="noWrap width1percent tri">
<input type="button" value="Valider" id="Valider_#i" data-valid=data />
<input type="button" value="Rejeter" id="Rejeter_#i" data-reject=data />
</td>
That's a "validate" button and a "rejection" button. Basically, each line can either be "approved" or "rejected", and the user uses those buttons to make a decision for each line. The actions are bound to a Javascript script, put on top of the main view, which looks like this:
$(function () {
$('*[data-valid]')
.click(function () {
// Get values of fields
$("#divLoading").show();
var idOfField = this.id;
var data = document.getElementById(idOfField).dataset.valid;
// Partially censored code
// Now that we have the values of all fields we need to use a confirmation message
var result = confirm("OK?")
if (result == true) {
// The user chose to validate the data. We have to treat it.
validateResults(data);
}
else {
$("#divLoading").hide();
}
})
ValidateResults:
function validateResults(data) {
$.ajax({
url: '#Url.Action("ValidateControl", "Article")',
type: "POST",
data: { data:data},
success: function (result) {
$("#tableControl").html(result);
$("#divLoading").hide();
}
});
}
A similar function exists for the rejection button.
Now, before successfully managing to refresh my Partial View, this worked fine. However, now that the refreshing works, clicking the buttons after refresh doesn't work. I believe this is because the Javascript action isn't bound to the buttons once more after the refresh event is done!
How can I make sure that my Javascript actions, in the main view, are bound to the buttons which are generated in the partial view?
Please note that I tried to put the portion of the main view in the partial view, instead. This makes sure that the actions are bound once again, but completely kills the CSS after refresh, which isn't a desirable outcome either!
Since you are essentially replacing the body of the table, you will need to re-wire the events if you do it the way you are doing it. You can also hook the event up to the parent tbody:
$(document).ready(function(){
$("#tableControl").on("click","*[data-valid]", function(){
....
});
});
I haven't tested the above but something like that should work. Or, just re-wire the events on the buttons after the partial view is refreshed on the page.

Categories

Resources