Enable and Disable the buttons - javascript

I want to enable and disable the buttons using jquery or javascript.
The real scenario is
If i click the start button it goes to the php table coloumn if the status is in running state the start button get's disabled same if the status is in stopped state the start button need to enable.

jQuery('#button-id').attr('disabled', true);
jQuery('#button-id').attr('disabled', false);
You just needs to change the disabled attribute value

Please use Ajax by JQuery.
$('#btn').click(function (e) {
e.preventDefault()
let btn = $(this)
btn_disable(btn)
$.ajax({
url: 'your_url',
method: 'your_method',
data: {your_data}, //if you haven't data please type {}
success: function (response) {
btn_enable(btn)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
btn_enable(btn)
},
complete: function (response) {
btn_enable(btn)
}
})
})
function btn_disable(btn) {
btn.attr('disabled', 'disabled')
btn.addClass('disabled')
}
function btn_enable(btn) {
btn.removeAttr('disabled')
btn.removeClass('disabled')
}
Here you can read more about Ajax :
https://api.jquery.com/jquery.ajax/

Please check the below sample. If the API response is true then the button gets disabled and if it's false then it gets enabled
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "ur_Api, success: function(result){
if(result === true){
$("#btn_status").attr('disabled', true);
}
else {
$("#btn_status").attr('disabled', false);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button id="btn_status">Status</button>
</body>
</html>

Related

$.ajax not working when used in ("click") event listener

This is my Javascript code:
const checkbox = document.querySelector("#checkbox");
const button = document.querySelector("#button");
button.addEventListener("click", function(e){
var text = "";
if(checkbox.checked === true){
text = "Is Checked";
}
$.ajax({
url: '/update_if_checked/',
data: {'is_checked': text},
type: 'POST'
}).done(function(response){
console.log(response);
});
});
I am getting an error which says $.ajax is not a function at HTMLButtonElement.
Here, checkbox is an input of type checkbox and when the button whose id is "button" is clicked, I want to send the data i.e. if the checkbox is checked to the Django Server.
I have imported this version of jquery in HTML:
<script src="https://code.jquery.com/jquery-3.1.1.min.js">
EDIT
Sorry about the id of the button that's button only.
HTML:
<div>Check<input type="checkbox" id="checkbox"></div>
<button id="button">Submit</button>
Your html elements has two similar ids
<div>Check<input type="checkbox" id="**checkbox**"></div>
<button id="**checkbox**">Submit</button>
Change one to checkboxinput and the other to checkboxbutton
Try this maybie:
$(document).ready(function () {
//Try to add your event listener here
}
Simply using your code works fine. Make sure to include jQuery BEFORE your regular JS code. Tried in JSFiddle and do not get any $.ajax() errors besides CORS, of course, because we do not have access to the path (URL for AJAX call).
const checkbox = document.querySelector("#checkbox");
const button = document.querySelector("#button");
button.addEventListener("click", function(e){
var text = "";
if(checkbox.checked === true){
text = "Is Checked";
}
$.ajax({
url: '/update_if_checked/',
data: {'is_checked': text},
type: 'POST'
}).done(function(response){
console.log(response);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Check<input type="checkbox" id="checkbox"></div>
<button id="button">Submit</button>
First of all in your html code, both of the elements i.e. the checkbox and the button have same id. Make it different.
<div>Check<input id="checkbox" type="checkbox"></div>
<button id="button">Click</button>
The script part, I have written it using jquery.
<script>
$(document).ready(function(){
$("#button").click(function(){
var text = "";
if($("#checkbox").is(":checked")){
text = "Is Checked";
}
$.ajax({
type: 'POST',
url: '/update_if_checked/',
contentType: 'application/json',
data: JSON.stringify({"is_checked": text}),
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
}).done(function(response){
console.log(response);
});
});
});
</script>

autofill on click using jquery

caveat: I'm pretty new to ajax/js.
I have the following script which works fine:
<head>
<script class="init" type="text/javascript">
jQuery.noConflict();
(function( $ ) {
$(document).ready(function() {
$.ajax({
url: "http://www.apilayer.net/api/live?access_key=3429d739de582bfe294836892fb7fc8d&format=1&currencies=GBP,EUR,NOK,ZAR,SEK&format=1",
data: {
format: 'json'
},
error: function() {
console.log("error");
},
dataType: 'jsonp',
success: function(data) {
var x=0;
for(var key in data.quotes){
console.log(x);
console.log(data.quotes[key]);
document.forms["myForm"].elements[x].value = +(Math.round(1/data.quotes[key] + "e+4") + "e-4");;
x++;
}
},
type: 'GET'
});
});
})(jQuery);
</script>
</head>
this automatically fills the form elements with exchange rates.
I now am trying to have it only do this when a button on the page is clicked.
I added:
<td>
<p>
<input tabindex="8" type="submit" name="submit" id="onlinerates" value="Use Online Rates"/>
</p>
</td>
and then changed the
$(document).ready(function() {
to
$(document.myForm.onlinerates).click(function() {
the script now does not appear to get called and the forms are not filled in.
I've tried using document.getElementById("onlinerates") , I've tried preceding this line with an additional $(document).ready(function() {
I've tried moving the script to within the form instead of the header. I tried using .focus instead of .click
none of that helped.
any ideas?
thanks in advance.
FIXED (sort of):
thanks to Rory for pointing out the issue with the double submit. i changed the onlinerates to use a checkbox instead of submit button. Also, i had to move the script to the form.
<input tabindex="8" type="checkbox" name="onlinerates" id="onlinerates" value=0/><label for="onlinerates">Use Online Rates</label></p>
<script class="init" type="text/javascript">
jQuery.noConflict();
(function( $ ) {
$('#onlinerates').click(function(e) {
e.preventDefault(); // stop the standard form submission
if($('#onlinerates').attr("checked")==true){
$.ajax({url: "http://www.apilayer.net/api/live?access_key=3429d739de582bfe294836892fb7fc8d&format=1&currencies=GBP,EUR,NOK,ZAR,SEK&format=1",
data: {
format: 'json'
},
error: function() {
console.log("error");
},
dataType: 'jsonp',
success: function(data) {
var x=0;
for(var key in data.quotes){
console.log(x);
console.log(data.quotes[key]);
document.forms["myForm"].elements[x].value = +(Math.round(1/data.quotes[key] + "e+4") + "e-4");;
x++;
}
},
type: 'GET'
});
}
});
})(jQuery);
</script>
The issue is because onlinerates is the id of the button, whereas accessing the element through the form uses the name. That said, it's easier to use jQuery to select the element; $('#onlinerates').
Also note that it's better practice (for accessibility reasons) to hook to the submit event of the parent form instead of the click of the button. Try this:
jQuery.noConflict();
jQuery(function ($) {
$('form').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: "http://www.apilayer.net/api/live?access_key=3429d739de582bfe294836892fb7fc8d&format=1&currencies=GBP,EUR,NOK,ZAR,SEK&format=1",
type: 'GET'
data: {
format: 'json'
},
dataType: 'jsonp',
success: function (data) {
var x = 0;
for (var key in data.quotes) {
document.forms["myForm"].elements[x].value = +(Math.round(1 / data.quotes[key] + "e+4") + "e-4");
x++;
}
},
error: function () {
console.log("error");
}
});
});
})(jQuery);
Try using an event handler for when the form is submitted:
$(document).ready(function() {
// Bind the event handler
$('#myForm').submit(submitRates);
});
function submitRates(e) {
e.preventDefault();
var form = $(this);
// Do AJAX stuff
}

submit form and check for complete without submit button

I need to submit a form and check for its completion without using the submit button.
I managed to submit it trough document.getElementById('logoForm').submit();, but now I need to call a function if the form was successfully submitted.
My form:
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
Submit function:
$("#file1").change(function() {
document.getElementById('logoForm').submit();
//setTimeout(reloadImg, 2000) this was how i called the next function but its not safe at all
alert('submited');
});
The function I want to be called on a successful submit:
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
You need to submit the form using AJAX, otherwise you will have a page reload, rendering all your JS void.
This is how you could do it with jQuery
//bind to submit
$("#logoForm").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
ok i got it working!!
$("document").ready(function(){
$("#file1").change(function() {
//bind to submit
$("#logoForm").submit(function(e)
{
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data: new FormData( this ),
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR)
{
reloadImg();
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("ERROR");
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#logoForm").submit(); //Submit the FORM
});
});
function reloadImg(){
var exists = document.getElementById('AppId').value;
$.post("includes/step_img.php", {id: exists}, function(data){
document.getElementById('imgDiv').innerHTML=data;
});
}
but once i click the file input i have to reload the page to make it work again... any ideas how to work around this?
As Regent said: "Amazing mix of pure JavaScript and jQuery"
if you will be using jquery first of all you will need to include the jquery library, I don't know if you did that.
Also, if you are working with jquery try to use all that jquery provide you to write less code.
Seeing your code I am assuming that you have a form with a input type file into. And when a file is loaded to the field, you want to submit the form. Also the form is targetted to a frame, so I am assuming that you have an iframe element there too.
To know if the form was successfully submitted you can use an ajax request but in this case your are sending files with the form, so you can not use an ajax request.
You can return a javascript code in your response that will be executed from into the iframe so, you can access to the parent element to do that you want
I have modified a little bit your code to integrate jQuery at all.
<html>
<head>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
jQuery("#file1").change(function() {
jQuery('#logoForm').submit();
});
});
</script>
</head>
<body>
<form name="logoForm" id="logoForm" method="POST" target="frame" enctype="multipart/form-data" action="includes/uplLogo.php">
<input type="file" name="file1" id="file1" />
</form>
<iframe name="frame"></iframe>
</body>
</html>
Then in your includes/uplLogo.php you need to return the javascript code to execute a similar of reloadImg()
So, in your includes/uplLogo.php you could have:
<?php
...
Your code here
...
if($all_is_ok) { ?>
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/latest/jquery.js"></script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
var id = jQuery('#AppId', window.parent.document).val();
jQuery.post("includes/step_img.php", {id: id}, function(data) {
jQuery('#imgDiv', window.parent.document).html(data);
});
});
</script>
<?php } ?>
I have not tested it because I just wrote it but I think that works.
Try to comment this line: e.unbind();
Try also to add a log just after the input file changes, and verify if you can see the log in the js console:
...
$("#file1").change(function() {
console.log('input file changed');
//bind to submit
...
for those who will need this in the future the problem was:
$("#file1").change(function()
i just changed that to:
function changed()
and add it to input on onchange method!

Trigger successhandler from ajax call when someone clicks a button

I have an ajax call which grabs data from a php file that connects to an api. I have a success handler that receives the data from the ajax call and then loads a function from the API library. The issue is, I want the user to click a button and then run the function inside of the success call (using the same data from the ajax call earlier).
I believe my ajax call needs to stay inside the window.onload = function(), it doesn't work if I try to run the ajax call when the user clicks the button.
<html>
<head>
<title>hi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script>
function hello(){
alert("hi");
}
function successHandler(data){
screenleap.startSharing('DEFAULT', data, {
nativeDownloadStarting: hello
});
}
window.onload = function() {
$.ajax({
type: "POST",
url: "key.php",
data: '',
success: successHandler,
dataType: "json"
});
};
</script>
</head>
<body>
<input type="submit" value="submit" id="submit">
</body>
</html>
Please let me know how I can do this, any help would be greatly appreciated.
Update:
so I have tried adjusting my code, but for some reason nothing happens anymore when I click the button. It doesn't even shoot out my console.log confirming I had even clicked the button.
<html>
<head>
<title>hi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script>
var dataFromServer;
function hello(){
alert("hi");
}
function successHandler(data){
dataFromServer = data;
console.log("data from server: ")
console.log(dataFromServer);
}
window.onload = function() {
$.ajax({
type: "POST",
url: "key.php",
data: '',
success: successHandler,
dataType: "json"
});
};
$("#submit").click(function(){
console.log('clicked submit');
if(dataFromServer)
{
console.log(datafromserver);
screenleap.startSharing('DEFAULT', dataFromServer, {
nativeDownloadStarting: hello
});
}
});
</script>
</head>
<body>
<input type="submit" value="submit" id="submit">
</body>
</html>
all the best,
-- 24x7
You can store data to some global variable and on button click use same variable.
var dataFromServer;
function successHandler(data){
dataFromServer = data;
}
jQuery("#submit").click(function(){
if(dataFromServer)
{
screenleap.startSharing('DEFAULT', dataFromServer, {
nativeDownloadStarting: hello
});
}
});
Update:
Instead of window.onload use jquery onload function to populate data.
http://jsfiddle.net/ZGggK/
$(function() {
$.ajax({
type: "GET",
url: "https://api.github.com/users/mralexgray",
data: '',
success: successHandler,
dataType: "json"
});
});

overwrite javascript standard submit function behavior

In a huge webapplication I need a workaround for submitting forms.
For overriding a built-in javscript method I tried this example, but I don't even get the alert popup.
My idea for the overwritten submit function is this:
function submit(event) {
var target = event ? event.target : this;
$.ajax({
url: target.action,
data: $('form').serialize(), // &nd someone knows how I can get the serialize() of the form I just clicked?
success: function (data) {
alert('done');
},
error: function (data) {
alert('error (check console log)');
console.log(data);
}
});
//this._submit();
return false;
}
The way the submit is used everywhere is not consistent. Possiblities in the original code:
<button onclick="form.submit">
onclick="calltoFunction();" // where inside the function the submit is called
<button type="submit" // the normal way
I guess my idea is possible, because I overwritten js-functions before. But how should I do it with the submit part.
Any suggestions, ideas, fixes are welcome!
Bind the event to your button like so:
$('#my_button').click(
function(event){
event.preventDefault(); //This will prevent the buttons default submit behavior
...//The rest is up to you!
}
);
function submit(form) {
$.ajax({
url: $(form).attr('action'),
data: $(form).serialize(),
success: function (data) {
alert('done');
},
error: function (data) {
alert('error (check console log)');
console.log(data);
}
});
return false;
}
<form id="my-form" action="/my-action-file.php" method="post" onsubmit="return submit('#my-form');">
<!-- my form content -->
</form>
I suspect you will find this useful:
$('#yourForm').beforeSubmit(function()
{
return doWhateverYouLikeAndReturnTrueToContinueFormSubmition($(this));
});
This will execute doWhateverYouLikeAndReturnTrueToContinueFormSubmition before any other form submission code
You can try this:
function submit(event) {
var target = event ? event.target : this;
$.ajax({
url: target.action,
type: "POST",
data: $('form').serialize(), // &nd someone knows how I can get the serialize() of the form I just clicked?
success: function (data) {
alert('done');
},
error: function (data) {
alert('error (check console log)');
console.log(data);
}
});
//this._submit();
return false;
}

Categories

Resources