I'm trying to get the value of a time input element via JavaScript. When I try using getElementById the value that is displayed is:
[object HTMLInputElement]
If use querySelectorAll, the value is:
[NodeList]
I also tried to use the index, but nothing new happens.
Here is my HTML:
<div class="principal-grid">
<title>Hour Control</title>
<label class="description-values">In</label>
<input id="data-in" type="time" class="values">
<label class="description-values">Interval - SaĆda</label>
<input id="data-interval-s" type="time" class="values">
<label class="description-values">Interval - Volta</label>
<input id="data-interval-v" type="time" class="values">
<label class="description-values">Out</label>
<input id="data-out" type="time" class="values">
<input id="submit" type="submit" class="send" value="Send">
</div>
And this is the script:
var dataIn = document.getElementById(['data-in']);
var dataInterval_out = document.getElementById(['data-interval-s']);
var dataInterval_in = document.getElementById(['data-interval-v']);
var dataOut = document.getElementById(['data-out']);
document.getElementById("submit").onclick = function (e) {
//test
document.getElementById("test").innerHTML = dataIn + ' ' + dataInterval_out +
' ' + dataInterval_in + ' ' + dataOut;
}
A couple of things to note here:
First up, when you use: var dataIn = document.getElementById(...)
It's returning a reference to the html element identified by the Id string and storing it in the dataIn variable you created. If you want the value of that element, you need to use: dataIn.value.
Here's an updated version of your script that does what I think you want:
var dataIn = document.getElementById('data-in');
var dataInterval_out = document.getElementById('data-interval-s');
var dataInterval_in = document.getElementById('data-interval-v');
var dataOut = document.getElementById('data-out');
document.getElementById("submit").onclick = function (e) {
//test
document.getElementById("test").innerHTML = dataIn.value + ' ' + dataInterval_out.value +
' ' + dataInterval_in.value + ' ' + dataOut.value;
}
The second thing is that getElementById takes a string value. You're wrapping it in []'s, which is unnecessary.
One last note: type="time" is not supported on all browsers. (Safari doesn't support it for example). So you may want to look for an alternative method for collecting dates, if supporting macOS and iOS devices is important to you.
To get value of input using vanilla js, use .value property.
var dataIn = document.getElementById('data-in').value;
var dataInterval_out = document.getElementById('data-interval-s').value;
var dataInterval_in = document.getElementById('data-interval-v').value;
var dataOut = document.getElementById('data-out').value;
Also, getting element by id, use document.getElementById('elementId')
Related
I must be screwing something up. When I try to use querySelector() in Javascript I can't seem to modify the value, onblur and onfocus clauses of an input tag but I can modify it's id and name using JavaScript. Help!
I cloned a chunk of HTML code with the following;
const newAdjustment = lastAdjustment.cloneNode(true);
The input tag I'm modifying looks like this;
<input type="text" class="form-control text-right entered-amount"
id="Amount15" name="Amount15" value="$3.00"
onfocus="deformatAmount(15)" onblur="recalc(15)">
</input>
I have no problem using querySelector() to modify the id and name of the input tag;
const originalSequenceNumber = 15;
const newSequenceNumber = originalSequenceNumber + 1;
const originalAIdName = 'Amount' + originalSequenceNumber;
const newAIdName = 'Amount' + newSequenceNumber;
newAdjustment.querySelector("#" + originalAIdName).id = newAIdName;
newAdjustment.querySelector("#" + newAIdName).name = newAIdName;
This leaves me with the following;
<input type="text" class="form-control text-right entered-amount"
id="Amount16" name="Amount16" value="$3.00"
onfocus="deformatAmount(15)" onblur="recalc(15)">
</input>
I then try to modify value, onblur and onfocus with the following;
const newAOnfocus = 'deformatAmount(' + newSequenceNumber + ')';
const newAOnblur = 'recalc(' + newSequenceNumber + ')';
newAdjustment.querySelector("#" + originalAIdName).value = "$0.00 ";
newAdjustment.querySelector("#" + newAIdName).onfocus = newAOnfocus;
newAdjustment.querySelector("#" + newAIdName).onblur = newAOnblur;
and nothing happened. newAOnFocus, newOnBlur and the input element are as follows;
newAOnfocus = deformatAmount(16)
newAOnblur = recalc(16)
newAdjustment = <input type="text" class="form-control text-right entered-amount" id="Amount16" name="Amount16" value="$3.00" onfocus="deformatAmount(15)" onblur="recalc(15)">
After I append the child to the document and use document.querySelector() I can modify the value but not the onblur or onfocus clauses. What am I doing wrong? What clause am I missing from querySelector()? By the way, there a three input and three button tags in newAdjustment and I'm having the same problem with all six.
Correction about .value
.value was updated correctly. The page reflected the correct value in .value but when I did a console.log() of newAdjustment it displayed the original value from the cloning (.cloneNode()). I'm wondering if I'm having the same problem with the rest, which means I'm actually not having a problem at all. More testing to follow.
You can use setAttribute on the input.
So
newAdjustment.querySelector("#" + originalAIdName).value = "$0.00 ";
newAdjustment.querySelector("#" + newAIdName).onfocus = newAOnfocus;
newAdjustment.querySelector("#" + newAIdName).onblur = newAOnblur;
Becomes
newAdjustment.querySelector("#" + originalAIdName).setAttribute("value", "$0.00 ");
newAdjustment.querySelector("#" + newAIdName).setAttribute("onfocus", newAOnfocus);
newAdjustment.querySelector("#" + newAIdName).setAtribute("onblur", newAOnblur);
I am trying to dynamically assign variable names using the user's input. For example:
var input = document.querySelector('input');
for(var i = 0; i < 10; i++){
var newVariableName = //input.value;
}
Any help would be very much appreciated.
Thank you,
Scratch Cat
Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:
Specify them the fixed way (e.g. obj.propertyName = 'Value')
Specify them using array notation (e.g. obj[propertyName] = 'Value'). In this case, note that propertyName is a string value.
In both cases, the result will be exactly the same. You could retrieve those properties likewise, e.g. obj.propertyName and obj[propertyName]. Both will return 'Value'.
In your case, #LuudJacobs's suggestion about using the window object will most probably do the trick...
You can use array in which the keys will be the input values and the value would be anything you want.
html
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
js
First you declare array
var a = new Array();
Then you use for loop to assign key names to array which will be the input values
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
Finally you can use those key names to access the values
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
Here is a link to an example
https://jsfiddle.net/309fpsjn/1/
<html>
<form>
<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">
</form>
<script>
var x = document.querySelectorAll(".example");
var a = new Array();
for(var i = 0; i < 3; i++){
a[x[i].value] = x[i].value;
}
alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);
</script>
</html>
I need something like an associative array that contains pairings of variable name / element ID.
Looping through this array/object, assign the element ID to the variable name that is its counterpart. Something like this:
jsFiddle
HTML:
<input id="fld_1" class="input" type="text" value="bob" /><br>
<input id="fld_2" class="input" type="text" value="fred" /><br>
<input id="fld_3" class="input" type="text" value="pat" /><br>
<input id="mybutt" class="btn" type="button" value="Test" />
JS:
objFields = {'f1':'fld_1', 'f2':'fld_2', 'f3':'fld_3'};
arrErrors = [];
$('#mybutt').click(function(){
alert('iii');
for (var key in objFields){
// eval(key = objFields[key]);
eval(key) = objFields[key];
alert('f1: ' +f1);
}
});
There is no requirement to using eval, I just need to turn the key into the variable name.
Where have I gone wrong?
Solution
JCOC611 got it right, but I wasn't clear in how I asked the question. As demo'd in this revised fiddle which implements JCOC611's solution, the variable/field names had to be used to get the value of the field contents, like this:
$('#mybutt').click(function(){
for (var key in objFields){
var tmp = objFields[key];
eval('var ' + key+ ' = $("#' +tmp+ '").val()');
}
});
If you know what you are doing and are absolutely sure about it, then use this:
eval(key + " = " + JSON.stringify(objFields[key]));
Or, if you want local variables:
eval("var " + key + " = " + JSON.stringify(objFields[key]));
Otherwise, I advice you implement one of the other answers.
You don't need that eval() at all, and you want to avoid it. All you really need to do is:
for (var key in objFields){
alert(key+': '+objFields[key]);
window[key] = objFields[key];
}
Will give you:
'f1':'fld_1'
'f2':'fld_2'
'f3':'fld_3'
Where:
f1 = 'fld_1';
f2 = 'fld_2';
f3 = 'fld_3';
If it is a global variable, it is as simple as:
window[key] = objFields[key];
or
window.key = objFields[key];
The second one is a bit less weird name immune.
The eval function runs a string add code and returns the result.
What your code did was evaluate the vague of key which is undefined and then tried to set it to a new value.
Is like writing 5=4;
Correct syntax:
eval('var ' + key + ' = ' + objFields[key]);
want to make values of the oject's dynamic (from user input) but I get "undefined". The idea is to have 3 input fields and the user should input values in them which will fill up the alert message.
<script type="text/javascript">
function Family (fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +", my mother's name is "+ this.motherName +" and my sister's name is " + this.sisterName +".");
}
}
var Me = new Family(
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter);
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
</script>
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="fatherId" />
<input type="submit" value="Send" onclick="Me.myFamily();">
Also I'm looking for a way how user can add or remove properties (values in them, too).
There are a few things wrong with your code.
You've used your variables here
Family["fatherName"] = father,
Family["motherName"] = mother,
Family["sisterName"] = siter); // This should be sister by the way
before declaring them here
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value; // Doesn't exist
Try switching the statements so you're declaring the variables first.
Also, there is no sisterId, you've used fatherId twice.
You're also calling javascript before the DOM is ready. If you're using jQuery, wrap your JS in
$(document).ready(function() { }
or if you want to stick with plain JS, try
window.onload = function() { }
You'll have to be more specific on what myFamily is supposed to do, since you haven't even mentioned that method.
Here is the working snippet of your example.
<input type="text" id="fatherId" />
<input type="text" id="motherId" />
<input type="text" id="sisterId" />
<input type="submit" value="Send" id="submit" />
<script>
function Family(fatherName, motherName, sisterName) {
this.fatherName = fatherName;
this.motherName = motherName;
this.sisterName = sisterName;
this.myFamily = function() {
alert("My father's name is " + this.fatherName +
", my mother's name is " + this.motherName +
" and my sister's name is " + this.sisterName + ".");
};
}
document.getElementById("submit").onclick = function() {
var father = document.getElementById("fatherId").value;
var mother = document.getElementById("motherId").value;
var sister = document.getElementById("sisterId").value;
Me = new Family(father, mother, sister);
Me.myFamily();
}
</script>
All the mistakes are summarized very well by Brandon.
*EDIT: (anser to your comment)
Your code has two execution related problems.
<script> tags are executed immediately and therefore if you insert script before the <input> part then there are no input elements available for you to retrieve.
You want to retrieve values of the inputs, but those inputs contain data when user clicks on the submit and therefore must be read using .value() at the onclick time. If you try to read them outside the onclick part then they are accessed immediately during page load when the input fields are empty.
thanks for looking.
im still learning the more complex javascript and jquery coding so could do with some help as i have no idea about the following or even if its possible!
i need a better/simpler/shorter way of doing the following (please note i have removed the irrelevant validation etc coding):
'
function Findbox5( myform, box1, box2, box3, box4, box5, Storeall, s1, s2, s3, s4, s5)
{
//store values
Myform = document.forms.myform;
box1 = Myform.box1.value;
box2 = Myform.box2.value;
box3 = Myform.box3.value;
box4 = Myform.box4.value;
box5 = Myform.box5.value;
s1 = Myform.s1.value;
s2 = Myform.s2.value;
s3 = Myform.s3.value;
s4 = Myform.s4.value;
s5 = Myform.s5.value;
//set as one string
Storeall = s1 + ":" + box1 + ";" + s2 + ":" + box2 + ";" + s3 + ":" + box3 + ";" + s4 + ":" + box4 + ";" + s4 + ":" + box5 + ";" ;
// next function...
} '
as you can see i have 5 input boxes and relevant selects for each box(each select has 4 options:1,2,3,4.). when a user enters data into a box they choose a relevant option. all boxes and options must be entered then they submit the form.
this data will be emailed to me as the variable stored under storeall. which would be something like 1:1234;2:1324;1:3232;4:5434;2:3211;
so what i hope to do is simplify this data into the following with either a seperate function or the same one: 1:1234-3232;2:1324-3211;4:5434;
is this possible? or have i done it the easiest way?
any comments or help welcomed, thanks again
First, you'll want to group these things into a single element that can be iterated against. So if your HTML looks like:
<form>
<input name="s1" />
<input name="box1" />
<input name="s2" />
<input name="box2" />
...
</form>
Then it's probably better to do something like:
<form>
<div class="set">
<input class="s" name="s1" />
<input class="box" name="box1" />
</div>
<div class="set">
<input class="s" name="s2" />
<input class="box" name="box2" />
</div>
...
</form>
Now you've established some commonality among these elements, instead of just different names/IDs. Each set of inputs is grouped by the .set class, and within each set, you know there's going to be two inputs: one with the .s class, and one with the .box class. Now iterating against them with JQuery is easy:
var str = "";
$("form div.set").each(
function(index, element)
{
currentValueS = $(element).find("input.s").val();
currentValueBox = $(element).find("input.box").val();
str += currentValueS + ":" + currentValueBox + ";";
}
);
This uses JQuery's .each() function. .each() allows you to provide a function to perform on each of the elements that JQuery finds from the indicated selector. Here, your selector is form div.set, which means "all div elements that have the class of .set, and are found anywhere under any form element". For each of these elements, you'll need to find the value of the <input> element with the .s class, and also the value of the <input> element with the .box class. Then you just add those to your growing str variable.
If you want everything in the form, you should use serializeArray :
$('#my_form').submit(function() {
var str = '';
$.each($(this).serializeArray(), function () {
str += this.name + ":" + this.value + ";";
});
sendByMail(str);
return false;
});