i have assigned a function outside of its scope like this:
toggleEdit.setAttribute('onclick', `toggleEdit('${dataId}')`);
inside the toggle edit function i want to refer to it again, but it's not happening
function toggleEdit(dataId) {
....
saveEdit.onclick = () => { // this is same element as toggleEdit above, function changed
if (newText) {
...
saveEdit.setAttribute('onclick', `toggleEdit('${dataId}')`); // refer again like above
} else {
alert('Please enter a valid todo')
...
}
}
}
saveEdit is same element as toggleEdit above but reassigning when condition is met not working. help?
Related
I have a jQuery event inside a JavaScript function. I've already read that you cannot access the inner function. However, I would like to know how to adjust my code so that the parent function returns true or false depending on the jQuery function.
function validate() {
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
if (input == "") {
return false;
}
});
if(onclickfunction() == true){
return true;
}
else{
return false
}
}
validate();
Or can you recommend a different approach?
Not sure what this code is supposed to do, because calling validate only creates the event listener without actually executing it. But what you can do is to prevent the default action when you need, which is how validation is usually implemented:
$("#button").on('click', function(){
var input = document.forms["formular"]["text"].value;
yourSecondFunction(input !== "");
});
function yourSecondFunction(inputIsValid) {
// Do your magic here
}
I am creating a validation script in JavaScript with jQuery and am using the .change() function from jQuery, when the input value is changed I want it to call an object function from itself, displayError(). The function is called from child classes when they are constructed.
The class:
class Input { //this makes a class that all inputs should be assigned to
constructor(input, error) {
this.inputBox = input; //jQuery Object of the input box
this.errorText = error; //jQuery Object of the error text
this.required = this.inputBox.prop("required"); //return true if the inputBox has attribute required and false if not
this.unique = this.inputBox.prop("data-unique"); //USED FOR KNOWING IF NEEDED TO QUERY IN DATABASE
this.errorText.hide(); //hides the error text
}
displayError() { //function that will decide whether the error text needs displaying
var valid = this.auth(); //sees if the value of the input box is valid
//QUERY DB TO SEE IF TAKEN
if (!valid) {
this.errorText.show(); //shows the error text
}
//else if TAKEN && this.unique{SHOW DIFFERENT MESSAGE}
else { //runs if the value is valid
this.errorText.hide(); //hides the error text
}
}
auth() {
let value = this.inputBox.val(); //asssigns the value of the input box to 'value'
if ((!this.required && value == "") || this.isValid(value)) { //if not required the value can be nothing, but if it is required then the value must be validated
return true; //says the value is valid
} else {
return false;
} //says the value is not valid
}
liveErrors() {
this.inputBox.change(function() {
this.displayError()
}); // <--- ISSUE HERE
}
}
All of my class variables are set and are working, I'm not sure if it is because after the .change() I am referencing this in a function which is not set because it is not global variable, if that is the issue I am not sure how to overcome that.
I am very new to JavaScript and OOP, sorry if i have any incorrect terminology or have done something stupid, thanks in advance.
In the anonymous inner function used as the callback for this.inputBox.change, this is the element this.inputBox is pointing to, which is the input element in the dom. You can verify that with a call to console.log( this, typeof this ); in that function before trying to call this.displayError();
You can use jQuery.proxy to call your member function with your chosen context, this.
I stripped down your code and used keypress instead of change for the example snippet, but you can see that it will work to trigger instance methods by typing in the two input fields and seeing that they triggering changes to their instance specific member elements.
Inside of your member function, this should work just as expected.
class Input { //this makes a class that all inputs should be assigned to
constructor(input, error) {
this.inputBox = input; //jQuery Object of the input box
this.errorText = error; //jQuery Object of the error text
}
toggleError() { //function that will decide whether the error text needs displaying
this.errorText.toggle(); //hides the error text
}
liveErrors() {
this.inputBox.keypress($.proxy(this, 'toggleError'));
}
}
let first = new Input($('.first-input'), $('.first-error'));
let second = new Input($('.second-input'), $('.second-error'));
first.liveErrors();
second.liveErrors();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="first-input">
<span class="first-error">First!</span>
<br/>
<input class="second-input">
<span class="second-error">Second!</span>
I have two functions and i want to call one function when the radio button is checked as an employee and the other when the radio button is checked as a user.
employee.form.send = function() {
employee.validator.checkForm();
if (employee.validator.valid()) {
employee.form.submit();
}
};
invite.form.send = function() {
invite.validator.checkForm();
if (invite.validator.valid()) {
alert(1);
invite.form.submit();
}
}
I would normally call them with a click event like this
invite.find('#sendInviteButton').on('click',invite.form.send);
Now i want to call different functions when the #sendInviteButton is clicked. Depending on the radio button selected. How do i do that?
I am not able to call the invite.form.send inside an if condition.
If I understood correctly, you want to do something like this:
if($('#employee_radio_button').is(':checked'))
employee.form.send();
else
invite.form.send();
You could wrap the click into a function with jQuery like so, assuming your function names are "oneFunction" and "anotherFunction"..
$('#sendInviteButton').click(function() {
if ($('#sendInviteButton').is(':checked')) {
oneFunction();
} else {
anotherFunction();
}
});
what about binding the event to a function which checks the state of the ratio button and than depending on that call the proper functions accordingly? (Check code below)
invite.find('#sendInviteButton').on('click', checkState); // update the event binding
function checkState() {
if (document.getElementById('sendInviteButton').checked) {
// call function if #sendInviteButton is checked
} else {
// call other function
}
}
or in case you use jQuery:
function checkState() {
if($('#sendInviteButton').is(':checked')) {
// call function if #sendInviteButton is checked
} else {
// call other function
}
}
My Scenerio:
I have a function:
The function Addprocedure() is called on onclick of Addprocedure button.
In this function i want to check if btnAddSelectedProcedures is clicked then do Something else do nothing
function Addprocedure(){
if()// Check if Button is clicked, button id = `btnAddSelectedProcedures`
{
//Do Something
}
else{
//Do nothing
}
}
Save the state of the button in a variable.
Define btnClicked globally as false. When btnAddSelectedProcedures is clicked, change btnClicked to true. When you call Addprocedure check if btnClicked variable is true and if so, that button has been clicked.
Example:
var btnClicked = false;
function Addprocedure() {
if (btnClicked) {
//Do something...
} else {
//Do something else...
}
}
$('BUTTON[name="btnAddSelectedProcedures"]').click(function() {
btnClicked = true;
});
$('BUTTON[name="Addprocedure"]').click(function() {
Addprocedure();
});
Try
$('#btnAddSelectedProcedures').click(function(){
$(this).data('clicked', true)
})
then
function Addprocedure(){
if($('#btnAddSelectedProcedures').data('clicked')){
//clicked
} else {
//not clicked
}
}
It is simple, check id
function Addprocedure(){
if(this.id === 'btnAddSelectedProcedures')// Check if Button is clicked, button id = `btnAddSelectedProcedures`
{
//Do Something
}
else{
//Do nothing
}
}
One possiblity,
You can declare a global variable and mark it as true when yourbtnAddSelectedProcedures clicked and use that to check in your Addprocedure() function.
var isButton1Clicked =false;
onButton1Click{
isButton1Clicked ==true
}
onButton2Click{
if(isButton1Clicked){
//procedd
}
}
I suggest to avoid using global var. Use a class instead ( or You can set data-* attribute as well )
$('#btnAddSelectedProcedures').on('click', function(){
//$(this).toggleClass('clicked');
if(! $(this).hasClass('clicked') ){ //allows you to set only once the class
$(this).addClass('clicked');
}
Addprocedure();
});
then
function Addprocedure(){
if( $("#btnAddSelectedProcedures").hasClass('clicked') ) //I guess you can call $(this) too
{
//Do Something
}
else{
//Do nothing
}
}
I used toggleClass because I think you want to check every time if the user clicked .
Use addClass in the other way.
<button id="1" onClick="Addprocedure(this.id)">B1</button>
and then
function Addprocedure(clicked_id)
{
alert(clicked_id);
}
I have this function:
$(document).ready(function(){
function Fos(buttonSel, inputSel, someValue, cssProperty) {
$(buttonSel).click(function(){
var value = $(inputSel).attr("value");
$("div.editable").click(function (e) {
e.stopPropagation();
showUser(value, someValue, this.id)
var css_obj={};
css_obj[cssProperty]=value;
$(this).css(css_obj);
});
});
}
Here are three places where function is written:
Fos('#border_button', '#border-radius', 2, '-webkit-border-radius');
Fos('#background_color_button', '#background-color', 1, 'background-color');
Fos('#opacity_button', '#opacity', 3, 'opacity');
<input type="text" id="border-radius" value="20px">
<div id="border_button">BORDER RADIUS</div>
<input type="text" id="background-color" value="red">
<div id="background_color_button">Background</div>
<input type="text" id="opacity" value=".5">
<div id="opacity_button">Opacity</div>
<div id="2" class="defaultclass editable" style="<?php getStyle('2') ?>">
something
</div>
When you click the DIV with the ID= "border_button", or "background_color_button", or "opacity_button"
it waits for you to click any DIV with class="editable", ...$("div.editable").click(function (e) {... it executes the function with those parameters.
I just need a fix that will only allow ONE function with the parameters to be enabled at one time.
Currently, when you click on all three divs with ID = "border_button", or "background_color_button", or "opacity_button" AND THEN on a div with class="editable", it executes the function with ALL THREE sets of parameters.
This is bad. I can't figure it out.
You can't "disable" a function, but you can set a variable that will force it to exit right away:
var stopMe = true
function myFunction() {
if(stopMe) {
return;
}
...
}
You seem to be binding and rebinding the same functions over and over, which is probably why you have that e.stopEventPropagation in there. Try assigning the events once and then managing the current state (which button is active) and going from there:
var $currentInput = null;
$("#border_button,#background_color_button,#opacity_button").click(function() {
if ($currentInput == null) {
$currentInput = $(this).prev();
}
});
$("div.editable").click(function(e) {
if ($currentInput == null)
return;
$(this).css(GetCssProperties());
showUser($currentInput.val(), /* where does someValue come from? */, this.id)
$currentInput = null;
});
function GetCssProperties() {
if ($currentInput == null) return null;
var value = $currentInput.val();
if ($currentInput.attr("id") == "border-radius") return {
"-webkit-border-radius": value
}
if ($currentInput.attr("id") == "background-color") return {
"background-color": value
}
if ($currentInput.attr("id") == "opacity") return {
"opacity": value
}
}
working example here: http://jsfiddle.net/HUJ5A/
Run the function for tag with a specific class. And a the end of the function remove this class from the tag.
jQuery(".myclass").click(function(){
/* do something */
jQuery(this).removeClass('myclass');
});
Can't tell everything from your question. But this part $("div.editable").click(function (e) { will bind multiple click events to div.editable each time the user clicks Foo arugments[0] or buttonSel.
This could be a pssible solution:
Have a global variable (or HTML hidden input) say, lastDivClicked, to store the id of the recently clicked div
Update lastDivClicked everytime one of those three divs are clicked upon
Change your function to this:
function Fos(inputSel, someValue, cssProperty) {
var buttonSel = $('#lastDivClicked').val();
$(buttonSel).click(function(){ ... }
}