Iterate through all but one elements in a form - javascript

I would love my while to iterate through all but one of the elements in the form. This is my code:
while (i < elnum && !empty) {
if (form.elements[i].value == "" && form.elements[i] != form.referral) {
error.innerHTML += 'All fields are required.</br>';
empty = true;
}
i++;
}
Where elnum is the number of elements.
Unfortunately, even if I leave only form.referral empty, it still enters inside the if. Basically, I want the check to be done for all fields but for that one.

Rather than trying to compare elements, try something like this:
if( form.elements[i].name == "referral") continue;
Put that just inside the loop, before the condition to check for an empty value.
That being said, it might be better to do something like this:
while(i < elnum) {
if( form.elements[i].hasAttribute("required") && form.elements[i].value == "") {
error.innerHTML += "All fields are required.<br />";
// re-add `empty=true` if the variable is needed elsewhere
// if it's only used to end the loop, then this is better:
break;
}
i++;
}
And make sure you add the required attribute to all required fields. This is a better solution because then it will take advantage of the browser's native ability to handle HTML5 forms, if it has any.

Related

JavaScript -- Validating a Certain Number of Inputs

I have 8 form inputs that are asking for either 8 half-day activity dates or, 4 fullday dates.
I collected all of the input values and put them into an array, and to test the collection process, wrote the following function that just says if ALL the inputs are empty, keep a button disabled and if ALL are full, enable the button.
function checkMeetings()
{
for(var i = 0; i < meetings.length; i++)
{
if(meetings[i] === "" || meetings[i] === null)
{
meetingsCanSubmit = false;
}
else
{
meetingsCanSubmit = true;
}
}
}
checkMeetings();
That test worked fine.
What I'd like to do is create a counter that counts the number of input boxes that have been filled in and when it gets to at >= 4 enable the button. (In reality it won't enable the button it's going to run a secondary function but for the purposes of this example I'm keeping it simple.)
Since the for loop is counting via the i++ anyways, I tried something to the effect of
if(meetings[i] <= 4) do the following, but that doesn't seem to be doing the trick. Should I be setting up a second counter within my if-statement?
You can use Array.prototype.filter(), check the .length of resulting array
var meetingsCanSubmit = meetings.filter(function(input) {
return input !== "" && input != null
}).length >= 4;
if (meetingsCanSubmit) {
// do stuff
}

"If" consolidation/avoiding nesting

I'm really trying to avoid nesting in this code snippet...
deal_trade_in_model_1 = document.getElementById('deal_trade_in_model_1').value;
deal_trade_in_amount_1 = document.getElementById('deal_trade_in_amount_1').value;
if (typeof deal_trade_in_model_1 !== 'undefined' && deal_trade_in_model_1 !== null) {
console.log(deal_trade_in_amount_1);
console.log(deal_trade_in_model_1);
if (deal_trade_in_model_1 !== null || deal_trade_in_model_1 !== "") {
if (deal_trade_in_amount_1 == null || deal_trade_in_amount_1 == "") {
console.log('entered into function');
document.getElementById("deal_trade_in_model_1").value = "";
document.getElementById("deal_trade_in_amount_1").value = "";
}
}
}
Basically, what this function does is take the value of two fields... things to know about them and what I want to do to them:
1) They're NOT required
2) If one of them is filled out, the other must be
3) If ONLY one of them is filled out, the user clicks submit, and this part of the function is called upon, I want to delete the value of both of them.
I've tried doing a compound of
&& (and)
and
|| (or)
buttttt it odiously it didn't work.
Primary question: What's the best way to get rid of the nesting (I planned on doing this twice and just swapping the code) that will be the most efficient? This, I want, to be done preferably in the smallest amount of IF statements possible.
Please note: If you change the code a lot, I might not know what you're talking about.. please be prepared to teach me or help me learn!
It sounds like you only want to do something if either of the fields are empty, but not both. Assuming both of the elements are text fields, .value will always return a string. Converting a string to boolean results in false if the string is empty, otherwise true.
So
Boolean(deal_trade_in_model_1) === Boolean(deal_trade_in_amount_1)
will be true if either both fields have a value (both will convert to true) or both fields are empty (both convert to false).
Thus your code can be reduced to
var model_1 = document.getElementById('deal_trade_in_model_1');
var amount_1 = document.getElementById('deal_trade_in_amount_1');
if (Boolean(model_1.value) !== Boolean(amount_1.value)) {
model_1.value = "";
amount_1.value = "";
}

JavaScript Help (Loops and Arrays in Particular)

So I am doing an assignment for a required javascript class and am stuck on a couple of parts specifically. We are supposed to create a guessing game with an array where we prompt the user to guess names and if they match anything in the array to tally it up as points.
Anyway here is the main code, the part that I am stuck on is figuring out how to loop the code so when the user is prompted 3 times for a guess and each guess is taken into account
var sportsArray = ["Football","Basketball","Rollerblading","Hiking","Biking","Swimming"];
var name = prompt("Please enter your name.", "Enter Here");
var arrayGuess = prompt("Guess a sport.", "Enter Here");
var counter;
for (counter = 0; counter < sportsArray.length; counter++) {
if (arrayGuess === "Football"||"Basketball"||"Rollerblading"||"Hiking"||"Biking"||"Swimming"){
alert("Good Job");
} else {
arrayGuess;
}
}
So the goal is to prompt the user to guess a part of the original array and if they do let them know that, but if they don't take points away and make them guess again until they have guessed 3 times.
Anyway if someone could lend a hand it would be appreciated.
You cannot simultaneously compare one item to a whole bunch of things like this:
if (arrayGuess === "Football"||"Basketball"||"Rollerblading"||"Hiking"||"Biking"||"Swimming")
Instead, you have to compare it to each individual item:
if (arrayGuess === "Football"||
arrayGuess === "Basketball"||
arrayGuess === "Rollerblading"||
arrayGuess === "Hiking"||
arrayGuess === "Biking"||
arrayGuess === "Swimming")
Or, there are more effective ways to compare to multiple items such as:
if (" Football Basketball Rollerblading Hiking Biking Swimming ".indexOf(" " + arrayGuess + " ") !== -1)
Or, using an array:
if (["Football","Basketball","Rollerblading","Hiking","Biking","Swimming"].indexOf(arrayGuess) !== -1)
Or, if this comparison happened a lot, you'd build an object ahead of time and use it for a lookup:
var items = {"Football":true,"Basketball":true,"Rollerblading":true,"Hiking":true,"Biking":true,"Swimming":true};
if (items[arrayGuess] === true)
If you want to compare without regards for proper case, then you can lowercase what the user entered and compare that to lower case test values:
var items = {"football":true,"basketball":true,"rollerblading":true,"hiking":true,"biking":true,"swimming":true};
if (items[arrayGuess.toLowerCase()] === true)
FYI, it's also not clear why you're using a loop here at all. No loop is needed to prompt once and test against all the possible sports values.
If you have to cycle through an array with a loop, then you can do this:
var items = ["football","basketball","rollerblading","hiking","biking","swimming"];
var testVal = arrayGuess.toLowerCase();
var match = -1;
for (var i = 0; i < items.length; i++) {
if (testVal === items[i]) {
// found a match
match = i;
break;
}
}
if (match !== -1) {
// items[match] was the match
} else {
// no match
}
I see a couple of things wrong here, as was already mentioned, your comparison in the if statement needs to reference the variable each time it is compared. But additionally, since you are in a loop based on the length of your sportsArray variable, it would be better to not reference strings at all in the if statement, and instead do something more like the following:
if (arrayGuess === sportsArray[counter]) {
// Do stuff here
} else {
// Do other stuff here
}
Additionally, your else clause isn't going to behave quite like you are expecting it to. You are going to have to assign a new value to it, probably by way of another call to prompt. As of now you are only referencing the variable, which will do nothing. If you need to take three guesses, I would add an 'else if' clause into the mix where you get a new value for the variable, an let the else clause display a score and break out of the loop.
if (arrayGuess === sportsArray[counter]) {
// Add to the score
} else if (counter < 2) {
// We prompted for the first guess before the loop,
// so take the second and third here
arrayGuess = prompt("Guess a sport.", "Enter Here");
} else {
// Display score then break to exit the loop
break;
}

A jQuery 'if' condition to check multiple values

In the code below, is there a better way to check the condition using jQuery?
if(($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
Unless there are other concerns, like if you will reuse the #test1, ... fields for more processing, yours should be good.
If you will fetch any of the values again to do something I would recommend storing the $('#test1') result in a variable so that you do not need to requery the dom.
Ex:
var t1 = $('#test1');
if((t1.val() == 'first_value')||($('#test2').val() == 'second_value') && ($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value')) {
t1.val('Set new value');
}
This also improves readability of the row ;)
var values = ['first_value', 'second_value', 'third_value', 'fourth_value'];
$('#test1, #test2, #test3, #test4').each(function(index, el) {
if($.inArray(this.value, values)) {
// do some job;
return false; // or break;
}
});
var c=0, b='#test', a=['first_value','second_value','third_value','fourth_value'];
for(var i=0; i<4; i++)
if($(b+i).val() == a[i])
c=1;
if (c) //Do stuff here
This will decrease your code size by 25 bytes;-)
Demo: just another idea is at http://jsfiddle.net/h3qJB/. Please let me know how it goes.
You can also do chaining like:
$('#test1, #test2, #test3, #test4').each(function(){ //...use this.value here });
It might be that De Morgan's laws gives you an idea of how to make the logic a bit more compact (although I am not sure what is the specific case or is it as simple as comparing values).
Code
var boolean1 = (($('#test1').val() == 'first_value')||($('#test2').val() == 'second_value'))
var boolean2 = (($('#test3').val()!='third_value')|| ($('#test4').val()!='fourth_value'))
if (boolean1 && boolean2)
alert("bingo");
else
alert("buzzinga");

how to check if a checkbox exists

The check box's exist for each row. the table is created by PHP and I need a way to check if the check box exists. when they are created they are given the ID of checkbox_(an incrementing number).
This is what I have so far, but it does not work on checking if the element exists.
var check = true;
var todelete = "";
var counter = 0;
//check if box exisits and record id and post
while(check)
{
if ($("#Checkbox_"+counter).length > 0)
{
todelete = todelete + $("#Checkbox_"+counter).value;
counter = counter + 1;
}
else
{
check = false;
}
}
I have also tried
if ($("Checkbox_"+counter))
if (document.getElementById("tbody").value == null)
Update:
Even with the # symbol or if i do it by javascripts element ID - when I debug the DOM, it hits the while, then the if, adds the value to todelete, adds 1 to the counter, then it goes back to the while, then hits the if
Then bounces back up to the while without even going into the if or the else???
this I do not understand, then it just bounces up and down between the two lines and crash's the browser?
Update2:
I needed to .tostring() the counter when adding it to the string for an element id. problem solved
You can use
if ($("#Checkbox_"+counter).length > 0)
I'm assuming that 'Checkbox_0' is an ID, so I've added the # symbol. If it's the name of the checkbox, you can use
if ($("input[name='Checkbox_"+counter+"']").length > 0);
[edit]Also, you should check to make sure you do / don't need the capital 'C'.
You can use for "checkbox exists in this case"
if ($("#Checkbox_"+counter).length > 0) {
//checkbox exists
}
if (($("#Checkbox_"+counter).length) > 0) {
...
//Or something more generalized
jQuery.fn.exists = function(){
return jQuery(this).length>0;
}
//then, if you have valid selector
if ($("#Checkbox_"+counter).exists()){
//do something here if our selected element exists
}
// if document.getElementById(name) do not exist
// document.getElementById(name).value generate already an error
if (document.getElementById(name) != null) {
// you code if checkbox exist
}

Categories