I tried using an infinite loop within this function however, when I set up the setInterval the function doesn't repeat. The problem is when the user sends the form and after the time interval passes. The function stays on the sent message and doesn't start from the beginning. Please see my JSBin.
Javascript:
$(function(){
function show_fb() {
$("#feedback_box").show("slow");
}
function hideAll() {
$("#feedback_box").hide("slow");
}
$("#feedback_box #close").click(function() { // When the X is pressed
$("#feedback_box").hide("slow"); // Hide the form
});
setInterval(show_fb,1000); // Show the form after 6 seconds , you can change 6000 to anything you like
$("#feedback_form").submit(function() { //When the form is submitted
$('#feedback_form #fb_title').css('background-color','#4444FF').text('Sending...').slideDown(900); //show "Sending" message
$.post("form_submit.php",{ mesaj:$('#mesaj').val(),rand:Math.random() } ,function(data) { //subimit the feedback via AJAX
$('#feed_subm').attr("disabled", "false"); //disable the "SEND" button
$('#feedback_form #fb_title').css('background-color','#C33').text('Thank You!').slideDown(900); //Shows a thank you message
setTimeout(hideAll,2000); // Hide the form after 2 seconds
});
});
return false; //Tells the code not to post the form physically
});
HTML:
</head>
<body>
<div id="feedback_box">
<form id="feedback_form">
<span id="fb_title">Give us some feedback :)</span><span id="close">X</span>
<textarea id="mesaj"></textarea>
<input type="submit" value="Send" class="mysubm" id="feed_subm"/>
</form>
</div>
</body>
You can repeat a function in jQuery like this:
Javascript:
$(document).ready(function() {
// First we will create the function that will be repeated
function repeat() {
setTimeout(function() {
// Enter your code that you want to repeat in here
repeat(); // This is where the function repeats
}, 1); // Where 1 is the delay (in milliseconds)
}
repeat(); // Here we are initially firing the function
});
In your example above, I can't see why you would need a function constantly being repeated however your question was How I can repeat a function in jQuery?
Which I think means How can I repeat a function in jQuery?
Well here's your answer.
Related
Pre-story: I am using Algolia search to search on my website.If the user start typing in the input field the results will start appearing on the screen.
End goal: close the filters (toggle functionality) by default.
Issues: when the user start typing in the input the url change and the filters stay open.
If I apply the code in the console after the user finishes with typing I can see the button being close.
If I apply the jQuery codes bellow and while I am typing the filters stay closed, but again once the user stops typing the filters open again.
Once I finish with typing (input looses focus) the filters open again.
My approach:
First
$("input#dropdown_search").on('input',function(e){
$("b- utton.button.filters__button").click();
});
Second
$('input#dropdown_search').keyup(function() {
$("button.button.filters__button").click();
});
Third
$('input#dropdown_search').on('inputchange', function() {
$("button.button.filters__button").click();
});
Fourth
$("input#dropdown_search").on('change keyup paste', function () {
ApplyFilter();
});
function ApplyFilter() {
$("button.button.filters__button").click();
}
It seems that they don't reach the end goal where they keep the filter hidden even after the user stops typing.
Can you please help?
Try this
$("input#dropdown_search").on('change', function () {
$("button.button.filters__button").trigger("click");
});
For your stop typing problem try this answer: Run javascript function when user finishes typing instead of on key up?
You can use trigger to trigger click
$("#dropdown_search").on('change keyup paste',function(event){
$(".buttonclass").trigger('click'); //trigger .buttonclass button on trigger of events
})
$(".buttonclass").on('click',function(event){
alert("I am clicked")
})
Example jsFiddle
Try this:
var timer;
$("input#dropdown_search").on('change keyup', function () {
clearInterval(timer);
timer = setInterval(function() {
ApplyFilter();
}, 1500);
});
type in first input , that will click the button immediately then fire function to change the second input value
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type=text id=dropdown_search>
<input type=text id=dropdown_search2>
<button id=target onclick="be()">
<script>
onload = function () {
var t = document.getElementById('dropdown_search');
t.oninput = function (){
document.getElementById("target").click();
};
t.onpropertychange = t.oninput; // for IE8
t.onchange = t.oninput;
};
function be() {
var t = document.getElementById('dropdown_search').value;
document.getElementById('dropdown_search2').value=t;}
</script>
</body></html>
The setInterval function is not working in my jsp page, below is my code:-
<script>
$(document).ready(function(){
$('form[name="lgform"]').submit(function(evnt){
evnt.preventDefault();
try{
mapPlotVar.clearInterval();
}
catch(e)
{
}
mapPlotVar=setInterval($("#btn_login").click(function(){console.log("update");},20000));
});
$("#btn_login").click(function(){
alert("hi");
});
});
</script>
<body>
<form name="lgform">
<div>
<table id="table" >
<tr>
<td width="35px"><input id="mob" type="text" name="mob_nu" placeholder="1234567890" maxlength="10"></td>
<td width="100px"><input type="button" name="login_btn" id="btn_login" value="Login"></td>
<td width="100px"><label for="Login" style="color: red" id="login_val"></label></td>
</tr>
</table>
</div>
</form>
</body>
</html>
After clicking the "btn_login" once i want the function to be called after every 20 seconds so that i get the alert message "hi" after every 20 seconds, but "hi" is only showing once, setInterval function is not working. What is wrong with my code? Any piece of code is appreciated.
I tried to use the set Interval here in a different manner because, i want the function to be called just after my first click and continue after every 20s and it wont work if we put the set interval function inside the function we call on button click in usual way.
Thanks in advance
setInterval($("#btn_login").click(function(){console.log("update");},20000));
The above will call jQuery.click once and pass its return value (a jQuery object) to setInterval but setInterval expects a callable function as its first argument.
The correct way to do it by wrapping into an anonymous function:
setInterval(function() {
$("#btn_login").click(function(){console.log("update");})
}, 20000);
But this still makes not much sense, since this way a new click event handler will be added (but not executed) to element every twenty seconds.
Your code has a lot of problems. Ignoring the other issues, if you want to set a 20s interval for a function on button click, you need to kick off the interval inside of the click handler.
$("#btn_login").click(function(){
setInterval( function () {
alert('hi');
}, 20000);
});
Of course, this will then happen on every button click. One way to solve it would be to use .one('click', function() { setInterval...}) instead of .click() because it will then work on first click only. But since it looks like you also want to cancel the interval, you'll need to take care of that as well.
edit:
var interval;
$("#btn_login").one( 'click', function() {
function run () {alert('hi');}
run();
interval = setInterval( run, 20000 );
});
// you can now cancel this interval somewhere else
function someCallback () {
if ( interval )
clearInterval(interval);
}
There are four basic things wrong with your code:
You do everything when the form is submitted, but you have no mechanism to submit the form (and your description says you don't want it to trigger on submission anyway).
Your code to tell the browser do stuff when the button is clicked is being passed to setInterval instead of the other way around.
You aren't passing a function to setInterval.
The code you want to run every time period is nowhere near your interval code
You need to throw out most of the code and start again.
var interval;
function run_on_interval_when_button_is_clicked(){
alert("hi!");
}
function run_when_button_is_clicked(event) {
event.preventDefault();
interval = setInterval(
run_on_interval_when_button_is_clicked,
20000
);
}
$(document).ready(function(){
$("#btn_login").on('click', run_when_button_is_clicked);
});
None of this has anything to do with JSP. That's server side code.
var interval;
$('#btn').on('click',function(){
if(typeof (interval) === 'undefined') {
interval = setInterval(function(){
alert('hi');
},20000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
$('#btn_login').on('click', function(){
setInterval(function(){ console.log("update"); }, 20000);
});
This is a small javascript/jQuery program where the user starts with a portfolio of 20K and, when one inputs an amount and clicks on 'buy', the program then evaluates if you have enough money to do so. If you don't, then a message appears saying that you have insufficient funds. I want that message to stay on the screen for at least 5 seconds and, ideally, fadeout slowly afterwards. I've tried both the $.delay() method with jQuery and the setTimeout() method and both don't work. Any idea why?
JavaScript/jQuery:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
Some other code that works:
JS :
$("#buttonBuy").click(function() {
amount= document.getElementById('investment').value
if (/*you have enough money*/){
//do something
}
else
{
//1st option (setTimeOut): it doesnt respect the delay for some reason,only shows up for about 1 sec
document.getElementById('insufficientFunds').innerHTML= "Insufficient funds! ";
setTimeout(function(){
document.getElementById('insufficientFunds').innerHTML= "";
}, 5000);
}
});
//2nd option (delay method) : I get error--> Failed to execute 'query SelectorAll on element: *;x is not valid selector
$(function () {
$('#insufficientFunds').fadeIn('slow', function () {
$(this).delay(5000).fadeOut('slow');
});
});
};
HTML :
<form>
<input type="text" id="investment" <br>
<button id="buttonBuy" >Buy</button>
</form>
<p>Portfolio Value :</p>
<p id="portfolio"></p>
//1st option
<p id="insufficientFunds"> </p>
//second option
<p hidden id="insufficientFunds" > insufficient funds! </p>
I can't repeat your error, but this code seems to be working.
$("#buttonBuy").click(function () {
amount = document.getElementById('investment').value
if (true) {
$(function () {
$('#insufficientFunds').fadeIn('slow', function () {
$(this).delay(5000).fadeOut('slow');
});
});
};
});
JSFiddle
I am using jQuery to prevent submitting form on clicking if amount is <10 and using jQuery AJAX to update amount after every 2 seconds. If meanwhile amount > 10 then I want to re-submit the form which is already filled.
I have used
$("form").submit(function(e){ e.Preventdefault;})
To prevent submitting the form when amount < 10 and if meanwhile amount updates to > 10 then I am unbinding the submit button and calling submit function again.
$("form").unbind("submit");
$("form").submit();
But this doesnt POST the data to action URL.
Here's my complete code
$(document).ready(function() {
var damount;
var checking=0;
setInterval(Call2, 3000);
function Call2() {
damount=$("#damount").val();
if(damount>10 && checking==1)
{
$("form").unbind('submit');
$("form").submit();
}
}
$("#addproject").click(function(){
checking=1;
damount=$("#damount").val();
if(damount<10)
{
$("form").submit(function(e){
e.preventDefault();
});
}
});
See another similar post and my response here:
https://stackoverflow.com/a/25806502/4021932
You're trying to call submit() on a jQuery object, which won't work. You need to call it on the DOM element.
$("form").unbind('submit'); //This is fine as it's dealing with the submit event, which jQuery handles
$("form")[0].submit(); //This calls submit() on the form DOM element
What about trying something like this:
$(function () {
$("form").submit(function (e) {
var damount = parseInt($("#damount").val());
if (damount < 10) {
e.preventDefault();
}
});
setInterval(function () {
$("form")[0].submit();
}, 3000);
});
I'm developing an application in that i need to capture user input from text box, if he stops typing for more than 3 sec. means we need to capture that text using javascript and need to store it in mysql db... plz help me out of this?
Thank you.....
Attach events to the input (e.g. keyup, keydown, keypress). There you will set up a setTimeout with a callback. Of course the timeout ID will be stored in a var (e.g. window.type_timeout). The setTimeout callback will do what you want ater those 3 seconds of inactivity.
You can start here. E.g.(using jQuery):
$('input').on('keyup',function(){
if( window.type_timeout ) clearTimeout( window.type_timeout );
window.type_timeout = setTimeout( do_stuff , 3000 , this /* extra data */ );
});
function do_stuff( input ){ /* do your stuff */ }
Use setTimeout. W3 schools has a pretty good reference on JavaScript timing
<script>
inputSaveTimeout = null;
function DoSomething() {
window.clearTimeout(inputSaveTimeout);
alert('I just did something');
}
function Updated(e) {
window.clearTimeout(inputSaveTimeout);
inputSaveTimeout = setTimeout(Save, 3000, e.value);
}
function Save(data) {
alert('Saved: ' + data);
}
</script>
<input type="text" onkeydown="Updated(this);" /><input type="button" value="Do Something" onclick="DoSomething(); return false;" />