show/hide div based on form value - javascript

var test = document.getElementById("TEST1").value;
if (test.value != 1) {
document.getElementById("field_DOPT").style.display='none';
}
This doesn't seem to work. I am getting the TEST1 value as 1 but its not hiding the div. Any help will be appreciated. thank you

In your case test is the value of the input element TEST1, it doesn't have a value property
so either assign the element as the value to test then use test.value in your condition
var test = document.getElementById("TEST1");
if (test.value != 1) {
document.getElementById("field_DOPT").style.display='none';
}
or use just test in the condition
var test = document.getElementById("TEST1").value;
if (test != 1) {
document.getElementById("field_DOPT").style.display='none';
}

You have assigned TEST1 value to the test variable, so in test you have do:
if (test != 1) {
document.getElementById("field_DOPT").style.display='none';
}

You already get the value property of your element when you define test, and then you look for the value property of its value property - so the simplest way to improve this code is:
var testValue = document.getElementById("TEST1").value;
if (testValue != 1) {
document.getElementById("field_DOPT").style.display='none';
}
I've changed your variable name from test to testValue so that it's clear that you are not actually dealing with the TEST1 element but instead with its value (so that it is clear there is no need to get the value property.

Related

jquery make alert equal to an array of names

This code above looks to see if my check boxes are checked or unchecked. IF they are unchecked then it logs in the console the names of the checkboxes that are unchecked. I want to take those names and put them in the alert box and am struggling to access the element.name outside the each loop. Anyone have any ideas?
// when page is ready
jQuery("#user_price_accept").submit(function(event) {
// on form submit
event.preventDefault();
var test = jQuery(this).find('input[type=checkbox]:not(:checked)')
var test2 = '';
test.each((i, element) => {
console.log(element.name)
test2 = element.name;
})
return test2;
if (test.length > 0) {
alert(test2);
}
});
jQuery has a handy .map() method which you can use to transform a collection of elements into an array of data.
You could then join that array into a string and alert it
jQuery("#user_price_accept").on("submit", function(event) {
event.preventDefault()
const test = jQuery(this).find('input[type=checkbox]:not(:checked)')
const names = test.map((_, el) => el.name).get() // get() returns the underlying array
if (names.length) {
alert(names.join(", "))
}
})
First, you're returning before the alert. That will stop execution of anything in the same bracket that occurs after that.
Second, you're reassigning test2 inside of your loop. Even if you can access it outside of the loop, all you're going to get is the name of the last element. Try using test2 += ', ' + element.name
Third, this bit here:
if (test.length > 0) {
alert(test2);
}
looks like you are checking the length of an unchanged list. Except the test you defined above is another jQuery object (which I'm not sure has a length built-in, but I digress). Still unchanged though. If this is what you are looking for, that's fine, but I would put the test.each((... inside of the if statment
You are missing concatenation of name and every time test2 gets replaced with a new name. Also returning test2 in function will go outside of function and alert code will not be executed. I have modified few lines
test2 += element.name; // names are added in test 2
return test2; // remove this line or handle after alert code
// when page is ready
jQuery("#user_price_accept").submit(function(event) {
// on form submit
event.preventDefault();
var test = jQuery(this).find('input[type=checkbox]:not(:checked)')
var test2 = '';
test.each((i, element) => {
console.log(element.name)
test2 += "," + element.name;
})
//return test2;
if (test.length > 0) {
alert(test2);
}
});

check if array has the user inputted value

I am using an input field to put user inputs in an array.
I want to check if the user inputted number is already in the array or not. And if it is in the array then the input should not be re-added.
Here is my attempt.
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
var oks = [];
// set num
// check if num is in the oks array
if( oks[num]==num ){
alert("It is already there.");
}
else{
oks[num.value]=num.value;
}
console.log(oks.value);
}
With the above code it says undefined in the console log.
Please help me find where I am wrong in this.
Thanks a lot :)
Your code has lots of mistakes, such as :
var oks = [];
The above is saying that every time the user inputs something, the array is empty, therefore there is nothing there, therefore the value is not there, so there is no use of trying to know whether the value exists or not, because it doesn't, so you should declare the oks variable outside of the eventListener.
oks[num]
The above is not the value, it's the element in the array whose index is the value, which are very different.
num.value
The above is a syntax error, because the num variable is a number not a dom element that has a value attribute.
And here's the solution to your problem :
if( oks.indexOf(num)>-1 ){
alert("It is already there.");
}
else{
oks.push(num);
}
you can do
if(oks.indexOf(num) != -1)
to check whether it lies in the array or not or alternatively you could use oks as an object and check if a fiels of a similar value is defined or not, which should be more efficient
var oks = [];
is being initialised on every request, hence it is always empty, initialise it at a parent/global scope, you should use
var oks = {};
// at a parent scope
if(e.keyCode === 43){
var num = document.getElementById("numbers").value;
// set num
// check if num is in the oks array
if( oks{num} != undefined ){
alert("It is already there.");
}
else{
oks[num]=true;
}
console.log(oks.num);
}

String variable prefixed with undefined in for loop

I have a drop-down on which i use .Change() to trigger a function. Function basically get certain data using getJSON and based on those value in have to create string of array for mp3 file.
Below code is generating string but always prefix undefined to string.
In code you will notice setTimeout which is just to provide certain delay till data received. In below example i am using static value and it still prefix undefined. not sure why may be i have defined variable in wrong manner.
Complete example JSBin
$('.customSurah').change(function(){
//surahNo = $('#surah option:selected').val();
setTimeout(function(){
//countSpan = $('#surah-wrapper').children().length;
surahNo = 1;
countSpan = 7;
var i=0;
for (i = 0; i <= countSpan; i++) {
strCat += surahNo+"/"+i+".mp3,";
console.log(strCat);
}
}, 3000);
});
OUTPUT
undefined114/0.mp3,
undefined114/0.mp3,114/1.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,114/6.mp3,
You have a variable strCat that is not initialized, and then you append a value to it in this line:
strCat += surahNo+"/"+i+".mp3,";
Since strCat is not initialized in first round of loop, you get undefined prepended to your string.
To fix this, you need to initialize the variable to empty value first:
var strCat = ''; // <- initialize your variable to empty value
surahNo = 1;
countSpan = 7;
The outcome is perfectly valid as per javascript is concerned.
Why?
I guess you probably know if you declare any variable in javascript and you don't assign its default value then automatically undefined is assigned. So, that is a valid. What happens when you do that:
var somevar; // non assigned default value set to -> undefined
console.log(somevar); // logs undefined
But,
In your case you have to give it a default value like a blank string var strCat "";. So, now when you do this:
var somevar = ""; // assigned default value to set to -> ""
console.log(somevar); // logs ""
So, the solution to your issue is, you have to initialize/assign a default value to your variable. like:
var strCat = "";

test for null not working

I have a an onclick function, inside this function I want to create a condition for the way some elements are shown in the textarea. added this in the function:
bPlace = bookForm.txtPlace.value;
if (bPlace="null") {
bPlace="!."
}
bookForm.myText.value = bPlace
according to this condition when the value in txtPlace in myForm is not null it should show anything the user puts in. But when I test it, when I type something, instead of showing that, it still shows the (( !. )) in the textarea.
I should say I used "Undefined" instead of Null and still the same thing happened
Can you please tell me what am I doing wrong?
The problem is you are using assignment operator instead of comparision operator
The statement bPlace="null" will assign the string null to bPlace and will return it, which is a truthy value so the if block will always get executed.
bPlace = bookForm.txtPlace.value;
if (bPlace == "null") {
bPlace = "!."
}
bookForm.myText.value = bPlace
But since bPlace is a input value, I think what you are trying to do is if the input is left blank you want to put a default value in that case you can check
bPlace = bookForm.txtPlace.value;
if (!bPlace) {
bPlace = "!."
}
bookForm.myText.value = bPlace
Demo: Fiddle
Which can be further shorten to
bookForm.myText.value = bookForm.txtPlace.value || '!.';
Demo: Fiddle

Weird issue on Jquery .each function

I have a weird issue in my codes
I have something like
var test, result;
$(".class td").each(function(){
test = $(this).find('input').attr('size');
if(test){
result = test * 10;
}
console.log(result);
})
not every td has a input fields so test could be undefined. However, the console will always output a value from the test after test is defined.
For example:
undefined (test = undefined)
undefined (test = undefined)
undefined (test = undefined)
200 (test = 20)
200 (test = undefined)
200 (test = undefined)
200 (test = undefined)
I am not sure what's going on here. Can someone help me out? Thanks.
Define result in the inner scope rather than holding it in the outer scope, since the first result has value your further iterations still holds the old value and that is what you see.
$(".class td").each(function(){
var result ,
test = $(this).find('input').attr('size');
if(test){ //remove this check and you will see NaN for the iterations where test = undefined in your code
result = test * 10;
}
console.log(result);
});
You can also avoid looping the td that doesn't have input fields.
$(".class td:has(input)").each(...
or
$(".class td:has(input[size])").each(...
You could just grab the inputs in the selector, and map the result of each item to an array:
var result = $('.class td input').map(function() {
return $(this).attr('size') * 10;
}).toArray();

Categories

Resources