Getting the length of a textbox value or content using JavaScript - javascript

This is something that's driving me nuts:
I have this code and it works: I am trying to learn JavaScript before becoming addicted to JQuery. My sample project involves getting the value of the text-box, and validating according to it's length. the name of the form is membership.
Example: This works:
function validateForm()
{
var element = document.membership;
if(element.txtName.value == "")
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
But this doesn't:
function validateForm()
{
var element = document.membership;
var nameLenght = element.txtName.value.lenght;
if(nameLenght < 1)
{
element.txtName.className = "alert";
}
else
{
element.txtName.className = "";
}
}
Just an FYI: I am new to JavaScript but very familiar with the syntax. I just want to learn the basics and move up.
I even read some solutions on here but feel I am simply sinking deeper.
Thanks for your help.

May be it is just because of typo in length here:
element.txtName.value.lenght;
must be element.txtName.value.length;.
If you want it to run every time user presses key , then look here: How to check string length with JavaScript

you can use this function as well
var a = txtName.value;
if (a.length < 1) {
alert('your message');
return false;
}

Related

Promises and for loops - trying to validate multiple element text

I am working on a function that will read the text of elements after using a filter feature. I have printed out the returned text and it is getting the elements, however I do not think I understand js promises.. activeFilters is a var I have already identified.
this.verifyColorFilterFunctional = function(color) {
var bool = true;
activeFilters.count().then(function (count) {
var amt = count - 1;
for (var i = 0; i < amt; i++){
activeFilters.get(i).getText().then(function(text) {
bool = (color === text);
console.log(bool);
});
if (!bool) {
break;
}
}
});
return expect(bool).to.become(true);
};
The console.log prints out true and false as desired, however there are two things I have noticed. When false, it doesnt break like I told it to in the if statement. Also, I am getting a typeError: true is not a thenable error.. I believe the logic sounds good in my head but not to JS. Any help would be greatly appreciated.
Protractor's element.all() supports getText() method which will return you the text displayed in the elements as an array.Then you can easily compare the resultant array using expect method.
this.verifyColorFilterFunctional = function(color) {
activeFilters.getText().then(function (textArray) {
expect(textArray).to.equal(Array(textArray.length-1).fill(color));
});
}

Looping through a ASP.NET Listbox with Javascript not working

I'm trying to loop through an ASP.NET listbox with Javascript, but I'm getting a null object or undefined when it hits the lboxRight variable in the for loop. Here's what I have.
function save() {
var containsTypeA = false;
var containsTypeB = false;
var containsType = false;
var lboxRight = $get('<%=lboxRight.ClientID %>').value;
if (lboxRight != null) {
for (var i = 0; i < lboxRight.options.length; ++i) {
if (lboxRight.options[i].value == "Type A") {
containsTypeA = true;
}
if (lboxRight.options[i].value == "Type B") {
containsTybeB = true;
}
}
containsType = true;
}
}
There's an onclick event mapped to when the save button is pressed that calls this function. Am I doing this the right way to look at the listbox and tell me if it has this specific value in it? My intention is for the listbox to contain Type A as a value and then when it loops through the listbox, if it finds that value within the list it will set that variable to true for some other logic. Visual Studio seems to complain about the for loop line, what am I doing wrong here? I am using the exact same loop written elsewhere and it works fine, so I am not understanding why this one isn't working.
Is there anything wrong with this as I have written it?
If it is complaining about something being null or undefined on the for loop line I would check to see what lboxRight.options is since you already check lboxRight.
Actually it wouldn't make sense for options to exist since lboxRight is being set to the value of the select not the select.
Try changing
var lboxRight = $get('<%=lboxRight.ClientID %>').value;
to
var lboxRight = $get('<%=lboxRight.ClientID %>');

How to detect if a user input has been repeated?

I'm trying to make hangman in javascript and I want to check if the user has used a letter already. I made a var letterGuessValue = to 0 and if they add an input it = 1. I know this would say know to everything if i got it to work (it doesn't even do anything) but am I on the right track maybe? Here's my code. http://jsbin.com/aWOnAfe/5/edit
I would say add an input to a list and whenever they add another input (aka letter), check this list to see if it is already in there. If it is, then its because they've already used that letter before. If not, then it is a new letter.
I don't see where the difficult part is.
http://jsfiddle.net/DerekL/jgqQ9/
Sample code
var used = {};
$("input").keyup(function(){
var val = this.value;
alert( used[val] ? "Used" : "Not used" );
this.value = "";
used[val] = true;
});
How it works
Assign true to used.LETTER when a letter is entered. Before assigning it though, if it was undefined then it hasn't been used. If it is true then it is used.
Sometimes developers tend to use an Array to record pressed keystrokes when doing key combinations, but in this case, iterating an Array would require both more memory and computation power. A simple object is an enough fit.
Use an array to store all of the used letters and function like this to add new ones.
var inputs = []
function addLetter(letter){
var used = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i] == letter){
used = true;
break;
}
}
if(!used){
inputs.push(letter);
}
}
The easiest way is to append each letter to a string, like this:
var letters = '';
var letterPressed = 'X'; // uppercase it if appropriate for your language
if (letters.indexOf(letterPressed) > -1)
{
// you already pressed it
}
else
{
letters += letterPressed;
}
You can also use an array to store your list of presses, although IMO that's overkill.

Seeing if input matches array if not alert

var tagAllowed = true;
var allowedTags =["Person","People","Dance","Word"];
if(tagAllowed === true) {
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
tagged.append('<span unselectable="on" class="tagged '+colorize+'" title="Click To Delete">'+inputVal.trim()+'</span>');
tagSize = $('.tagged').length;
var ele = $('.tagged').last(),
subtract = parseInt(ele.outerWidth(true),10);
input.width(input.width() - subtract);
tagged.width(tagged.width() + subtract);
input.css('marginLeft','5px');
input.val("");
input.css('color','#000');
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
The following code works in a way, if the input.val() does not match it will show the custom alert errorMess and well even if the word matches it still shows the custom alert. I am wondering if maybe I am doing something wrong in my conditional. As I don't need the custom alert to appear if the words match.
If any suggestions please post. I know this isn't the best example with just a code, but I hope all of you get what I am trying to say. I just don't want the custom alert to appear if the two words match together.
You have the if-statement inside the for-loop. The input value will never equal more than one of the tags in the array. You could use a for-loop to set a boolean. Then the if-statement could follow the for-loop.
boolean isAllowedTag = false;
for(var i=0;i<allowedTags.length;i++){
var aTags = allowedTags[i];
if(input.val().toLowerCase() === aTags.toLowerCase()) {
isAllowedTag = true;
break;
}
}
if (isAllowedTag) {
// ...
} else {
errorMess.children('span').remove();
errorMess.prepend('<span>'+errorProcess+'<span>');
errorMess.slideDown();
}
}
add a break; after your input.css('color, '#000'); line. also, you should really change those last 3 lines to: input.val("").css({marginLeft:'5px', color:'#000'});. Making calls to .css() is slow, so it's better to do as much as you can in one call.

validate 2 dropdowns (only some combinations valid)

I am completely new to JavaScript.
I have size and color dropdowns on a page for users to order a product, but only certain combinations are available i.e. pink is the only color in large sizes.
I thought I'd make an array of allowed sizes and test the user input against these.
If the choice is invalid then I want a popup to tell the user why.
In the real world I'll use SQL & PHP to create the array of allowed choices, in the example below I've hard coded 3 valid choices for testing. Unfortunately the code below doesn't do anything.
I'm sure it's a simple newb mistake. I really don't know what I'm doing :)
Can somebody help me out?
The validation function is supposed to happen when user clicks the form submit...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
Here's the function:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
There are a few lines where you use the assignment operator (that is single equals =) instead of one of the equality operators (that is double or triple equals, triple is usually preferred in JavaScript). Example:
if (found = "false") {
Would appear to be the problem at first sight - it's an assignment not a comparison :) use triple equals === instead of single:
if(found === "false") {
Also, consider the following (commented) updates to your code, which reflects more the typical style of JavaScript code:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}

Categories

Resources