Javascript - Use document.getelementbyid().value with a variable - javascript

I'm trying to capture the value of a text field on an HTML form using document.getElementById(my_field).value where the variable my_field is passed to my function dynamically, but am hitting a wall.
How do you use a variable in this context?
The function just doesn't seem to parse the contents of the variable my_field, instead treating it as a string no matter whether I use quotes, square brackets or curly braces.
function myFunction() {
var my_field = arguments[0];
var current_value = document.getElementById(my_field).value;
alert ("Current Value: " + current_value);
}
I'm doing it this way because I have multiple records on a form and each row has its own unique id for the required field.
Running the above just does nothing. The alert never pops which I assume is because current_value never gets set.
To add further detail - I tried to simplify everything for the purposes of this question as there's lots of other unnecessary complications that will only detract from the main issue - on my HTML form is a text field which calls my function on onChange
onchange="enforce_multiples('quantity[<?php echo $line_id; ?>]',<?php echo $product['minimum'];?>)"
I've checked that arguments[0] and [1] are being captured correctly by outputting their values to an alert. Everything works fine up until I try to set the quantity_entered value.
<script>
function enforce_multiples() {
var line_id = arguments[0];
var quantity_increments = arguments[1];
var quantity_entered = document.getElementById([line_id]).value;
alert("QE" + quantity_entered);
//var quantity_mod = quantity_entered % quantity_increments;
//var revised_quantity = quantity_entered - quantity_mod;
//alert("RQ: " + revised_quantity);
//document.getElementById([line_id]).value = revised_quantity;
}
</script>
Checked the console and I receive the error: Uncaught TypeError: Cannot read property 'value' of null on the geElementById line

You should write document.getElementById(my_field) instead of document.getelementbyid(my_field).

OK so I got to the bottom of this in case anyone is interested.
In order to use a variable in document.getElementById() you simply add the variable name with no quotes.
var my_variable = "field1";
document.getElementById(my_variable);
The reason this wasn't working on my form was because the text fields only had the name parameter and not an id parameter.
So I needed to change:
<input type="text" name="field_name" value="1234" />
To
<input type="text" name="field_name" id="field_name" value="1234" />
And that sorted it. Otherwise I was just getting generic NULL error messages in the console.

Related

javascript compute mistake (calculator)

I need to make a calculator using JavaScript, HTML and CSS. Everything worked out fine until I came to coding the compute (=) button.
This is my HTML:
<input type="button" value=" = " onclick="compute()">
This is my JS:
function compute() {
var input_var = document.getElementById('input');
ans = Math.floor(+eval(input_var.value));
document.getElementById('answer').value = '=' + 'ans';
}
If anyone that knows how to solve what's wrong, I would greatly appreciate it if you could reply.
First of all, you should post the whole code to get accurate solution!
Probably these could be some of the errors:
Set id attribute of your = button with value "input"
3rd line should be: ans = Math.floor(eval(+input_var.value));
4th line should be: document.getElementById('answer').value = '=' + ans; as StaticBeagle has also mentioned.
You should be lucky that you made the mistake to put the variable in quotes. That's why you don't get a value other than the literal string =ans(maybe, we don't know as you didn't post all code that's needed to give a better answer).
Back to why you're lucky.
Never use eval! eval is evil. (Unless you know what you do, but you don't the next couple of years). To parse a number, you'd use Number(input_var.value).
The next error is that you create a global variable by omitting one of var, let, const for your ans declaration.
The next thing you shouldn't do is to use inline javascript. We use eventListener instead. As said before, it's impossible to answer more specific as your question lacks too many details - however I'll show you how you get a value by pressing a button in the console.
document.getElementById('foo').addEventListener('submit', e => {
// prevent submitting the form (I guess another error in your code)
e.preventDefault();
const value = Number(document.getElementById('input').value);
console.log('The value is: ' + value);
}, false);
<form id="foo">
<input type="number" id="input">
<input type="submit" value=" = ">
</form>
Not sure if ans is a local or global variable, but if its intention is to be a local variable then you should have it like this:
var ans = Math.floor(eval(+input_var.value));
Also, because you're setting the value of your element to '=' + 'ans' you're actually setting it to the actual string 'ans'. If you want to refer to what ans is you should write it like this:
document.getElementById('answer').value = '=' + ans;

Assign variable to form field value

I'm trying to assign a value to a hidden form field, the value comes from a query string parameter. The function to extract the query string parameter works fine, however the function to assign the variable (using document.forms) to the hidden form field value attribute doesn't seem to work, the value is empty if I inspect element, however it works if I run it through the console in Chrome. Many thanks.
Get variable from function that finds query string:
var actionCode = getAllUrlParams().actioncode;
Set hidden form field value:
function setHidden()
{
document.forms[0].action.value += actionCode;
return true;
}
Form HTML:
<input id="field25" name="action" type="text" value="" class="field-size-top-large" disabled="disabled">
Live page is here: http://exhibit.ubm-events.com/LP=83?cid=sm(n)_VIS_DRV20180515%7C1&actioncode=EMA1234
pass the actionCode variable to the function so that it's definitely in scope, and use .getElementById seeing as the element has an ID.
function setHidden(actionCode)
{
document.getElementById("field25").value += actionCode;
return true;
}
Try below code
function setHidden(a,b){
return a*b;
}
document.getElementById('field25').value = setHidden(2, 3);
you need to select the element using jquery and assign the value to it
$("#field25").val("your value")
Ref http://api.jquery.com/val/#val2

How to pass input field name as an argument in javascript function?

I've created a JavaScript function that checks if a certain data already exists in my database. What I want to know is if there is a way to make the input field name in a JavaScript pass as an argument
Here is my code
function checkDataAvailability(displayid,input_id,fieldname)
{
'use strict';
$(document).ready(function(){
//var x = document.getElementByName(fieldname).elements;
$(displayid).load('php/signcheck.php').show();
$(input_id).keyup(function(){
},
$.post('php/signcheck.php', { username: form.x.value },
//$.post('php/signcheck.php', { username: form.fieldName.value },
function(result){
$(displayid).html(result).show();
});
});
});
}
var a = checkDataAvailability ('#userstat','#username_input','username');
A little explanation. The two commented lines are the two methods I've tried to run the field name as an argument separately. Unfortunately they aren't working.
Here is my form
<form action="php/register_exec.php" method="POST" name="form">
Username <span id="userstat" class="checkerr"></span>
<input type="text" name="username" id="username_input" required>
</form>
Passing form fieldnames as argument is no different than passing string argument to functions
var a = checkDataAvailability ('userstat','username_input','username');
Important thing is what you do inside the function.
You can get the value of input field in primarily two ways
Directly read the value using value property as:
document.getElementById('username_input').value
or
document.getElementById(fieldid).value //if you pass fieldid to your function
Use the form field directly
//assuming you pass formname and fieldname as variables to your function
var form = document.getElementById(formname);
var inputvalue = form.elements.namedItems(fieldname).value
You can modify them to suit your jquery syntax if need be.
Since you're already using the jQuery library, you can continue using it.
$('input[name="' + fieldname + '"]').val()
There are 3 ways of achieving what you desire -
If you want to stick with your current code pattern, then replacing form.fieldname with form[fieldname] would get you the correct results. This is because fieldname is a string, and form."some string" would give you an error.
The other two ways are the same as neouser99 and avck specified in their answers.

IE11 Unable to get property 'value' of undefined or null reference

it's seems that I'm having a frustrating problem and can't seem to find an answer.
I'm trying to get the value of the element in <td> tag. The id reaches the function but for some reason I can't get the value of it.
JS
function f(id)
{
console.log(id);
expr=/ /gi;
value = document.getElementById(id).value;
value = value.replace(expr, "");
//remaining code
}
PHP
print "<td style=\"height:20px;\"><input $disbled type=\"text\" name=\"".$values[$i][0]."\" onChange=\"return f('".$values[$i][0]."')\" value=\"".$values[$i][1]."\" class=\"".$values[$i][2]."\"></td>\n";
Any help would be appreciated!
A couple of problems there:
Your element doesn't have an id at all
Your code is falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog).
Here's a fixed version:
function f(name)
{
console.log(name);
var expr=/ /gi;
var value = document.querySelector('[name="' + name + '"]').value;
value = value.replace(expr, "");
//remaining code
}
#1 is fixed by using querySelector and an attribute selector selecting by name
#2 is fixed by declaring the local variables in f
You could also fix #1 by giving your element an id and sticking with getElementById.
The input you are trying to access has not ID property defined. You shall add it in order to access the input object via getElementById().
<input $disbled id=\"".$id."\" type=\"text\" name=\"".$values[$i][0]."\" onChange=\"return f('".$values[$i][0]."')\" value=\"".$values[$i][1]."\" class=\"".$values[$i][2]."\">

Why does this javascript throw this particular error?

In my HTML code I have a button that when pressed runs a javascript function. This is the HTML code for the button:
<button type="button" onclick="repeatName()">Click me!</button>
I want the user to enter something into a text field (which is inside of a form). This is the code for the text field:
<input type="text" name="txtName" />
I want this div's innerHTML to be changed according to the information put in the name textbox once the button is pressed. This is the code for the div:
<div name="editThis" width="50px" height="50px" border="1px">
</div>
When the button is clicked, I want it to run the function below. It is supposed to change the innerHTML of the div.
function repeatName() {
var editField = document.getElementsByName("editThis").innerHTML;
var repeatedName = document.theForm.txtName.value;
editField = (repeatedName + " is the value.")
}
THE PROBLEM IS that whenever the button is clicked, I see this error in the Firefox error console:
Error: uncaught exception: [Exception... "Cannot modify properties of a WrappedNative" nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)" location: "JS frame :: chrome://global/content/bindings/autocomplete.xml :: onxblpopuphiding :: line 825" data: no]
What is this error and how can I correct it?
According to the documentation, document.getElementsByName(str) returns "a list of elements".
It's clear that "a list of elements" doesn't have a singular .innerHTML property. I'd guess that the specific error relates to your browser's internal mechanism for representing that list in its own WrappedNative type.
Iterate the results instead; in your case, you only need the first result, so get it with the array accessor syntax [0].
But, since name properties relate to form components, you should use id instead. Retrieving an element by ID is easier, since IDs are [supposed to be] unique.
Also, since Javascript has no references, you cannot store innerHTML in a variable and change it expecting the original property to change; you must make the assignment in the same statement in which you notate innerHTML:
function repeatName() {
var editField = document.getElementsById("editField");
var repeatedName = document.theForm.txtName.value;
editField.innerHTML = repeatedName + " is the value."
}
I think Tomalak has it right. Alternately, you can give your div an id, and then use getElementById, which will return a single object and not a collection.
i.e.
<div id="editThis" .... > .... </div>
...
...
document.getElementById("editThis").innerHTML = repeatedName + " is the value";
Div elements don't have a name attribute, so use an id instead.
<div id="editThis" ...>
Then use:
function repeatName() {
var editField = document.getElementById("editThis");
if (editField) {
editField.innerHTML = document.theForm.txtName.value + ' is the value';
}
}

Categories