Calling a JQuery function inside a condition - javascript

I'm new to JS and JQuery and I'm trying implement the following functionality.
I have a form which has multiple inputs, each having its individual validation. These validations have been implemented inside one function.
function checkUpload() {
var flagu1=0;
var bookname = document.getElementById("title").value;
var flagu2=0;
.....
.....
var flagu6=0;
if( flagu1==0 && flagu2==0 && flagu3==0 && flagu4==0 && flagu6==0 )
return true;
else
return false;
}
This validation function is executed when a user clicks on the following button:
<button class="btn btn-secondaryup" name="submit" value="Upload" id="submitmeup" data-loading-text="UPLOADING..." onclick="clearBox('uploaderror')" type="submit" style="width:100%">UPLOAD</button>
Now I'm trying to implement Bootstap's 'loading state button' in this. The functionality would work like this:
When a user clicks on the button, the front-end validation function is called. Once the validation function (checkUpload()) returns true, the following JQuery function should be called.
<script>
$('#submitmeup').click(function() {
var $btn = $(this);
$btn.button('loading');
setTimeout(function () {
$btn.button('reset');
}, 5000);
});
</script>
The trick is that the button loading function has to be called only after the checkUpload function returns true. How do I implement this?

use below code. Use function inside condition .if function returns true then it execute code in side if condition
<script>
$('#submitmeup').click(function() {
var $btn = $(this);
if(checkUpload()){
$btn.button('loading');
setTimeout(function () {
$btn.button('reset');
}, 5000);
}
});
</script>

First remove the onclick attribute from the button:
<button class="btn btn-secondaryup" name="submit" value="Upload" id="submitmeup" data-loading-text="UPLOADING..." type="submit" style="width:100%">UPLOAD</button>
Then define your functions and set .on('click') event handler:
$(function() {
var $submitButton = $('#submitmeup');
// Submit handler
function handleSubmit() {
clearBox('uploaderror');
var uploadValid = checkUpload();
if (uploadValid) {
// Upload successful
showButtonLoading();
}
}
function showButtonLoading() {
$submitButton.button('loading');
setTimeout(function () {
$submitButton.button('reset');
}, 5000);
}
function checkUpload() {
var flagu1=0;
var bookname = document.getElementById("title").value;
var flagu2=0;
.....
.....
var flagu6=0;
if( flagu1==0 && flagu2==0 && flagu3==0 && flagu4==0 && flagu6==0 )
return true;
else
return false;
}
function clearBox(type) {
// Your implementation here
}
// Event handler
$submitButton.on('click', handleSubmit);
});
Now, clicking the button will go to handleSubmit function, which employs your code.

Related

Change button's text and function

I'd like to do the following. I got a button like this:
<button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button>
The JS part is this:
var search = new SiteSearch();
Now I'd like to do this:
Once clicked, the label of the button should show Stop search. And the called function should be search.stop(). If the user clicks Stop search, the button should be the Start search button again.
How can I do this in an elegant way?
Here you have working code snippet for this:
$(document).ready(function() {
function startSearch() {
console.log('Here your start search procedure');
}
function stopSearch() {
console.log('Here your stop search procedure');
}
$('.search-button').click(function() {
var buttonSelector = '.search-button';
if($(buttonSelector).hasClass('searching')) {
$(buttonSelector).removeClass('searching');
$(buttonSelector).text('Start search');
stopSearch();
} else {
$(buttonSelector).addClass('searching');
$(buttonSelector).text('Stop search');
startSearch();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="uk-button uk-position-bottom search-button">Start search</button>
Here's what I'd do: add an ID to the button, then query that button in the script and add a click listener to it. The script would keep track of whether or not a search is being done, then call search.start/stop() and set the button text accordingly.
<button id="search-button" class="uk-button uk-position-bottom">
Start search
</button>
<script>
const search = new SiteSearch()
const searchButton = document.querySelector('#search-button')
let searching = false
searchButton.addEventListener('click', () => {
if (!searching) {
search.start()
searching = true
searchButton.textContent = 'Stop search'
} else {
search.stop()
searching = false
searchButton.textContent = 'Start search'
}
})
</script>
You can do this easily like below:
var $elem = $('.uk-button.uk-position-bottom');
var search = {
//start function
start: function(){
//change the text
$elem.text('Stop search');
//change the click function
$elem.attr('onclick', 'search.stop()');
console.log('start clicked');
},
//stop function
stop: function(){
//change the text
$elem.text('Start search');
//change the click function
$elem.attr('onclick', 'search.start()');
console.log('stop clicked');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="uk-button uk-position-bottom" onclick="search.start()">Start search</button>
i think this answer is the same as a previus posted question:
https://stackoverflow.com/a/10671201/7387232
with the little add that when the button is clicked the button has to change the onclick propriety maybe with a check
object.onclick = function() {
if(search.isRunning()) search.stop();
}
and viceversa :-)
Try this:
Html:
<button id="search-btn" "class="uk-button uk-position-bottom" onclick="toggleSearch()">Start search</button>
JS:
var searching = false;
function toggleSearch(){
if(searching){
search.stop();
document.getelementbyid("search-btn").innerHTML = "Start search";
}else{
search.start();
document.getelementbyid("search-btn").innerHTML = "Stop search";
}
searching = !searching;
}
If I understood correctly your question this will solve your problem:
<button class="uk-button uk-position-bottom" data-process="0">Start search</button>
<script>
$(".uk-button").click(function () {
var $this = $(this);
var processStatus = $this.data("process");
//var search = new SiteSearch();
if (processStatus == "0") {
//you can trigger start function
$this.data("process", "1");
$this.text("Stop Search");
}
else if (processStatus == "1") {
//you can trigger stop function
$this.data("process", "0");
$this.text("Start Search");
}
});
</script>

Function works only in debugger

I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});

How to add a confirm dialogue to many different buttons at once with jQuery?

Let's say I have this HTML...
<button class="btn-remove-this">Remove this</button>
<button class="btn-remove-that">Remove that</button>
<button class="btn-remove-some-other-thing">Remove some other thing</button>
<!-- and many more 'Remove ...' buttons -->
...and this JavaScript.
$(function() {
$('.btn-remove-this').click(function() {
functionWhichRemovesThis();
}
$('.btn-remove-that').click(function() {
functionWhichRemovesThat();
}
$('.btn-remove-some-other-thing').click(function() {
functionWhichRemovesSomeOtherThing();
}
// and many more click handlers
});
Now I would like to prompt the user with a confirm dialogue before removing all those things. Is there a way to do it without adding and calling confirm inside every single click handler?
I have on my mind something like adding a single class to all of the different buttons (let's say btn-remove) and then adding a single click handler which could look like this:
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
// execute the body of the "more specific" click handler
} else {
// prevent the body of the "more specific" click handler from executing
}
}
You may write different click handler for different button and call common check function will function you want to call has a parameter and on ok click you can call that callback function.
$('.btn-remove-this').click(function() {
check(functionWhichRemovesThis);
});
$('.btn-remove-that').click(function() {
check(functionWhichRemovesThat);
});
$('.btn-remove-some-other-thing').click(function() {
check(functionWhichRemovesSomeOtherThing);
});
function check(callback){
if (confirm('Are you sure you want to remove this?')) {
callback();
} else {
// prevent the body of the "more specific" click handler from executing
}
}
This is also a way. So that you dont have to modify your code much.
I suggest you to use data-* for it here in your case:
<button class="btn-remove" data-func="functionWhichRemovesThis">Remove this</button>
<button class="btn-remove" data-func="functionWhichRemovesThat">Remove that</button>
<button class="btn-remove" data-func="functionWhichRemovesSomeOtherThing">Remove some other thing</button>
Now in your js code you can do this:
var removeUtil = {
functionWhichRemovesThis : function(){},
functionWhichRemovesThat : function(){},
functionWhichRemovesSomeOtherThing : function(){}
};
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
var removeIt = $(this).data('func');
removeUtil[removeIt];
}
});
Here is an example of how i would do it:
<button class="btn-remove btn-remove-some-other-thing">Remove something</button>
<button data-callback="App.remove.that" data-confirmText="Remove that?" class="btn-remove btn-remove-some-other-thing">Remove that</button>
<button data-callback="App.remove.this" data-confirmText="Remove this?" class="btn-remove btn-remove-some-other-thing">Remove this</button>
<script type="text/javascript">
var App = {};
App.remove = {};
// create an object to define different callbacks, outside of document(ready) so you an access it anywhere else you want.
App.remove['this'] = {
'yes': function () {
console.log('this.yes')
},
'no': function () {
console.log('this.no')
}
};
App.remove['that'] = {
'yes': function () {
console.log('that.yes')
},
'no': function () {
console.log('that.no')
}
};
$(document).ready(function () {
$('.btn-remove').click(function () {
var callback = {};
if (typeof $(this).attr('data-callback') !== 'undefined') {
// get the callback object of current button.
callback = $(this).attr('data-callback').split('.').reduce(function (obj, i) {
return App.remove[i];
}, App.remove);
}
var confirmText = 'Are you sure you want to remove this?';
if (typeof $(this).attr('data-confirmText') !== 'undefined') {
// set alternate text if needed
confirmText = $(this).attr('data-confirmText');
}
if (confirm(confirmText)) {
if (callback.hasOwnProperty('yes')) {
// do callback if property exists in callback object
callback.yes();
}
} else {
if (callback.hasOwnProperty('no')) {
// do callback if property exists in callback object
callback.no();
}
}
});
});
</script>

How to return false to parent event from its child in js

Here is my js code:
$(function () {
$('#buyer').on('submit', function (event) {
var userCaptcha = $('#jCaptcha').val();
$.post('Jcaptcha', {
jcaptcha: userCaptcha
}, function (responseText) {
if (responseText !== "") {
$('#ajaxcall').html(responseText);
//return from here
}
});
});
});
I want to return false to my submit event so that form should not get submit.
You can prevent the form from submitting in the first place, not inside the ajax callback, using event.preventDefault();. Your actual submit must be handled via ajax - I assume this is what happens in your $.post.
$(function () {
$('#buyer').on('submit', function (event){
event.preventDefault(); // dont actually submit natively
var userCaptcha = $('#jCaptcha').val();
$.post('Jcaptcha', { jcaptcha : userCaptcha }, function (responseText) {
if (responseText !== "") {
$('#ajaxcall').html(responseText);
}
});
});
});

How to get current object you working with

I need to process an AJAX request twice, first, when the site has been opened first time, and second, when a button is clicked. I dont want to write 2 similar functions. So I created an ajaxPost function. I wonder how to detect what event has called the ajaxPost function? opening the browser or clicking a button?
function ajaxPost() {
url = "post.php";
if (this!=Window) {
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});
Check for the jQuery event that you're passing with a click.
function ajaxPost(event) {
url = "post.php";
if (event == undefined || event == null) { //Was not generated by a user click
button = $(this).attr("class");
} else {
button = "";
}
var posting = $.post(url,{"button": button});
posting.done(function(data) {
$(".word").html(data);
});
}
$(document).ready(function() {
ajaxPost();
$("input[type=button]").click(ajaxPost);
});
A simple solution would be to include an additional parameter when calling the function:
function ajaxPost( caller ) {
switch( caller ){
case "initial_load":
// called on page load
break;
case "button_click":
// called on button click
break;
}
...
}
Now you would need to pass this parameter from the two different types of calls:
$(document).ready(function() {
ajaxPost( "initial_load" );
$("input[type=button]").on( "click", function(){
ajaxPost( "button_click" );
});
});

Categories