enable or disable a button on another page - javascript

How would I be able to click a button on one page, that will enable another button on another page?
my javascript
function enableButton2() {
document.getElementById("button2").disabled = false;
document.getElementById("divbutton").hidden = false;
}
HTML
<input type="button" id="button1" value="button 1" onclick="enableButton2()"/>
<div id="divbutton" hidden>
<input onclick="window.location.href='menu.html'" type="button" id="button2" value="button 2" disabled />
</div>
this code works but will only work if both these buttons are on the same page, what I'm trying to do is separate them into their own pages but still work as intended, that is clicking the first button will make the second button appear.
Thanks in advance!

localStorage would be an efficient approach if you also want to save the user's button choice. localStorage allows you to store a value in the same origin, which means you just have to check whether the value was changed and differentiate which button should be enabled.
For example,
function enableButton2() {
localStorage.enabledButton = '2'
}
Then to check which button to enable, which would be used in the second page
setInterval(() => {
if (localStorage.enabledButton == "1") {
//Enable button 1
}
if (localStorage.enabledButton == "2") {
//Enable button 2
}
})

You can use Broadcast Channel API to communicate between different tabs.
For example, declare the following on both pages:
const bc = new BroadcastChannel('button_disable');
bc.onmessage = function(event){
if(event.data == "hide"){
//hide the buttons
}else if(event.data == "show){
//show the buttons
}
}
Then, if you want to hide/show the button, simply dispatch a message:
bc.postMessage('hide');

Related

How to have multiple submit buttons for a quiz on one page

I'm creating a language quiz and it requires multiple submit buttons on one page through which one can check their answers. Having one submit button works fine. But so far, having multiple submit buttons creates issues where one submit button, when pressed, generates two (if there are 2 questions) of the same answers under both submit buttons. So after one click you will see 4 of the same answers. And only one submit button will be disabled. See scripts below for more info.
Below you'll find the html form for 1 of the quiz questions.
<form id="formId">
<h5>1. I am strong</h5>
<p>Translate the above sentence.</p>
<input type="text" id="q1" /><br><br>
<input type="submit" class="btn btn-outline-primary" id="submitId" value="Check answer" />
</form>
Below you'll find the javascript that gives the answer when submit button is clicked.
<script>
var answers = {
"q1": ["Ik ben sterk"]
};
function markAnswers(){
$("input[type='text']").each(function(){
console.log($.inArray(this.value, answers[this.id]));
if($.inArray(this.value, answers[this.id]) === -1){
$(this).parent().append("<br>The correct answer: Ik ben sterk");
} else {
$(this).parent().append("<br><font style='color:green;'>Correct!</font>");
}
})
}
$("form").on("submit", function(e){
e.preventDefault();
markAnswers();
});
</script>
The script below is to make sure user cannot submit answer again.
<script>
var form = document.getElementById('formId');
var submitButton = document.getElementById('submitId');
form.addEventListener('submit', function() {
// Disable the submit button
submitButton.setAttribute('disabled', 'disabled');
// Change the "Submit" text
submitButton.value = 'Check answer';
}, false);
</script>
Above scripts are just for one question. If I add another question and I copy paste scripts and change the ID's to q2, formId2 and submitId2 it will not work as described earlier. What do I need to change to the scripts in order for this to work? Any suggestion is welcome. Thanks.
Your markAnswers function is looping through all inputs, that's why you're getting the answers for all of them when you click any of the buttons.
You can fix this by changing the id of the forms to be like formId1, formId2 etc., then giving that id to the markAnswers function.
Example:
function markAnswers(id) {
$(`#q${id}`).each(function () {\
if ($.inArray(this.value, answers[this.id]) === -1) {
$(this).parent().append(`<br>The correct answer: ${answers[this.id]}`);
} else {
$(this).parent().append("<br><font style='color:green;'>Correct!</font>");
}
});
}
$("form").on("submit", function (e) {
e.preventDefault();
const id = e.target.id.replace("formId", "")
markAnswers(id);
});
Additionally, you can disable the button in the same submit event as well:
$("form").on("submit", function (e) {
...
$(`#submitId${id}`).each(function () {
this.setAttribute('disabled', true);
this.value = "Check answers"
})
});
Here's a working example: Codesandbox

Show message when radio button selected

I am trying to get the following to work without much success
$(document).ready(function()
{
$('#shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a').click(function()
{
alert("Please ensure you have selected the correct option");
});
});
</script>
Using inspect on Chrome, I looked for the ID for the radio button and found shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a but even so, when I save the javascript and load the page and click the radio button, no message is displayed.
The code I used to find the ID in inspect was as follows:
<input name="shippingOptionIds.5ed62ea40135a" class="form-checklist-checkbox optimizedCheckout-form-checklist-checkbox" id="shippingOptionRadio-5ed62ea40135a-7dac01c2c834210be865275f0700a45a" type="radio" value="7dac01c2c834210be865275f0700a45a">
you have to add an event (type input not click) to the radio and then add condition if the input.checked === true then show message
// select radio input
const input = document.getElementById('input');
// add event on input
input.addEventListener('input', () => {
if (input.checked) {
alert('this is a message!');
}
});
<input type="radio" id="input">

Detect if a form has unsaved changes before letting user focus to a different form

Is there any way to detect if user has changed from the content of one section to another in the same page?
I have a page with multiple buttons (1 form/section is opened once you click on each button), when they all are closed i can detect user is changing to another form using a click event on the button element.
My sections in this case are forms loaded when you click on every button in the page. pure jquery to load the content via ajax inside them.
The problem is when all sections are open. I need to detect when user has changed between the content of one section to another.
I have to warn the user about saving your changes in a previous form because system has a timeout for inactivity, if user didnt save his data, it is lost once user gets logout from application.
the event prompt the user to save the data of the previous form.
The only way I can think of doing this is using a mouse event, but this can sometimes be a frustrating experience.
Solved
Thanks DelightedD0D, I ended up doing this
This var saves the previous form number
var pendingForm = [];
Events which fire a possible warning
//Pressing tab is reviewed if there are unsaved changes in the previous section.
$(document).keyup(function(eventTab) {
var code = eventTab.keyCode || eventTab.which;
if (code === 9) {
checkPrevious(eventTab);
}
});
//Clicking is reviewed if there are unsaved changes in the previous section
$(document).mouseup(function(eventMouse) {
checkPrevious(eventMouse);
});
Here we establish when a form is pending or has changed
$('.formSection').on('keyup change', 'input, select, textarea', function() {
$(this).closest('.formSection').addClass('pending');
//We get the number of the form by the id
var numForm = $(this).closest('.formSection').attr('id').substr(11, 2);
if ( $.inArray(numForm , pendingForm) == -1 ) {
pendingForm.push(numForm);
}
});
//I have my own functions to save and cancel, but the idea is Save the data
//then find the formSection from previous form, remove pending class and
//remove number form from array of pending sections
$('.save').click(function() {
//save data...
var numForm = pendingForm.pop();
$('#formSection'+numForm).removeClass('pending');
});
And this function checks when user move to another form
function checkPrevious(e) {
var $target = $(e.target);
//If it is clicked somewhere within a form or a button that opens a section
if ($target.closest('.formSection').length || $target.hasClass('btnSection')) {
var isDisabled = false;
if (pendingForm.length > 0) {
prevForm = pendingForm.slice(-1).pop();
//Every submit form button has an id with a consecutive number in my case
//If disabled, that means it has errors in validation (Bootstrap)
//**I have to improve this verification yet**
isDisabled = $('#submitForm' + prevForm).is(':disabled');
}
// get any forms with changes that are not the current form or do not contain the clicked element
var $otherFormsWithChanges = $('.pending').filter(function() {
var $this = $(this);
return $this.hasClass('pending') && (!$this.is($target) || $this.has($target).length != 0);
});
// if another form has a change, thow up a message
// allow the user to go back to the form or ignore the changes
if ($otherFormsWithChanges.length > 0 && $otherFormsWithChanges.has($target).length === 0 ) {
var modalPrev = $('#modalPrev');
if ( isDisabled == false ) {
//If everything is ok, we can save
modalPrev.find('.modal-content .modal-body').html("<p>You have unsaved changes. Do you want to save previous form?</p>");
modalPrev.find(".btnSave").removeClass('hide');
} else {
modalPrev.find('.modal-content .modal-body').html("<p>You have some errors in your previous form.</p>");
modalPrev.find(".btnSave").addClass('hide');
}
$('#modalPrev').modal('show');
}
}
}
I show a modal instead of an alert with two buttons [Save] and [Cancel], every one has a function which do a save or close but both remove the previous section from the array to not be considered anymore.
You could do this by setting a class on the form when input values change then listening for clicks on the document and checking if a form other than the one being interacted with has changes. If one does, present a message to the user.
This should work:
Note that you dont have to use forms, just add the track-changes class to some parent of the inputs you have grouped together
jsFiddle example
$(document).mouseup(function(e) {
var $target = $(e.target);
// get any forms with changes that are not the current form or do not contain the clicked element
var $otherFormsWithChanges = $('.pending').filter(function() {
var $this=$(this);
return $this.hasClass('pending') && (!$this.is($target) || $this.has($target).length !=0);
});
// if another form has a change, thow up a message
// allow the user to go back to the form or ignore the changes
if ($otherFormsWithChanges.length > 0 && $otherFormsWithChanges.has($target).length===0 ) {
var c = confirm("You have unsaved changes.\n\n Click cancel to go back to the unsaved form or OK to ignore");
c ? $otherFormsWithChanges.removeClass('pending') : $otherFormsWithChanges.find('input, select, textarea').focus();
}
});
$('.track-changes').on('keyup change', 'input, select, textarea', function() {
$(this).closest('.track-changes').addClass('pending');
});
$('.save').click(function() {
// save data...
$(this).closest('.track-changes').removeClass('pending');
});
form{
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>form 1</h4>
<form class="track-changes" has-changes="false" action="">
<input type="text">
some text
<br>
<button type="button" class="save">Save</button>
</form>
<h4>form 2</h4>
<form class="track-changes" has-changes="false" action="">
<input type="text">
some text
<br>
<button type="button" class="save">Save</button>
</form>
<h4>form 3</h4>
<form class="track-changes" has-changes="false" action="">
<input type="text">
some text
<br>
<button type="button" class="save">Save</button>
</form>

Trigger functions from checkbox on click by clicking on a button

I have a couple of checkboxes and a button. When I click on checkbox - function is triggered. This is the desired behavior but I want to trigger it by clicking on the button. I want to have the possibility to first select checkboxes (I tried with return false and event.preventDefault but these completely switch the selection off) and then by clicking the button - trigger functions from checkboxes. Here is a link to jsfiddle:
http://jsfiddle.net/j93k2xns/6/
So for instance: I can select 3 checkboxes (nothing should happen) and after I click the button - three alerts should appear.
The code:
HTML:
<input type="checkbox" name='check[]' id="first">first</input>
<input type="checkbox" name='check[]'>second</input>
<input type="checkbox" name='check[]'>third</input>
<input type="checkbox" name='check[]'>fourth</input>
<input type="button" value="validate" id="val-button">
JS:
var check_state;
$(document).on('click','input[name="check[]"]', function(e){
if(check_state === true) {
alert('a');
} else {
return false;
}
});
$(document).on('click','#val-button', function(){
check_state = true;
});
There are a few interpretations to his question. If I'm reading it correctly, he wants to bind an arbitrary function to the checkboxes. Clicking the button should fire this event. This is how you can achieve that using custom events in jQuery:
$(function () {
$("input[name='check[]']").bind("myCustomButtonClick", function() {
if(this.checked) {
alert('a');
}
});
})
$(document).on('click','#val-button', function(){
$("input[name='check[]']").trigger("myCustomButtonClick");
});
And the associated jsfiddle: http://jsfiddle.net/3yf7ymos/
$(document).on('click','#val-button', function(){
$( 'input[name="check[]"]' ).each(function( index ) {
if($(this).is(':checked')) {
alert("a");
return true;
}
});
});
If you want to do something when the user checks a checkbox, add an event listener:
$('input[type="checkbox"]').click(function() {
if ($(this).is(':checked')) {
// do something
}
});
If the idea is run a couple of functions after the inputs are checked by clicking on a button:
function myFunction() {
if ($('input[id="something"]:checked').length == 0) {
// do something
} else if ($('input[id="something_2"]:checked').length == 0) {
// do something
}
//and so on..
}
$('#val-button').click(function() {
myFunction();
});
I have a similar inquiry. I have a number of check boxes. Each checkbox is linked to a different URL that opens a PDF form. I want my team to be able to select which forms they need by ticking the checkbox. Once they have done that, I would like a button to trigger the opening of each form based on which check box is checked. I have it so the checkbox upon being checked opens the form right away but it is very distracting. Its preferable they all get opened at once by a "button". Help. I am quite new to JavaScript so may need additional clarity.

How to prevent second click on radio button if it is already checked so that javascript event can be prevented

How to prevent second click on radio button if it is already checked so that javascript event can be prevented.
As I am doing many things onclick of radio button
<input name="EnumEvent" type="radio" value="Open" onclick="show_event()"/>
javascript
function show_event()
{
document.getElementById("radio-btns-div1").style.display="block";
document.getElementById('invited').style.display="none";
document.getElementById('invited').value = '';
document.getElementById('invite_1').value='';
}
You could use change event instead of click
<input name="EnumEvent" type="radio" value="Open" onchange="show_event()"/>
DEMO
Add the disabled attribute
function show_event()
{
document.getElementByName("EnumEvent").setAttribute("disabled", "disabled");
...
}
Don't forget to remove the attribute when/if you want the user to be allowed to select another option.
var clicked = false;
$('input:radio.yourclass').click(function(event){
if (clicked){
event.preventDefault();
}
clicked = true;
});
function Clicked() {
if (document.getElementById("radio-btns-div1").checked) {
document.getElementById("radio-btns-div1").disabled = true;
}
Refer to Disable radio button according to selected choice

Categories

Resources