I'm in the middle of creating a program in the browser which compares the selections of the user with a list of pre-defined holidays using Objects. I tried to create an object from the selections of the user to use in comparisons and select the most matching holiday, however when I try to select the value (adding .value) it seems to break the flow of Java, and none of the code read afterwards is read.
var climateVar = document.getElementById('climateselect')/.value\;
var accVar = document.getElementById('accomadationselect')/.value\;
var durationVar = document.getElementById('duration')/.value\;
var userInput = new Input(climateVar/.value\, accVar/.value\, durationVar/.value\);
for (var key in userInput) {
var woo = userInput[key];
document.getElementById('someDiv').innerHTML += woo/.value\;
}
without any .value/s, this prints[object HTMLSelectElement]null[object HTMLSelectElement] - (I changed "getElementById" to "querySelector" which simply made it print "nullnullnull")
, but when I try to add .value anywhere, the entire script stops working, and so everything under this will not run. Why on earth would adding .value stop the script from working? Nothing else changed.
Also, I'm a novice at this, this was meant to be a practice project, but I've been stuck on this for about a day now. any other advice you might feel like giving would also be appreciated
everywhere I typed /.value\ I've tried to add .value, and it has had the effect of stopping the code
Are you sure you are calling value on a valid object? The object has to exist and support .value to get a result - e.g.
http://jsfiddle.net/pherris/t57ktnLk/
HTML
<input type="text" id="textInput" value="123"/>
<div id="divHoldingInfo">123</div>
JavaScript
alert(document.getElementById('textInput').value);
alert(document.getElementById('divHoldingInfo').innerHTML);
alert(document.getElementById('iDontExist').value); //errors out
Related
I'm quite new to coding. My goal is to make a simple "daily planner" page where you can save text in each line. I was trying to do this via local.storage, but I'm not quite sure what I'm doing wrong.
I've tried get vs setitem (which I'm not sure if there's a difference) I tried renaming my elements.
div.text(dailyPlanner[i].hour);
let textbox = $("<textarea>");
textbox.attr("data-hour", dailyPlanner[i].line);
textbox.addClass("col-8 col-md-10 description");
textbox.val(dailyPlanner[i].text);
if (currVal !== null) {
localStorage.setItem(textbox, line);
let textbox = localStorage.setItem(textbox)
}
The key needs to be a string so make the key "textbox" and also, what is the value of currVal? Can you confirm it isn't null?
I see two problems in your setIem call:
You are using an html node as a key (textbox) while you should use a string
You are using line as a value, which is undefined in your present code.
So you can try this instead, or adapt this to your case.
localStorage.setItem(dailyPlanner[i].text, dailyPlanner[i].line);
This has me stumped, and should be pretty simple.
I have an input in my html:
<input type="text" id="fafsaNbrFam" name="fafsaNbrFam" value="<%=nbrFam%>" class="hidden" />
System.out.println(nbrFam); // Works, gives me "6"
Then my js code:
$("#submit").click(function(e) {
var numEntries = 0;
var fafsaNbr = 0;
$("input[name^='name_']").each(function() {
if (this.value) {
numEntries++;
}
});
// EVERYTHING ABOVE HERE WORKS
fafsaNbr = $("input[name=fafsaNbrFam]").val();
alert(fafsaNbr + "X");
// WHERE THE 6 is I want to put the variable fafsaNbr, just hardcoded for now.
if (6 > numEntries && !confirm("The number of members you listed in your household is less than the number you indicated on your FAFSA. Please confirm or correct your household size. ")) {
e.preventDefault();
}
});
On my alert to test this, I get "undefinedX", so basically my jquery to get the value is coming up undefined.
EDIT: So it turns out my code wasn't the problem, but the placement of my input. Even though the original input placement was being processed, once I changed it, it all worked properly. Needless to say, I am still stumped.
You are missing the quotes around the name value. Try:
fafsaNbr = $("input[name='fafsaNbrFam']").val();
Your code is working fine,
I just added your code to jsFiddle and it works
Live EXAMPLE
Could you please make sure, the java scriplet is loading inside the value tag properly or not by checking the view source in browser?
Try to parse the value of the input like this:
fafsaNbr = parseInt($("input[name=fafsaNbrFam]").val());
Or Check whether the $("input[name=fafsaNbrFam]") is undefined or not.
I've found some code on a site and been tinkering with it a little. It involves some functions to add and delete students (the add code is below) from an array - into a value field. I can't figure out why in tarnations we need this extra piece of code, however.
Here is the js code:
var students = ['Paulie', 'Nicole', 'Kevin', 'Mare'];
function addClick(){
var addRemove = document.getElementById('addRemoveStudent');
var studentsBox = document.getElementById('studentsBox')
students.push(addRemove.value);
addRemove.value = '';
studentsBox.value = students.join(', ');
}
My question is: Why do we need the addRemove.value = ''; line? I've tested it without that code and it still works fine. Is there a reason we need that?
I can send more code including the HTML but didn't what to overwhelm anyone with the volume.
Thanks so much in advance!
-Anthony
It's not necessary. I guess semantically it means to clear the addRemove box first before replacing the value.
It's optional, but it's simply to clear the text box so the user can enter a brand new value if they want to run the function again.
To clear the value of the addRemoveStudent ( I think it is a input type="text") Just for it, It is not needed in the array. Just to clear the value of that control.
Presumably addRemove is an input element. Setting the value property of an input element to an empty string '' means that the input is emptied: it will have no text in it.
My guess is that this function is run when a button is clicked, so it adds a new student to the array, updates the studentsBox field with the right data, and clears the input element so you can add more if the user wishes to do so.
I am trying to reduce the repetition in my code but not having any luck. I reduced the code down to its simplest functionality to try and get it to work.
The idea is to take the last two letters of an id name, as those letters are the same as a previously declared variable and use it to refer to the old variable.
I used the alert to test whether I was getting the right output and the alert window pops up saying "E1". So I am not really sure why it wont work when I try and use it.
E1 = new Audio('audio/E1.ogg');
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
fileName.play();
$('#note' + fileName).addClass('active');
});
The code block works when I use the original variable E1 instead of fileName. I want to use fileName because I am hoping to have this function work for multiple elements on click, instead of having it repeated for each element.
How can I make this work? What am I missing?
Thanks.
fileName is still a string. JavaScript does not know that you want to use the variable with the same name. You are calling the play() method on a string, which of course does not exist (hence you get an error).
Suggestion:
Store your objects in a table:
var files = {
E1: new Audio('audio/E1.ogg')
};
$('#noteE1').click(function() {
var fileName = this.id.slice(4);
//alert(fileName); used to test output
files[fileName].play();
$('#note' + fileName).addClass('active');
});
Another suggestion:
Instead of using the ID to hold information about the file, consider using HTML5 data attributes:
<div id="#note" data-filename="E1">Something</div>
Then you can get the name with:
var filename = $('#note').data('filename');
This makes your code more flexible. You are not dependent on giving the elements an ID in a specific format.
Update: clarified question (I hope)
Hi.
I'm developing a plugin in Wordpress and I'm outputting elements according to user privileges A and B.
In case of A, I ouput element "Foo".
In case of B, I output element "Bar".
Up till now, I haven't checked if an element exists before I try to retrieve the value.
This of course gives me a javascript error in some browsers (like IE7).
I've looked at using the typeof() function:
if(typeof(element) == 'undefined') {
//do something...
}
I'm also using jQuery. So one solution could be using this:
if ($("#mydiv").length > 0){
// do something here
}
Using the above methods, makes me having to check each element before trying to retrieve any values.
The "ideal" solution would be to get values based on user privileges. E.g:
if (userPriv == A) {
//get values from element 'Foo'
}
This way I can check once, and do the data gathering. The only solutions I can think of are setting the value of a hidden input element or use cookies.
<input type="hidden" id="userPriv" value="A" />
The other solution would be adding a value to the cookie.
setcookie("userPriv", "A");
Unfortunately, this last option gives me a warning message saying that cookie must be set in header (before html output). I think it's because I'm doing this in Wordpress.
I'm looking for opinions on which method is "the best way" to accomplis this.
Forgive me if I'm missing something, but checking for a DOM element in javascript is usually pretty easy.
var elementA = document.getElementById('id_of_a');
var elementB = document.getElementById('id_of_b');
if (elementA) {
//...
} else if (elementB) {
//...
}
The key is the if statement. getElementById will return nothing null if the element is not found, which will evaluate to false in the if statement.
Alternatively, if you don't really want to check for existence of individual DOM elements, can you send the users priv in a hidden input and act on that? That's a cookie free way of sending values clientside. Something like (edited to have jQuery code instead)
<input type="hidden" id="userPriv" value="A" />
...
var priv = $('#userPriv').val();
if (priv == 'A') {
//...
}
I'd still recommend checking for individual elements over checking a hidden input. It seems cleaner to me, more along the unobtrusive lines
You can use object as associative array:
var map = new Object();
map[A.toString()] = new Foo();
map[B.toString()] = new Bar();
In that case is much simpler to check and you will avoid "spaghetti code".