Getting a submit selection into a variable with jQuery - javascript

I am making a condition that verifies some class and depending on the value, the respectable submit input is stored into a variable:
_btnAjax = "";
if (_aVar.hasClass("one")) {
_btnAjax = $("#one");
}
if (_aVar.hasClass("two")) {
_btnAjax = $("#two");
}
and then, using the .on('click' function(e){}); on that variable:
_btnAjax.on('click', function(e) {
// some Ajax
}
The problem is that I receive the error TypeError: _btnAjax.on is not a function
I already made exactly the same thing on a <li></li>, but either <button></button> or <input type='submit'/> don't work.

The reason that fails is because neither of your two conditions are true.
For example, if _aVar does not have a class of one AND it does not have a class of two then _btnAjax is a string in your code.
Double check that your UI has the right classes.
In addition, make sure you handle the other case.
Try writing your code more like this:
var _btnAjax;
if (_aVar.hasClass("one")) {
_btnAjax = $("#one");
} else if (_aVar.hasClass("two")) {
_btnAjax = $("#two");
} else {
// Do something to handle the fact that neither case was true.
// You can return early, throw an error, or set _btnAjax to
// an empty jQuery object.
}

You're trying to use a jQuery function (.on)
Try this:
$(_btnAjax).on('click', function(e) {
// some ajax
}
Although I think you should use a id or class selector like:
// selector should be whatever your button has as id or class property.
// (preferably an id since this won't conflict with other classes)
$('#btnAjax').on('click', function(e) {
// some ajax
}

Related

Check all / check none checkboxes

I' trying to establish user options for checking all and none checkboxes. I use this code:
function selectToggle(toggle, form) {
var myForm = document.forms['cbx'];
for( var i=0; i < myForm.length; i++ ) {
if(toggle) {
myForm.elements[i].checked = "checked";
}
else {
myForm.elements[i].checked = "";
}
}
}
document.getElementById("all").addEventListener("click", selectToggle, true);
document.getElementById("none").addEventListener("click", selectToggle, false);
Here works only the option check all - check none doesn't work.
But, if i use instead of event listeners inline javascript like All | None both options work.
How can i force document.getElementById("none").addEventListener("click", selectToggle, false); to work?
That is because the third parameter in addEventListener is actually the useCapture option. You are not passing true or false into the arugment for the function selectToggle. To do that, you will need to call it using an anonymous function:
document.getElementById("all").addEventListener("click", () => selectToggle(true)));
document.getElementById("none").addEventListener("click", () => selectToggle(false)));
I have left out the second argument because it doesn't seem like you're using it in your method at all. However, if the second arugment is to be used as a form identifier, then you can do this:
document.getElementById("all").addEventListener("click", () => selectToggle(true, 'cbx')));
document.getElementById("none").addEventListener("click", () => selectToggle(false, 'cbx')));
Explanation of why your code went wrong: The reason why in your original code the check all function works, is because when you use selectToggle as the callback, like this:
document.getElementById('all').addEventListener('click', selectToggle);
...the first argument is actually the event object. Since it is an object that is passed to the first argument called toggle, toggle will always be truthy, hence you will always end up executing the logic inside the if (toggle) {...} block.

Returning function as parameter with closures

Here is a link to my JS fiddle: https://jsfiddle.net/apasric4/v1qkmgyu/1/
function inputCheck(input) {
if (input.name==="email") {
console.log("email")
return isValidEmail
} else if (input.name==="password") {
return isValidPassword
console.log("pass")
} else if (input.name==="userName") {
return isValidUserName
console.log("user")
}
}
function isValidEmail (email) {
return /^[^#]+[#][^#.]+\.[a-z]+$/.test(email)
}
function isValidPassword(pass) {
return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(pass)
}
function isValidUserName(user) {
return /^[a-zA-Z0-9]+([_ -]?[a-zA-Z0-9])*$/.test(user)
}
function validation(e) {
e.preventDefault()
inputs.forEach(input=> createListener(inputCheck(input)))
}
function createListener(validator) {
return (e)=> {
const inputValue=e.target.value;
const valid=validator(inputValue)
console.log(valid)
}
}
I'm trying to create form validation using closures. I am trying to make my code as efficient as possible.
I want to loop over each input element (without selecting each individually), and apply an event listener to each one. The inputCheck function would return a validator function depending on the name attribute of each input, and the createListener function takes the value returned by inputCheck, which would be a specific type of validator, and then for testing purposes, console.log true or false.
So far, the only if branch that works in the inputCheck function is the first one associated with name attribute email. The other if branches won't work if I type values into other input elements and submit the form.
Can anyone tell me where I'm going wrong and how to improve my code?
I'm new to closures so I understand that this issue might seem relatively simple to most of you.
I can observe two things:
First, just like #VLAZ pointed out, two console.log in inputCheck are actually not executed since they are placed after return.
Second, createListener and validation are not quite right. createListener returns a function with one argument. validation forEach doesn't log anything because createListener returns a function, no function execution here.
There is another problem with the argument e of createListener. It seems like you treat it as an event, but based on your implementation, there is only one event, that is form submit event. So, I'd suggest to modify these two functions a little bit:
function validation(e) {
e.preventDefault()
inputs.forEach(input=> createListener(inputCheck(input))(input))
}
function createListener(validator) {
return (e)=> {
const inputValue=e.value;
const valid=validator(inputValue)
console.log(valid)
}
}
Then, the console prints out true or false based on the input value of each input field.
Please check whether the output is your intension or not https://jsfiddle.net/jqgbefhw/

jQuery - Get array of multiple selector

I have a global click event handler, which listens for certain items passed to it. The code has this format:
$(document).on('click', '#id, .my-class, .my-other-class', function(e) {
if ($(this).is($(this)[0])) {
return true;
}
}
however this does not return true only the first object (#id) but for any of the selectors ('#id, .my-class, .my-other-class').
I understand this is probably because $(this) has only one item in it (0 - which has all of the selectors).
I can get the code to work if I do this:
$(document).on('click', '#id, .my-class, .my-other-class', function(e) {
if ($(this).is('#id') {
return true;
}
}
however I do not want to type the entire selector again (call me lazy), especially if I have to type .my-other-class (I would never have a class with that large a name but it is a matter of principle).
Thus I tried to use .split(', ') however that err'd on var $this = this.split(', '); and var $this = $(this).split(', '); saying they are not a functions.
Does anyone know how to get it so that I can type if ($(this).is($(this)[0]) {}, or something like that and it will work? Or is this not possible...

efficiently creating variables when a checkbox is checked and using these variables later in the code

below is the information I need help with.
$(document).ready(function(){
$('.checkboxes :checkbox').click(function(){
if($(this).is(':checked')){
console.log(this.id + this.checked)
i want to set a variable with the samename of the id of the checked box
so if showItems was checked i would have a variable
var showItems = true;
I want this so I could see if showItems is checked which would alow me to perform the proper functions
i think i could do something like this
if($this.id = "withones"){
var withones = true;//on
}
if($this.id = "withoutOnes"){
var withoutOnes = true;//on
}
etc.
i feel like the above is a rookie way to code. lets say i have alot of checkboxes and it also looks like im repeating myself. I tried putting the ids in an array and loop through them but I got the html element in the console when i clicked on the box. I would like for someone to tell me if there is a more efficient way to set up these variables. and if so show me please.
Also I'm new to programming so thanks for your help so far. but I was also thinking about another problem. if I set up these variables here and I want to set up another function somewhere else to perform mathematical operations perse. i want that function to be able to evaluate the value of the withones and withoutOnes variables so I would like to do something like this in the function
function add(){
if(withones){ //true|| false
return 2 + 2;
}
if (withoutOnes) {
return 'blah'
};
}
I have had problems in the past trying to test the values that are set outside the function. I think i tried setting it in the arguments. but it just didn't read. If you could also show me an example of using the variables some where else in the code like discussed above that will be helpful . I forgot to mention that the value of the variable will change when the user clicks on the box. either to true or false. I think my problem in the past is that when the box is checked and then uncheck I had a problem changing the variable especially when it is being used in a separate function
}
});
});
You can have an object with your vars and add vars to that object dinamically:
var oVars = {}
// adding a var
oVars[nameVar] = valueVar
// accessing the var
oVars[nameVar]
You can capture the id with the attr() or you can just change the value of the checkbox with val() method in jQuery like this: FIDDLE
$(document).ready(function () {
$('.checkboxes').change(function (event) {
if ($(this).is(':checked')) {
var captureId = $(this).attr('id');
$(this).val(true);
alert($(this).val());
}
else {$(this).val(false);
alert($(this).val());}
});
});
Note that you can evaluate later all the checkboxes with one button and collect the value false or true from them. Why would you go through all of the complications with changing values of variables.
The other two answers are correct, though it sounds like you're wanting to know generally how to manage a big list of checkboxes with differing methods depending on type. It could look like this:
function multiply(this_object){
if((this_object.is(':checked')) && (this_object.attr("with") == 1))
return "with withone and checked";
else
return "is not both";
}
$(document).ready(function(){
$('.checkboxes').click(function(){
var this_object = $(this);
alert(multiply(this_object));
});
});
There should be no need to store all of the values in a variable unless you are passing all of them to another page - eg., via AJAX. Just reference them straight from the source field. If you need other info stored alongside, make a new attribute on the field - like the "with" one that I made for this example. See this Fiddle: http://jsfiddle.net/6ug6gL97/
your question is quite broad; so I’ll try to do my best to give you some kind of answer. First of all I’d use variables of global scope when declaring variables: withones and withoutOnes. Secondly, you wanted to avoid repetition in your code. Well, for that purpose I’d use JavaScript Arrays. In an array, you can add your variables as objects. In an object you can have your ids and other data “packed” neatly in the array, which in turn helps your code to become efficient.
Below is an array with objects:
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
The above array can be used in your $('.checkboxes :checkbox').click(function() handler and add() function to avoid repetition. The updated code is below where jQuery's each() method is used for looping Array elements.
The last a bit of your question was related to add() function. Well, this was the tricky bit of your question, and I tried to use a callback function hopefully in the right way to execute your functions from the array. In the add method I tried to follow this answer: https://stackoverflow.com/a/13343452/2048391
About the last bit I’m not 100% sure did I use a callback function in the right way; so I hope someone more familiar with these tricky JavaScript functions can correct me, if something needs to be changed –thanks.
objectArray = [{
id: "withones",
checked: false,
method: function () {
return 2 + 2;
}
}, {
id: "withoutOnes",
checked: false,
method: function () {
return 'blah';
}
}];
$(document).ready(function () {
$('.checkboxes :checkbox').click(function () {
var id = this.id;
var checkedValue = this.checked;
$.each(objectArray, function (index, object) {
if (object.id === id) {
object.checked = checkedValue;
}
});
add();
});
function add() {
// clear results
$("#addResults").text("");
$.each(objectArray, function (index, object) {
if (object.checked === true) {
var returnValue = createCallback(object.method)
$("#addResults").append(returnValue + "<br>");
console.log(returnValue);
}
});
}
function createCallback(method) {
return method();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="checkboxes">
<input type="checkbox" id="withones"></input>
<label>With Ones</label>
<br>
<input type="checkbox" id="withoutOnes"></input>
<label>Without Ones</label>
</div>
<div id="addResults">
</div>

How to get the name of a jQuery UI widget?

I need a way to read the name of a jQuery UI widget. I have subclassed the dialog widget into two subclasses, myDialog1 and myDialog2. I have created a destroyDialog function to destroy whichever dialog is active. There should be a way to determine the name of the widget instance.
What I want to do is something like this:
var destroyDialog = function() {
activeDialog[activeDialog.widgetName]("destroy");
}
But I don't see a way to get the widget name. For now I'm using ugly nested try-catch statements.
var destroyDialog = function() {
try {
activeDialog.dialog("destroy");
}
catch (e) {
try {
activeDialog.myDialog1("destroy");
}
catch (e) {
activeDialog.myDialog2("destroy");
}
}
}
You can get the widget name (and use it) by using
activeDialog.data("widgetName");
... as tdmartin refers to. So therefore:
activeDialog[activeDialog.data("widgetName")]("destroy");
But to get around this problem personally, I have written a plugin that will allow you to call a widget method without knowing what type the widget is. This will allow you to do:
activeDialog.callWidgetMethod('destroy');
It relies on you using jQuery UI 1.11+. If you are using <1.11, you can take out the "Skip this widget if it does not have the method" check, but the downside of that is that you will get an error if you attempt to call a method that a widget does not have.
Plugin code:
jQuery.fn.callWidgetMethod = function () {
var args = arguments;
var result = null;
if(!this || !this.length)
return this;
this.each(function (i,o) {
var compClass = $(this).data("widgetName");
var func = $(this)[compClass];
// Skip this element if it does not appear to be an initialised jQuery widget
if(!compClass || !func)
return true;
// Skip this widget if it does not have the method (the name of which will be in args[0])
// This relies on the 'instance' method provided in jQuery UI 1.11
if(args.length>1 && !$(this)[compClass]("instance")[args[0]])
return true;
result = func.apply($(this),args);
});
if(this.length>1)
return this;
else
return result;
};
If you standardize your namespace you could use a regex to match the name of the variable where your widget instance is stored (the name of the widget), returned by the $().data() method.
for (i in $(<your element>).data() ) {
if (i.match(/dialog/)) {
$(<your element>).data(i).destroy();
}
}

Categories

Resources