currently i am using
var email, fax, sms = false;
if($('#uemail:checked').val() != undefined)
email = true;
if($('#ufax:checked').val() != undefined)
fax = true;
if($('#usms:checked').val() != undefined)
sms = true;
but its such a long way to write it.
is there a better way to write this?
Try this:
if($('#uemail').is(':checked'))
email = true;
Or even shorter:
email = $('#uemail').is(':checked');
You're passing the :checked selector into jQuery's .is() method which returns a boolean value;
http://api.jquery.com/is/
You can use .length, like this:
var email = $('#uemail:checked').length,
fax = $('#ufax:checked').length,
sms = $('#usms:checked').length;
.length is the length of the array of matched elements...if it's not checked, it's 0. And since .length == 0 serves for .length == false in JavaScript you can do the short version above. If you need a true/false, then just do .length != 0 instead :)
Or, another alternative that produces booleans, just use the DOM .checked property:
var email = $('#uemail')[0].checked,
fax = $('#ufax')[0].checked,
sms = $('#usms')[0].checked;
Or, no jQuery at all just use getElementById():
var email = document.getElementById('uemail').checked,
fax = document.getElementById('ufax').checked,
sms = document.getElementById('usms').checked;
An alternative may be to use an associative array and then loop through the keys. It would certainly be more DRY.
// Initialise all the checkbox values as unknown
var items = {
"email" : none,
"fax" : none,
"sms" : none
};
// Loop through each checkbox index
for (var index in items) {
// Get the id of the checkbox
var id = '#u' + index;
// Find out if the checkbox is checked
items[index] = $(id).is(':checked');
}
Related
I have been trying to search for an existing value in an array like below
var values = []
values.push(localStorage.getItem('items'));
console.log(values);
if (values.includes(2)) {
alert('Already Exists.');
}
When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.
My challenge is how to find the value 2 in the array values ?
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().
Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:
var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);
if (values.includes("2")) {
console.log('Already Exists.');
}
Hope this help you.
var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');
function checkValue(value,arr){
var status = 'Not exist';
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
status = 'Exist';
break;
}
}
return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );
First of all, this isn't jQuery, it's vanilla JS.
Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.
Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with
vals.includes(2) for a true/false answer,
vals.find(val => val === 2) for 2 or undefined,
val.indexOf(2) to get the index of the
first element equal to 2.
Hope this helps.
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true
var values =localStorage.getItem('items')
var spliter = values.split(',')
console.log(spliter);
if (spliter.includes('2') == true) {
alert('Already Exists.');
}
I've been searching around and all the answers I've seen will use something along the lines of $('form :input')$ to get all of the inputs. But I already have a reference to the form using $("form").submit() and I just need to grab a specific input field from the fieldname. I'm unsure of how to use $(this) with additional selectors to get the forms specific elements
So, how would I go about doing that.
Example of the bit of code I need to workout.
$('form').submit(function(){
var form = $(this)
var form_errors = array_of_errors
for(var fieldname in form_errors){
var errors = form_errors[fieldname]
var field = \\how to get this
\\ Something like $(form, 'input[name='+fieldname+']') maybe?
}
});
$(selector, context)
jQuery selectors can have a second argument, used to define their context.
$(`input[name=${fieldname}]`, form);
will do the trick.
This means that your selector will look only inside the element you have passed as context.
Documentation:
http://api.jquery.com/jquery/#jQuery-selector-context
$(context).find(selector)
An alternative could be to use find() in conjunction with the context:
$(form).find(`input[name=${fieldname}]`);
$('form').submit(function(){
var $form = $(this), // good naming practice to use $ to signify jQuery object
form_errors = validateForm(this); // semi-colon
var fields = Object.keys( form_errors );
for ( var i=0,n=fields.length; i<n; i++ ){
var field = fields[i],
errors = form_errors[field],
$field = $form.find('input[name=' + field + ']');
$field.applyErrorMarkup(errors); // whatever you plan to do with the field
}
});
// Pseudocode of one possible way to validate your form
function validateForm(frm){
var errors = {};
// BEGIN LOOP: <insert code to iterate over fields and validity checks>
var field = 'fieldname'; // placeholder
if( true /* error found */ ){
var err = errors[field];
var msg = 'new error message'; // should be the dynamic validity check error message (e.g., 'only numbers permitted')
errors[field] = err && [msg].concat( err ) || msg;
}
// END LOOP
return errors;
}
How can I verify all the items listed in a combo box? Like for example I want to check if a combo box have "item1" "item2" "item3". How do I output all options out and check?
Here's how to excess the combobox:
Ext.ComponentQuery.query('combobox[name=boxname]')[0];
Just access the store of your box and interrogate it. For example:
var store = Ext.ComponentQuery.query('combobox[name=boxname]')[0].getStore();
console.log(store.getById('item1'));
If item1 is not there the result will be null.
UPDATE:
Based on conditions lets say, I want to be able to validate the combo
box that it only has "item1" and "item2", not any more or any less.
Given that say the variable target contains what you want in your combo, you can verify your combo this way:
var target = ['item1', 'item2'],
combo = Ext.ComponentQuery.query('combobox[name=boxname]')[0],
check = function(combo, target) {
var store = combo.getStore();
if (target.length !== store.getTotalCount()) {
return false;
}
var result = true;
store.each(function(item){
if (!Ext.Array.contains(target, item.getId())) {
result = false;
return false;
}
});
return result;
};
console.log(check(combo, target));
The method check will return true if the combo contains what you want, or false otherwise.
var store = Ext.ComponentQuery.query('combobox[name=boxname]')[0].getStore();
store.each(function(record){
var name = rec.get('name');// instead of name use the attribute you want to use for the validation
if(name === 'code4jhon'){
console.log('this dudes name is code4jhon')
}
});
http://docs.sencha.com/extjs/4.2.3/#!/api/Ext.data.Store-method-each
I would like to display an error message when a user types a value in an input field (emailaddressVal) that matches a value in my array (invalidEmailAddresses). But I don't know how to go about it.
Thanks for your help!
$(document).ready(function(){
$("input[name='emailAddress']").blur(function(){
// Actual Email Validation function
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var hasError = false;
var emailaddressVal = $("input[name='emailAddress']").val();
var invalidEmailAddresses =
['aol.com', 'yahoo.com', 'yahoo.fr', 'juno.com', 'hotmail.com', 'gmail.com'];
if($.inArray(invalidEmailAddresses,emailaddressVal) == -1) {
alert('The email provided is not from a business related domain');
}
});
});
Try the following code
$(document).ready(function () {
$("input[name='emailAddress']").blur(function () {
var emailAddress = $("input[name='emailAddress']").val().trim();
if (isValidEmailAddres(emailAddress)) {
var hasError = false;
var emailaddressVal = emailAddress.split('#').slice(1)[0].trim();
var invalidEmailAddresses = ['aol.com', 'yahoo.com', 'yahoo.fr', 'juno.com', 'hotmail.com', 'gmail.com'];
if ($.inArray(emailaddressVal, invalidEmailAddresses) >=0) {
alert('The email provided is not from a business related domain');
}
} else alert("Invalid EmailID");
});
function isValidEmailAddres(emailID) {
var regexExp = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return regexExp.test(emailID);
}
});
See this fiddle
Changes That I did
I added a email Validation Function. Only if it is a valid email address you will proceed for hostname checking.
Correct Format of $.inArray is $.inArray( stringvalue, array). So it has to be $.inArray(emailaddressVal,invalidEmailAddresses)
emailaddressVal will contain a full email address. First you need to extract the hostname from that full email address. It is done at
var emailaddressVal = emailAddress.split('#').slice(1)[0].trim();
So if your email address is abc#gmail.com, the above line will return gmail.com.
Return type of $inArray is the position at which the passed string (emailaddressVal in your case) is present in the arraylist (invalidEmailAddresses). It will return a value greater than or equal to 0. As per your requirement you have to show the message when you want the host in email id is present in array of host names. You need to do
if($.inArray(emailaddressVal, invalidEmailAddresses) >=0)
You can use the jQuery inArray test like this.
var emailaddressVal = $("input[name='emailAddress']").val();
The code beloe test the user input to see if it is in the array and stores the index in which it is located.
var inArrTest = $.inArray(emailaddressVal, invalidEmailAddresses);
This code test the inArrTest variable and gets the index of the users matched value.
if (inArrTest) {
// Your error message would go here. //
console.log(invalidEmailAddresses[inArrTest]);
}
You can nest your error message inside the if block.
The original code does not work because the -1 checks to see if the variable is not in the array.
$.inArray(invalidEmailAddresses,emailaddressVal) == -1)
Sukanya's code check to see if the variable is greater than 0 which is the first index of an array.
$.inArray(emailaddressVal,invalidEmailAddresses) > 0
I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),