How to Make a button disabled until a hyperlink is clicked - javascript

I'm working on a project where a button needs to be disabled until a hyperlink is clicked and a checkbox is checked. I currently have the checkbox part down using jQuery:
$('#tc-checkbox').change(function(){
if($(this).is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
But I also need to set it up so the class of tc-disable is still on the button until an anchor tag is clicked as well. I've never really done this before where a link needs to be clicked before removing a class and couldn't find what I was looking for as I was Googling for an answer.

Hope the code below helps. I also added console out put so you can track the value. Another option is use custom attribute on link element instead of javascript variable to track if the link is clicked.
var enableLinkClicked = false;
$('#tc-link').click(function() {
enableLinkClicked = true;
console.log("link clicked\ncheckbox value: " + $($('#tc-checkbox')).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($('#tc-checkbox').is(":checked")) {
$('#tc-btn').removeClass('tc-disable');
}
});
$('#tc-checkbox').change(function() {
console.log("checkbox clicked\ncheckbox value: " + $(this).is(":checked"));
console.log("link clicked: " + enableLinkClicked);
if ($(this).is(":checked") && enableLinkClicked) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
#tc-btn.tc-disable {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button id="tc-btn">My Button</button>
<br/>
<a id="tc-link" href="javascript:void(0);">Link to enable button</a>
<br/>
<input type="checkbox" id="tc-checkbox" />

If the page is refreshing or taking you to a different page when you click the hyperlink, you will want to look into sessionStorage. When the hyperlink is clicked you will want to set a sessionStorage variable and when the page loads you want to check that variable to see if it is populated. If the variable is populated, enable the button.
Set the variable.
sessionStorage.setItem('key', 'value');
Get the variable
var data = sessionStorage.getItem('key');
If you need to re-disable the button you can clear the session storage and reapply the disabled class.
sessionStorage.clear();
You can learn more about session storage here.
If the page does not refresh you could just set an attr on the link when it is clicked like so.
$('#tc-link').on('click', function() {
$(this).attr('clicked', 'true');
});
Then when the checkbox is checked you can check this in your function.
$('#tc-checkbox').change(function(){
if($(this).is(":checked") && $('#tc-link').hasAttr('clicked')) {
$('#tc-btn').removeClass('tc-disable');
} else {
$('#tc-btn').addClass('tc-disable');
}
});
These are just some solutions I could think of off the top of my head. Hope this helps.

Maybe this is better for you. First you make an .on('click' event listener on the anchor element, then, if the checkbox is checked enable the button. I added the else statement to disable the button if a user clicks the link and the checkbox is not set for an example. In this example you don't need the classes.
But if you needed to keep the the classes then you would replace the $('#tc-btn').prop('disabled', false); with $('#tc-btn').addClass() or .removeClass()
$( '#theLink' ).on( 'click', function(e)
{
e.preventDefault();
if($('#tc-checkbox').is(':checked'))
{
$('#tc-btn').prop('disabled', false);
$('#tc-btn').val('Currently enabled');
}
else
{
$('#tc-btn').val('Currently disabled');
$('#tc-btn').prop('disabled', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="tc-checkbox" />
This link will enable the button
<input type="button" id="tc-btn" value="Currently disabled" disabled="disabled"/>

Here a much more simple solution and it handles the state of the button if they uncheck the "I Accept" checkbox. It is pretty easy to implement. I just used Bootstrap to pretty up the example.
//Handles the anchor click
$("#anchor").click(() => {
$("#anchor").addClass("visited");
$("#acceptBtn").prop("disabled", buttonState());
});
//Handles the checkbox check
$("#checkBx").on("change", () => {
$("#acceptBtn").prop("disabled", buttonState());
});
//Function that checks the state and decides if the button should be enabled.
buttonState = () => {
let anchorClicked = $("#anchor").hasClass("visited");
let checkboxChecked = $("#checkBx").prop("checked") === true;
return !(anchorClicked && checkboxChecked);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/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-md-12">
View Terms
</div>
</div>
<div class="row">
<div class="col-md-12">
<label class="form-check-label">
<input class="form-check-input" id="checkBx" type="checkbox" value="">
I accept the terms
</label>
</div>
</div>
<div class="row">
<div class="col-md-12">
<button id="acceptBtn" class="btn btn-success" disabled="disabled">
Ok
</button>
</div>
</div>
</div>

A one-liner solution using Javascript could be:
<input type="submit" id="test" name="test" required disabled="disabled">
<label for="test">I clicked the <a target="_blank" href="https://stackoverflow.com" onclick="document.getElementById('test').disabled=false">link</a>.</label>
Change the type "submit" to "button" or "checkbox" accordingly to your needs.

Related

When click on button, show divs with checked checkbox using JQuery

I want to use JQuery on my Coldfusion application for showing/hiding div elements with checkbox checked/unchecked within the div.
Basically, in a view I show multiple divs elements, every div have also more divs inside, one of these internal divs contains an input type checkbox that could come checked or unchecked.
I also have three buttons in that view 'Active, Inactive, All'. When clicking on Active I want to show all div elements with checkbox checked, not showing the unchecked, and the other way around when clicking on Inactive.
<div class="btn-group ">
<button id="actives" type="button">Actives</button>
<button id="inactives" type="button">Inactives</button>
<button id="all" type="button">All</button>
</div>
<div id="apiDiv">
<cfloop array="#apis#" index="api">
<div class="card card-found">
<div class="card-header">
<cfif Len(api.iconClass)>
<i class="fa fa-fw #api.iconClass#"></i>
</cfif>
#structKeyExists( api, "name" ) ? api.name : api.id#
</div>
<div class="card-body">
<p>#api.description#</p>
</div>
<div class="card-button">
<input class="#inputClass# ace ace-switch ace-switch-3" name="#inputName#" id="#inputId#-#api.id#" type="checkbox" value="#HtmlEditFormat( api.id )#"<cfif ListFindNoCase( value, api.id )> checked="checked"</cfif> tabindex="#getNextTabIndex()#">
<span class="lbl"></span>
</div>
</div>
</cfloop>
</div>
I´m not an expert at all with JQuery. The only thing I have done is what follows and I do not know whether if is a good beggining or not:
$("#actives").click(function (e) {
$("#apiDiv .card").filter(function() {
<!--- code here --->
});
});
Someone please that can help me with it? Thanks a lot in advance!
After your CF code executes, it will generate a .card for each loop iteration of your apis array. So you jQuery code will need a click handler for the #actives button and that will loop through each() iteration of the checkboxes to determine the checked/unchecked state. At that point find the closest() ancestor .card and show()/hide() the .card depending upon the checkbox state.
$("#actives").click(function (e) {
$('input[type=checkbox]').each(function() {
if (this.checked) {
$(this).closest(".card").show();
} else {
$(this).closest(".card").hide();
}
});
});
If you want to do it with jQuery code:
$('#actives').click(function(){
$('#apiDiv').show();
});
Working Fiddle
The code you are probably looking for is in these event handlers for your buttons:
function activesHandler() {
jQuery(".card-button > input:checked").parents(".card.card-found").show();
jQuery(".card-button > input:not(:checked)").parents(".card.card-found").hide();
}
function inactivesHandler() {
jQuery(".card-button > input:checked").parents(".card.card-found").hide();
jQuery(".card-button > input:not(:checked)").parents(".card.card-found").show();
}
function allHandler() {
jQuery(".card.card-found").show();
}
jQuery("#actives").click(activesHandler);
jQuery("#inactives").click(inactivesHandler);
jQuery("#all").click(allHandler);
I reproduced some of your ColdFusion by replacing it with JavaScript and provided a demonstration of the above event handlers in this JSFiddle.
Call the checkbox by its id and when it's checked, write a function to display the divs you want to display:
<input type="checkbox" id="check">
$document.getElementById("check").onclick = function(){
$document.getElementById("div_name").style.display="block"; // block displays the div.
}

jQuery checked attribute not seen when using html()

I have a specific problem where I need to render a html string from the server and show it to the user. The user then clicks the checkboxes and I transform it back into a html string and save it on the server.
Problem is after the user clicks the checkboxes, the transformed HTML string does not contain the checked attribute.
Here is a snippet
$("button").on("click", function(){
console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox"/>
<button> Test </button>
</div>
But when I manually click the checkbox and click the button and examine the console log, the checked attribute inside the HTML string is not seen.
How can I solve this problem?
Set checked attribute manually by .attr('checked', 'checked') on change:
$("button").on("click", function() {
console.log($("#container").html());
});
$('#checkbox').change(function() {
if ($(this).is(':checked')) {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox" />
<button> Test </button>
</div>
When you check a checkbox manually, the checked HTML attribute doesn't change.
You can change it yourself by selecting every checked checkbox and manually updating them with the jQuery :checked selector:
$('#container input[type="checkbox"]:checked').attr('checked','true');
$("button").on("click", function() {
$('#container input[type="checkbox"]:checked').attr('checked','true');
console.log($("#container").html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="checkbox" id="checkbox" />
<button> Test </button>
</div>

When checkbox is checked show hidden button and hide the visible button

I am a beginner in javascript, hopefully you can help me with this problem..
I have 2 buttons in html form and 1 checkbox, 1 button should be hidden and the other is visible. My problem is how to show the hidden button and hide the visible button at the same time when the checkbox is checked..
I know how to hide/show the button flip-ch1 but I can't do it to other button.
I have a script here:
$(document).ready(function() {
$('#flip-ch1').hide();
$('#radio').mouseup(function() {
$('#flip-ch1').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="radio" id="radio">
<button class="btn_style" id="ch1">Add</button>
<button class="btn_style" id="flip-ch1">Add</button>
</div>
Toggle them both:
<script type="text/javascript">
$(document).ready(function(){
$('#flip-ch1').hide();
$('#radio').mouseup(function () {
$('#ch1').toggle();
$('#flip-ch1').toggle();
});
});
</script>
Just add this line:
$('#ch1').toggle();
So, the complete js code would be:
$(document).ready(function () {
$('#flip-ch1').hide();
$('#radio').mouseup(function () {
$('#flip-ch1').toggle();
$('#ch1').toggle();
});
});
Do not get confused by the .hide(). It is used to hide one of the buttons only in the beginning. No need to use afterwards. The reason that you do not see any changes after toggling the checkbox, is that when first button is hidden the second one gets its place, the place does not remain empty. You can spot all this that I mentioned on inspect element of any major browser.
Try $('#radio').is(':checked') as below
$(document).ready(function() {
$('#flip-ch1').hide();
$('#radio').on('change', function() {
if ($('#radio').is(':checked')) {
$('#flip-ch1').show();
$('#ch1').hide();
} else {
$('#flip-ch1').hide();
$('#ch1').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" name="radio" id="radio">
<button class="btn_style" id="ch1">Add 1</button>
<button class="btn_style" id="flip-ch1">Add 2</button>
</div>

Run server-side script when jQuery Switch button is switched

I have the following jquery plugin on my client side which gives me a on/off switch. I need "off" and "on" to trigger different server side scripts. I know how this can be achieved with a regular "on-click" button, but not with a switch button.
Here is what's in client-side:
<div id="second_div">
<form>
<div style="float: left; width: 50%;">
<p style="padding-bottom: 13px;"><em>Checkbox</em></p>
<p><input type="checkbox" name="check-1" value="4" class="lcs_check" autocomplete="off" /></p>
</div>
</form>
<div style=" clear: both;"></div>
</div>
<div id="third_div">
<em style="color: #777; font-size: 14px;">Check your browser console to see triggered events</em>
</div>
<p></p>
I would like "off" to trigger one function "google.script.run.loggOff();
I would like "on" to trigger another function "google.script.run.loggOn();
This is usually how i do it with an 'onclick button':
Client Side (on-click button):
<button type="button" onclick="google.script.run.createDoc();">Create Google Doc</button>
<script>
google.script.run.createDoc();
</script>
Server Side (on-click button):
function createDoc() {
var copyDoc = DocumentApp.openById(copyId);
copyDoc.saveAndClose();
}
Maybe I'm misunderstanding the question, but if you want to add click functions the on and off you can do something like this.
//off
$('.lcs_check').click(function() {
$('.lcs_check').attr('id','loggOff');
google.script.run.loggOff();
});
//on
$('.lcs_check #loggOff').click(function() {
$('.lcs_check #loggOff').removeAttr('id','loggOff');
google.script.run.loggOn();
});
This plugin is LC-switch, i found the github page and a more detailled demo page.
In the demo page there is a Event section, there is 3 events for what you trying to accomplish.
// triggered each time a field changes status
$('body').delegate('.lcs_check', 'lcs-statuschange', function() {
var status = ($(this).is(':checked')) ? 'checked' : 'unchecked';
console.log('field changed status: '+ status );
});
// triggered each time a field is checked
$('body').delegate('.lcs_check', 'lcs-on', function() {
console.log('field is checked');
});
// triggered each time a field is unchecked
$('body').delegate('.lcs_check', 'lcs-off', function() {
console.log('field is unchecked');
});
But it look like each of this event are called after state has changed. I didn't find a way to have click information before state is changed.

I want to disable link button after clicking of it and other enable. toggle enable/ disable between both link buttons using javascript

I want to disable link button after clicking of it & other enable. toggle enable/ disable between both link buttons using javascript
<a id="a1" href="page1.aspx">One</a><a id="a2" href="page2.aspx">Two</a>
Simple, just add listeners to the onclick events on both links, that disable the link in question and enable the other one.
Something like
document.getElementById('a1').onclick = function() {
document.getElementById('a1').disabled = true;
document.getElementById('a2').disabled = false;
};
document.getElementById('a2').onclick = function() {
document.getElementById('a2').disabled = true;
document.getElementById('a1').disabled = false;
};
Of course if you're going to be extending this to multiple buttons then you could easily abstract the above out to registration methods, looping over arrays of buttons etc. (possibly those that implement a particular class rather than explicitly specifying the array).
The simplest way is to hide the link rather than to make it disabled.
You can use this code to hide the link after click on it.
Its tested code & it worked perfect for me. :-)
<script type="text/javascript">
onclick = function() {
var chk= document.getElementById('myElementId');
chk.style.display="none";
};
</script>
To disable a LINK rather than a BUTTON, the only thing you can do apart from hiding it is to set it not to go anywhere.
onclick="this.href='javascript: void(0)';"
Your question can have any one of the following 3 possible scenario. Choose whichever suites your problem.
Case1) A catch in your question is that since they are links pointing to page1.aspx and page2.aspx respectively once you click on a link a new page loads in the browser. So the effect you want to achieve doesn't really matter.
Case 2) If, you have both the links 'One' and 'Two' on each of aspx pages then you can as well hardcode the disabling of the link pointing to itself. (Or as well not have the link at all).
Case 3) If you have a frame to display the links 'One', 'Two' and you have a another frame to load content of both links then your question has a meaning disabling the other link. Here is the code for the same.
<html>
<a id="a1" href="javascript:void(0)" onclick="toggle(objA1,objA2,'page1.aspx')">One</a>
<a id="a2" href="javascript:void(0)" onclick="toggle(objA2,objA1,'page2.aspx')">Two</a>
<br><iframe id="ifrm" src=""></iframe>
<script>
var objA1 = document.getElementById('a1');
var objA2 = document.getElementById('a2');
// d=element to disable, e=element to enable
function toggle(d,e,link)
{
//if already disabled do nothing(don't follow url)
if(d.disabled) return;
//enable/disable
d.disabled = true;
d.style.cursor = 'default';
e.disabled = false;
e.style.cursor = 'hand';
//follow link
ifrm.src = link;
}
</script>
</html>
You can access and set the "disabled" attribute like this:
if(somebutton.disabled == true){
somebutton.disabled = false;
}
I recommend using a JavaScript framework like jQuery.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<style type="text/css">
.submit{
padding:8px;
border:1px solid blue;
}
</style>
</head>
<body>
<h1>Disabled submit form button after clicked with jQuery</h1>
<form action="#">
<p>
I'm a form ~
</p>
<input type="submit" value="Submit"></input>
<button>Enable Submit Button</button>
</form>
<script type="text/javascript">
$('input:submit').click(function(){
$('p').text("Form submiting.....").addClass('submit');
$('input:submit').attr("disabled", true);
});
$('button').click(function(){
$('p').text("I'm a form ~").removeClass('submit');
$('input:submit').attr("disabled", false);
});
</script>
</body>
</html>
<script type="text/javascript">
function validateForm(formObj) {
if (formObj.username.value=='') {
alert('Please enter a username');
return false;
}
formObj.submitButton.disabled = true;
formObj.submitButton.value = 'Please Wait...';
return true;
}
</script>
<form name="frmTest" action="" method="post" onsubmit="return validateForm(this);">
Username: <input type="text" name="username" value="" /><br />
<input type="submit" name="submitButton" value="Submit" />
</form> ​​​​​​

Categories

Resources