block the button in html code on a certain conditions using JS - javascript

I need the following - if LABEL value is Admin button "CHANGE" must be disabled without possibility to SUBMIT and if the label value is any other then SUBMIT is possible and button is enabled. I made the following code, but for some reason script work only for the second click, for the first click SUBMIT still works
<h3>ACCESS RIGHTS MANAGEMENT</h3>
<h5 style="color: gray"> User selected:</h5>
<h5 style="color: red">{{ context.user_name }}</h5>
<h5 style="color: gray"> Current role:</h5>
<h5 id="roll" style="color: red">{{ context.user_role }}</h5>
<h6 style="color: black">List of roles</h5>
<h7 style="color: grey">
{% for role in context.all_roles %}
<label>{{ role.get('name') }}</label>
{% endfor %}
</h7>
<form method="post" action="/auth/editor/ {{ context.user_id }}"
class="row mt-3 text- center">
<div class="col-auto">
<div class="form-floating my-box">
<input type="text" class="form-control" id="floatingInput" name="role"
placeholder="Input a new role" required>
<label for="floatingInput">New Role:</label>
</div>
</div>
<div class="col-auto">
<input id="button" onclick='disable()' display="false" type="submit"
value="CHANGE" style="height: 58px" class="btn btn-sm btn-primary"/>
<script type = "text/javascript">
function disable () {
let adm = document.getElementById("roll").textContent;
if (adm == "Admin") {
const button = document.querySelector('#button');
const disableButton = () => {
button.disabled = true;
};
button.addEventListener('click', disableButton);
document.getElementById('warning').innerHTML = 'WARNING: You are cannot
edit Admin';
} else {
const button = document.querySelector('#button');
const disableButton = () => {
button.disabled = false;
};
}
}
</script>
</div>
<div class="col-auto">
<label id="warning" style="color: red"></label>
</div>
</form>
THanks!

You are running your disable function only after the first click, you could try running it on page load to evaluate if it's going to be disabled on load.
For that run the function after declaring it:
function disable() {
let adm = document.getElementById("roll").textContent;
if (adm == "Admin") {
const button = document.querySelector('#button');
const disableButton = () => {
button.disabled = true;
};
button.addEventListener('click', disableButton);
document.getElementById('warning').innerHTML = 'WARNING: You are cannot edit Admin';
} else {
const button = document.querySelector('#button');
const disableButton = () => {
button.disabled = false;
};
}
}
// Add this
disable();

Related

Subscription button with data validation

What the script does is hide the input element and show the "thanks message".
But prior to this I need it to validate if input emailfield is validated, and show the "thanks message" only if that happens.
Thanks!
var nextStep = document.querySelector('#nextStep');
nextStep.addEventListener('click', function(e) {
e.preventDefault()
// Hide first view
document.getElementById('my_form').style.display = 'none';
// Show thank you message element
document.getElementById('thank_you').style.display = 'block';
});
<form class="row row-cols-lg-auto g-2 align-items-center justify-content-end">
<div class="col-12" id="my_form">
<input id="emailfield" type="email" class="form-control" placeholder="Ingresa tu Email" required="required">
</div>
<div class="col-12" id="thank_you" style="display: none;">
Gracias por subscribirse!
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary-soft m-0" name="subscribirse" id="nextStep">Subscribirse</button>
</div>
</form>
var nextStep = document.querySelector('#nextStep');
nextStep.addEventListener('click', function (e) {
e.preventDefault()
let inputEmail = document.querySelector('#emailfield')
if (/.*\#.*\..*/.test(inputEmail.value)) {
// validation passed
// Hide first view
document.getElementById('my_form').style.display = 'none';
// Show thank you message element
document.getElementById('thank_you').style.display = 'block';
} else {
// validation not passed
}
});
Instead of this regexp you can use any that you want

How do I trigger validation on html if I don't have a form

How do I trigger validation on html if I don't have a form
i.e here i have set the required attribute, but when I click on the Save button the field doesnt get the red outline, I assume this is because instead of SaveButton invoking a form it is calling Javascript, is there a call I can make in the Javascript to trigger the validation ?
function cloneProfile() {
var newProfileName = document.getElementById("clone_profile").value;
var origProfile = profile.options[profile.selectedIndex].value;
var index = profile.selectedIndex;
if (newProfileName.length == 0) {
return;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/start.clone_profile', true);
xhr.setRequestHeader("Content-type", "text/plain");
xhr.send(origProfile + "\0" + newProfileName);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (xhr.responseText.startsWith('ok')) {
document.getElementById("clone_profile").value = "";
$('#cloneprofilemodal').modal('hide');
var newProfile = document.createElement("option");
newProfile.text = newProfileName;
newProfile.value = xhr.responseText.substring(3);
profile.add(newProfile);
profile.selectedIndex = profile.length - 1;
//TODO is not ordered alphabetically, means wrong one selected but also Default not put at start
removeAllAlerts(document.getElementById("cloneprofilemodalAlerts"));
}
}
};
}
<div class="modal-body">
<div class="form-group">
<label for="clone_profile" id="clone_profilelabel">
Please enter name for new Profile
</label>
<input type="text" id="clone_profile" name="clone_profile" aria-describedby="clone_profilelabel" class="largeinputfield form-control" required>
</div>
<div id="cloneprofilemodalAlerts">
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-outline-secondary">
Cancel
</button>
<button onclick="cloneProfile();" class="btn btn-outline-primary">
Save
</button>
</div>
You could just disable the save button until the input has a greater length than 0, using an event listener:
function cloneProfile() {
// your code
}
const button = document.getElementById('save-button')
const input = document.getElementById('clone_profile')
input.addEventListener('input', e => button.disabled = e.target.value.length === 0)
<div class="modal-body">
<div class="form-group">
<label for="clone_profile" id="clone_profilelabel">
Please enter name for new Profile
</label>
<input type="text" id="clone_profile" name="clone_profile" aria-describedby="clone_profilelabel" class="largeinputfield form-control" required>
</div>
<div id="cloneprofilemodalAlerts">
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-outline-secondary">
Cancel
</button>
<button disabled id="save-button" onclick="cloneProfile();" class="btn btn-outline-primary">
Save
</button>
</div>
Note, I added an id to your button, as well as the disabled property.
input.addEventListener('input', e => button.disabled = e.target.value.length === 0)
We add an event listener to the input, declared earlier
we listen for the 'input' evnet (or oninput), and go on to provide a callback function
We take the passed parameter, e, which is the event.
We can access the button from earlier, and its disabled property, using button.disabled
We access the input element itself using e.target, and then the value of that input using .value, and then the length, using .length
Since we are checking it is equal to 0, the statement will evaluate to true or false
Here is what I belive you were looking for, with everything gathered from the comments
function cloneProfile() {
console.log("run your code here")
}
const button = document.getElementById('save-button')
const input = document.getElementById('clone_profile')
input.addEventListener('input', e => button.disabled = !(e.target.validity.valid))
input:invalid {
border: 2px dashed red;
}
input:valid {
border: 2px solid black;
}
div {
margin-bottom: 10px;
}
<div class="modal-body">
<div class="form-group">
<label for="clone_profile" id="clone_profilelabel">
Please enter name for new Profile
</label>
<input type="text" id="clone_profile" name="clone_profile" aria-describedby="clone_profilelabel" class="largeinputfield form-control" required>
</div>
<div id="cloneprofilemodalAlerts">
</div>
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-outline-secondary">
Cancel
</button>
<button disabled id="save-button" onclick="cloneProfile();" class="btn btn-outline-primary">
Save
</button>
</div>

Onclick html call for JavaScript function not working in Safari

I am trying to call a function in my javascript file from an onclick event in html. This code works perfectly in Google Chrome but does not work in Safari as it redirects to the same page and empties the form, without redirecting to the home page of my website.
Here is my HTML code:
<!-- Login or subscribe form-->
<div class="py-5">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="card text-white p-5 bg-primary signUpBoxStyle">
<div class="card-body">
<h1 class="mb-4">Effettua il login o iscriviti</h1>
<form>
<div class="form-group"> <label>Indirizzo email</label>
<input type="email" class="form-control" placeholder="Inserisci email" id="email"> </div>
<div class="form-group"> <label>Password</label>
<input type="password" class="form-control" placeholder="Password" id="password"> </div>
<input type="button" class="btn btn-light text-primary btn-sm" value="Accedi" onclick="loginFunction()">
<input type="button" class="btn btn-light text-primary btn-sm" value="Crea un Account" onclick="signupFunction()"> </form>
</div>
</div>
</div>
</div>
</div>
</div>
And this is my JavaScript
function loginFunction() {
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
})
};
You might need to tell the browser not to carry out the default behavior of that element via preventDefault(). This SO answer give a little more detail.
Having an if statement to check the attribute is not that scalable but it may be possible that you pass the function call as a parameter.
let buttons = document.querySelectorAll('input[type=button]')
buttons.forEach(button => {
button.addEventListener('click', e => {
let func = e.target.getAttribute('data-call')
if (func === 'login') {
loginFunction()
} else if (func === 'signup') {
signupFunction()
}
})
})
let loginFunction = () => {
console.log('loginFunction')
}
let signupFunction = () => {
console.log('signupFunction')
}
<form>
<input type="button" value="Accedi" data-call="login">
<input type="button" value="Crea un Account" data-call="signup">
</form>

Javascript Not working when trying to hide and display form in Ruby

Iam trying to create a button that displays a form when a user clicks on it. I have tried checking through my code and i have not found any error but the button does not work. Please Help!
//load turbo scripts
document.addEventListener('turbolinks:load', function() {
//assign elements in to variables
const openProjectButton = document.getElementById('new-project-button')
const projectPopover = document.getElementById('new-project-popover')
//check if elements exist
if (openProjectButton && projectPopover) {
//attach listener
openProjectButton.addEventListener('click', function() {
//if the popover class contains is-hidden remove it else return nill.
return projectPopover.classList.contains('is-hidden') ? projectPopover.classList.remove('is-hidden') : null
}, false)
//attach listener to cancel button
const cancelProjectpopover = document.getElementById('cancel-project-popover')
cancelProjectpopover.addEventListener('click', function() {
//add back is-hidden
return projectPopover.classList.add('is-hidden')
}, false)
}
})
<div class="col-md-1 mr-auto">
<button id="new-project-button" class="btn btn-primary mr-auto">New</button>
<div id="new-project-popover" class="project-popover is-hidden">
<div class="form-group">
<input type="text" placeholder="Name this project" class="form-control">
</div>
<button type="submit" class="btn btn-success">Save</button>
<button id="cancel-project-popover" class="btn btn-secondary">Cancel</button>
</div>
</div>
Are you sure that outer event 'turbolinks:load' is fired at all? Because when I remove that event listener, everything works as it should:
//assign elements in to variables
const openProjectButton = document.getElementById('new-project-button')
const projectPopover = document.getElementById('new-project-popover')
//check if elements exist
if (openProjectButton && projectPopover) {
//attach listener
openProjectButton.addEventListener('click', function() {
//if the popover class contains is-hidden remove it else return nill.
return projectPopover.classList.contains('is-hidden') ? projectPopover.classList.remove('is-hidden') : null
}, false)
//attach listener to cancel button
const cancelProjectpopover = document.getElementById('cancel-project-popover')
cancelProjectpopover.addEventListener('click', function() {
//add back is-hidden
return projectPopover.classList.add('is-hidden')
}, false)
}
.is-hidden {
display: none;
}
<div class="col-md-1 mr-auto">
<button id="new-project-button" class="btn btn-primary mr-auto">New</button>
<div id="new-project-popover" class="project-popover is-hidden">
<div class="form-group">
<input type="text" placeholder="Name this project" class="form-control">
</div>
<button type="submit" class="btn btn-success">Save</button>
<button id="cancel-project-popover" class="btn btn-secondary">Cancel</button>
</div>
</div>

Trying to prevent modal close on button click - javascript

I'm working on a small project in ASP.NET MVC, and in one part I need help of javascript.
Acctually there is modal with three inputs, old password, new and confirm new password,
and in case all fields are empty I need to prevent user from closing modal, I tried to solve it like this:
function comparePasswords(currentPassword) {
//Here I will loop throught all of my three inputs to check are they empty
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty.');
$('#ChangePassword').modal({
backdrop: 'static',
keyboard: false // I need to prevent user from clicking ESC or something
})
}
}
But I get following error (check the image):
EDIT:
FULL CODE:
<div class="form-group">
<label for="UserPassword">Pw:</label>
#Html.TextBoxFor(model => model.PasswordHash, new { #class = "form-control custom-input", data_toggle = "modal", data_target = "#ChangePassword", ariaDescribedby = "basic-addon1" })
</div>
#*Modal for ChangePassword which is opening when user clicks on control above ^*#
<div id="ChangePassword" class="modal fade" role="dialog">
<div class="modal-dialog modal-sm">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Updating password</h4>
</div>
<div class="modal-body" id="allInputs">
#*Modal Old Password*#
<div class="form-group">
<label for="UserPassword">Old password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="Eldin123" name="oldPassword" id="OldPassword" data-toggle="modal">
</div>
#*Modal New Password*#
<div class="form-group">
<label for="UserPassword">New password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="newPassword" id="NewPassword" data-toggle="modal">
</div>
#*Modal Repeat New Password*#
<div class="form-group">
<label for="UserPassword">Confirm new password:</label>
<input type="password" class="form-control custom-input modal-trigger" value="" name="confirmPassword" id="ConfirmNewPassword" data-toggle="modal">
</div>
#*Modal - submit*#
<div class="confirm-login">
<button type="button" class="btn custom-btn-big" onclick="comparePasswords();">NEXT</button>
</div>
</div>
</div>
</div>
</div>#*end of Modal for ChangePassword*#
#*Confirm button*#
<div class="confirm-login">
<button class="btn custom-btn-big" data-target="#">SAVE ALL CHANGES</button>
</div>
</div>
</div>
</div> #*End of User / Administration*#
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
function fieldInvalid() {
var formInvalid = false;
$('#allInputs input').each(function () {
if ($(this).val() === '') {
formInvalid = true;
console.log(formInvalid);
}
});
}
function passwordsInvalid() {
var invalidPassword = true;
var oldPw = $("#OldPassword").val();
var newPw = $("#NewPassword").val();
var confirmNewPw = $("#ConfirmNewPassword").val();
if (oldPw != newPw) {
alert('Postojeći password nije ispravan.');
}
else if (oldPw != confirmNewPw) {
alert('Password koji ste unijeli se ne slaže.');
}
else {
invalidPassword = false;
}
return invalidPassword;
}
var comparePasswords = function () {
if (fieldInvalid()) {
alert('One or more fields is empty.');
}
else {
if (!passwordsInvalid()) {
$("#ChangePassword").modal('hide');
}
}
}
</script>
}
So when someone clicks on password input, modal will be opened, and from that modal after informations are there user should click on button "NEXT" and there is event onclick which is calling comparePasswords method.
You are missing bootstrap library file.
Order of the file should be
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Same Problem (missing bootstrap.js) http://jsfiddle.net/1aeur58f/676/
Problem resolved (by adding bootstrap.js) http://jsfiddle.net/1aeur58f/677/
Hope this will help you.

Categories

Resources