Variable empty with if statement - javascript

$(".my-input").each(function () {
var theSelectBoxContainer = $(this).parent().next();
var theSelectBoxValue = theSelectBoxContainer.dxSelectBox('instance').option('value');
var txtvalue = $(this).val();
if (txtvalue != "" && txtvalue!=" ") {
if (i)
field += " and ";
field = field + "'" + $(this).val() + "'";
i++;
}
});
Above my jQuery code. With this code, I overwrite the values entered in the TextBoxes. But I do not want textboxes to be written when null characters are entered. But it is written. I check with if, but it is not. Where is the error?

You can use $.trim(txtvalue) which will validate empty, null and undefined.
Or you can also use:
if (txtvalue === undefined || txtvalue === null) {
// show error messages..
} else {
//execute this code..
}

Related

How to prevent a user from entering duplicate email?

i use jQuery Plugin For Email Address Management - Multiple Emails
I want to prevent the user from entering two identical emails.
To do this, I use the array. Every email that is entered is poured into the array.
In fact, my goal is to prevent the user from entering duplicate emails
But unfortunately I can not do it properly
var items = [];
function guardarNumeros() {
boxvalue = $('.email-ids').text();
items.push(boxvalue);
console.log(items);
// Check if a value exists in the fruits array
if (items.indexOf("a#a.com") !== -1) {
console.log("Value exists!")
} else {
console.log("Value does not exists!")
}
}
return this.each(function () {
$(this).after("<span class=\"to-input\">Email :</span>\n" +
"<div class=\"all-mail\"></div>\n" +
"<input type=\"text\" name=\"email\" class=\"enter-mail-id\" placeholder=\"Enter Email ...\" />");
let $orig = $(this);
let $element = $('.enter-mail-id');
$element.keydown(function (e) {
var keycode = e.keyCode ? e.keyCode : e.which;
$element.css('border', '');
if (keycode == "13" || keycode == "188" || keycode == "9" || keycode == "32") {
let getValue = $element.val();
if (/^[a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,6}$/.test(getValue)) {
$('.all-mail').append(
'<span class="email-ids">' + getValue +
'<span class="cancel-email">x</span></span>' );
$element.val('');
email += getValue + ';'
guardarNumeros()
} else {
$element.css('border', '1px solid red')
}
}
$orig.val(email.slice(0, -1))
});
Can you help me
Thank
you always are checking if the "a#a.com" was entered.
try something like:
if (items.indexOf( boxvalue ) !== -1) {
console.log("Value exists!")
} else {
console.log("Value does not exists!")
items.push(boxvalue);
}

How to detect whether an html input object is a button or not?

I am working on trying to pull the inputs from a form, excluding buttons, but not radio buttons. I am getting my inputs via the .find() method of the form element. I have the inputs, but am unable to restrict them to just inputs other than the submit button or a similar button. I have tried the jquery .is(), .type(), both with no luck any suggestions/ references would be helpful as I have not found anything to help as of yet. Here is the code I am using to pull the forms.
var inputs = formList.find(":input");
if (inputs ? inputs.length > 0 : false)
{
for(j = 0;j < inputs.length; j++)
{
console.log("input: " + inputs[j]);
if (inputs[j].name != "")
{
webForms.push({"inputName": inputs[j].name});
}else if (inputs[j].id != "")
{
webForms.push({"inputName": inputs[j].id});
}
}
}
Like I said, I have tried the .is and .type with no luck. Here is an example of how I was using .is()
var formList = $("form");
var formName = $("form").attr("name");
if (formList != null ? formList.length > 0 : false)
{
if (formList.length < 2)
{
if (formList.attr("name") ? formList.attr("name") != "" : false)
{
//alert("form name is not null");
//alert("form name: " + formList.attr("name"));
var webForms = [];
//alert("formList name: " + formList[i]);
var inputs = formList.find(":input");
if (inputs ? inputs.length > 0 : false)
{
for(j = 0;j < inputs.length; j++)
{
console.log("input: " + inputs[j]);
if (inputs[j].name != "")
{
if(inputs[j].is(":button"))
{
console.log(inputs[j].name + " is a button");
}
webForms.push({"inputName": inputs[j].name});
}else if (inputs[j].id != "")
{
if(inputs[j].is(":button"))
{
console.log(inputs[j].name + " is a button");
}
webForms.push({"inputName": inputs[j].id});
}
}
}
//alert(JSON.stringify(webForms));
jsonForm.forms[jsonForm.forms.length - 1].name = formList.attr("name");
//alert("json form name: " + JSON.stringify(jsonForm));
jsonForm.forms[jsonForm.forms.length - 1].inputs = webForms;
//alert("name: " + jsonForm.forms[jsonForm.forms.length - 1].name);
}
}
Any help here is appreciated.
You can use the following code to get the input elements which aren't buttons or inputs with a type attribute of "submit".
var inputs = formList.find(':input:not(button, [type="submit"])');
Here is a live demonstration.
the problem is inputs[i] returns a dom element reference not a jQuery wrapper object so its does not have the is method you can use
inputs.eq(i).is(':button')
I would recommend to use .each() loop to iterate over the jQuery object than using a loop
var inputs = formList.find(":input");
inputs.each(function () {
var $input = $(this);
console.log("input: " + this);
if (this.name != "") {
if ($input.is(":button")) {
console.log(this.name + " is a button");
}
webForms.push({
"inputName": this.name
});
} else if (this.id != "") {
if ($input.is(":button")) {
console.log(this.name + " is a button");
}
webForms.push({
"inputName": this.id
});
}
})
This could even be simplified to
var inputs = formList.find(":input");
inputs.each(function () {
var $input = $(this);
console.log("input: " + this);
var name = this.name || this.id;
if (name != "") {
if ($input.is(":button")) {
console.log(name + " is a button");
}
webForms.push({
"inputName": name
});
}
})

Input removing leading 0

I have a form input field.
<input style="text-align:right;" type="text" name="DiversionCalc_Diversion_Rate" id="calc_dr" value="0.25%" />
I am attempting to format it based on focusout using jQuery 1.7.2
$('#calc_dr').focusout(function () {
var value = $.trim($(this).val()).toString();
if (value.indexOf("0.") === -1) {
var $t = ("0" + value).toString();
alert($t);
$(this).val($t);
}
if (value != '' && value.indexOf("%") === -1) {
$(this).val(value + '%');
}
});
While this mostly is working, the alert pops up the correct 0.25 when I enter .25 in the field, however, the $(this).val only ever shows .25
How can I get it to show what it's showing me in the alert???
Make $t a global variable (pull it out of the if loop) and assign it instead of value.
$('#calc_dr').focusout(function () {
var value = $.trim($(this).val()).toString();
var $t = value;
if (value.indexOf("0.") === -1) {
$t = ("0" + value).toString();
alert($t);
$(this).val($t);
}
if ($t != '' && $t.indexOf("%") === -1) {
$(this).val($t + '%');
}
});
The basic idea is to grab the value, manipulate the value, then update the UI. The key being there is only one update at the end.
// Get the new value (strip everything but numbers and period)
var v= parseFloat($(this).val().toString().replace(/[^0-9\.]+/g, ""));
// Basic data type validation
if (isNaN(v)) v= 0;
if (v< 0) v= 0;
if (v> 100) v= 100;
// other validation updates v as needed...
doCheckDiversionRate(v);
// update UI (btw toFixed() will add a leading zero)
$(this).val(v.toFixed(2) + '%');

form validation with radio buttons and specific errors

I am trying to make a form validate where there are radio buttons and textarea. I want nothing to be left empty i.e the form should be completely filled. I have done the radio buttons part of validation where if a user does not select a radio button he will get an error for that particular question. you can see the code here for detailed code.
Please help me out. I am not getting error for textarea.
Just add another check for textarea
function RadioValidator() {
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++) {
var name = AllFormElements[i].name;
if (AllFormElements[i].type == 'radio') {
....
} else if (AllFormElements[i].type == 'textarea') {
if (AllFormElements[i].value == '') {
ShowAlert += name + ' textarea must be filled\n';
}
}
}
if (ShowAlert !== '') {
alert(ShowAlert);
return false;
} else {
return true;
}
}
you didn't write any validation for 'textarea' block. I have updated it with one textarea... add rest validations.
function RadioValidator()
{
var ShowAlert = '';
var AllFormElements = window.document.getElementById("FormID").elements;
for (i = 0; i < AllFormElements.length; i++)
{
if (AllFormElements[i].type == 'radio')
{
var ThisRadio = AllFormElements[i].name;
var ThisChecked = 'No';
var AllRadioOptions = document.getElementsByName(ThisRadio);
var problem_desc = document.getElementById("problem_desc");
for (x = 0; x < AllRadioOptions.length; x++)
{
if (AllRadioOptions[x].checked && ThisChecked === 'No' && problem_desc.value === "")
{
ThisChecked = 'Yes';
break;
}
}
var AlreadySearched = ShowAlert.indexOf(ThisRadio);
if (ThisChecked == 'No' && AlreadySearched == -1 && problem_desc.value === "")
{
ShowAlert = ShowAlert + ThisRadio + ' option must be selected\n';
}
}else if(AllFormElements[i].type =='textarea')
{
// add your rest of text area validations here
var problem_desc_1 = document.getElementById("problem_desc");
if(problem_desc_1.value === "")
{
ShowAlert = ShowAlert + '"Services (Please Specify)" can not be blank. \n';
}
}
}
if (ShowAlert !== '')
{
alert(ShowAlert);
return false;
}
else
{
return true;
}
}
You need to add a check for textarea as well
In your javascript check you have only added a condition for type radio.
check for textarea type as well and add error if the value is blank.

Can't get JavaScript to check for null objects

I really don't know what the issue is here. As far as I can see, the code is simple and should work fine.
var Prices="";
for (var PriceCount = 1; PriceCount <= 120; PriceCount++) {
var CurrentPrice = "Price" + PriceCount;
if (prevDoc.getElementById(CurrentPrice).value != null) {
if (Prices == "") {
Prices = prevDoc.getElementById(CurrentPrice).value;
} else {
Prices += "," + prevDoc.getElementById(CurrentPrice).value;
}
} else {
break;
}
}
There could be up to 120 hidden inputs on the form. The moment we check for an input that doesn't exist the loop should break. My test page has two input elements that get pulled. On the third (the null) I get this error in firebug:
prevDoc.getElementById(CurrentPrice) is null
if (prevDoc.getElementById(CurrentPrice).value != null) {
Yes it is null...that's what the check is for ಠ_ಠ
Does any one know what I'm doing wrong? This seems like it should be really straight forward.
EDIT:
for clarity's sake, prevDoc=window.opener.document
if (prevDoc.getElementById(CurrentPrice).value != null) {
can be expanded to:
var element = prevDoc.getElementById(CurrentPrice);
var value = element.value; /* element is null, but you're accessing .value */
if (value != null) {
value is never null.
If it is not filled in, the value would be "" or a length of zero.
If the element does not exist, you would check for the existence of the element.
var CurrentPrice = "Price" + PriceCount;
var elem = prevDoc.getElementById(CurrentPrice);
if (elem && elem.value != null) {
I think it should be:
var Prices="";
for (var PriceCount = 1; PriceCount <= 120; PriceCount++) {
var CurrentPriceId = "Price" + PriceCount,
CurrentPrice = prevDoc.getElementById(CurrentPriceId);
if (CurrentPrice != null) {
Prices = (Prices == "") ? CurrentPrice.value : (Prices + "," + CurrentPrice.value);
}
else break;
}
Try
if (prevDoc.getElementById(CurrentPrice) !== null)

Categories

Resources