Why is the value of the input element undefined? [duplicate] - javascript

This question already has answers here:
HTML class not being recognized [closed]
(4 answers)
Closed 3 years ago.
I have a simple form:
<form name="demoForm" id="demoForm">
<label id=”givenNameLabel” class =blueText>Please enter your given name:
<input type = “text” name = “givenName” id= “givenName” value ="nn">
</label>
<button onclick = validate("givenName");>Validate this entry</button>
</form>
But when I try to get the value it is undefined.
I am getting the value either with vanilla JS or with jQuery:
<script type="text/javascript">
function validate(someTextID){
alert("In validate()") //Works
var thisElement = "#"+someTextID; //the text element;
var thisLabel = thisElement + "Label"; //the label for the text element;
var thisValue = $(thisElement).val(); //The value stored in the text box
alert("thisElement is " +thisElement); //Works
alert("thisLabel is " +thisLabel); //Works
alert("thisValue is " +thisValue); //Why is the value undefined?
//more code to take actions depending on thisValue
}
</script>

After straightening out your HTML a bit by replacing your "smart" quotation marks with "normal" ones (as Sebastian Simon mentioned in his comment)
I simplified your code a bit and added a significant part:
return validate(...) in your onclick part makes sure that the return value from your validation function is used to determine whether to submit the form or not.
return falseinside your function will cause the form not to be transmitted (if you return true the form will be submitted)
function validate(textid){
console.log(document.querySelector('#'+textid).value); //Works
//more code to take actions depending on thisValue
return false; // if you don't want to submit the form yet
}
<form name="demoForm" id="demoForm">
<label id="givenNameLabel" class ="blueText">Please enter your given name:
<input type="text" name = "givenName" id= "givenName" value ="nn">
</label>
<button onclick ='return validate("givenName")'>Validate this entry</button>
</form>
Here is an alternative version. I suspect, that you can probably do without the ids of the individual elements and you can re-use your validation function for other input fields, if you address the input fields in a "relative" way, i.e. by looking for a previousElementSibling of the clicked button.
The Array.prototype.forEach.call() is a clumsy looking construct that applies the Array method forEach() to the nodelist returned by document.querySelectorAll() (this version should even work in the Internet Explorer). Inside the forEach() function the click-event is bound to the validate(ev) function for each button with class "validate".
Array.prototype.forEach.call(document.querySelectorAll('.validate'),
function(el){el.addEventListener('click',validate)});
function validate(ev){
var el=ev.target.previousElementSibling;
console.log('validating element '+el.name+', the value is: '+el.value);
//more code to take actions depending on el.name and el.value
ev.preventDefault(); // in case you DON'T want to submit the form yet ...
}
<form name="demoForm" id="demoForm">
<label class ="blueText">Please enter your given name:
<input type="text" name="givenName" value="Carsten">
<button class="validate">Validate this entry</button></label><br>
<label class ="blueText">Where do you live?
<input type="text" name="myhome" value="Hanover">
<button class="validate">Validate this entry</button></label><br>
<label class ="blueText">What are your hobbies?
<input type="text" name="myhobbies" value="coding">
<button class="validate">Validate this entry</button></label>
</form>

Related

Need help using increments and displaying in a textbox

We need to have a textbox where you enter a number, hit a button, and it increments by 1, while staying in the same text box. Here is the code I have so far:
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
JavaScript:
function btnIncrement_onclick() {
// get textbox and assign to a variable
var countTextbox = document.getElementById("txtCounter");
var txtCounterData = txtCounter.value;
var countTextbox.value = 0++;
}
If someone could explain to me how to do it not just give me the answer. I don't know why I'm having such a hard time with this.
Try the following simple code :
function btnIncrement_onclick()
{
//asign the textbox to variable
var textbox = document.getElementById("txtCounter");
//Get the value of textbox and add 1 then update the textbox
textbox.value = parseInt(textbox.value)+1;
}
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
Hope this helps.
In your HTML:
In your html you had a onclick="btnIncrement_onclick()" and that means every click will triggers your function.
In your JS:
function btnIncrement_onclick() {
// Named as countTextbox you input. sou we can use it later.
var countTextbox = document.getElementById("txtCounter");
// Get the current value attribute of it, initialy 0.
var txtCounterData = txtCounter.value;
// The line above is not being used. but you can check it with a console.log like this:
console.log(txtCounterData);
// Now you are calling again your input and changing his value attribute. this ++ means a increment. so we are increasing +1;
countTextbox.value++;
}
You should read more about increment and operators and DOM (the way whe select the tag by id, and again selected his attribute).
Sorry didn't found a good source in english.

Getting data from input using JavaScript

I am trying to get a value out of a <input type='num'> with JavaScript I am using the following code:
Choose a number between 1 and 5 <input type='num' name="input">
<button id="btn">Click me!</button>
<script>
var input;
document.getElementById('btn').onclick = function(){
input = document.getElementById('num');
alert(input); //To check what value input has
</script>
This should get a value but I just get a null what am I doing wrong?
You have not defined your id. Also I guess your input type should be number.
<input type='number' name="input" id="num">
^^^^^^^^^^^^ ^^^^^^^^
And to alert its value you need to use
alert(input.value) //.value is used to get value of input
There are more than one problems with your code
1) You have to close the bracket of your function
it should be
document.getElementById('btn').onclick = function(){
input = document.getElementById('num');
alert(input); //To check what value is outputted
}
2)
input = document.getElementById('num');
The getElementById() method returns the element that has the ID
attribute with the specified value.
so ID attribute is essential here and in your code there is no ID attribute defined so you have to defined it first
like
<input type='number' id="num" name="input">
3) document.getElementById('num'); does not return the value of input field
it returns object
so if you want value then use the following code
document.getElementById('num').value;
4) your input type="number"
for the desired output you can use following code
Choose a number between 1 and 5 <input type='number' name="input" id="myid">
<button id="btn">Click me!</button>
JS
var myButton = document.getElementById("btn");
myButton.onclick = function()
{
alert(document.getElementById("myid").value); //where does id come from?
}
The above method is pure JS if you need jquery method you can refer below
$( "#btn" ).click(function() {
var input=$("#myid").val();
alert(input)
});
getElementById() works on elements with id attribute. So, as you have not put id attribute in your input type, it is not able to find the element with id=num.
Just add id="num" in your input element and then you are good to go.

Javascript change hidden field on submit

Hi I am trying to install a merchant facility onto my website and it needs to submit a value $vpc_Amount which is the amount purchased in cents.
What I need to do is multiply the amount entered by the user ($amount) by 100 to get $vpc_Amount.
I tried the following but it isn't working.
<input type="text" ID="A1" name="amount"onkeypress="process1()">
<input type="hidden" id="A2" name="vpc_Amount">
And then the javascript
function process1() {
f1 = document.getElementById("A1").value;
total = f1*1000;
document.getElementById("A2").value = total;
}
What is happening is it is occasionally working but most of the time it doesn't. I know there is something wrong with the script so hence asking here.
Try to use onkeyup function -
<input type="text" id="A1" name="amount" value="" onkeyup="process1();" />
<input type="hidden" id="A2" name="vpc_Amount" />
javascript function -
function process1() {
var f1 = document.getElementById("A1").value;
var total = (f1 * 100);
document.getElementById("A2").value = total;
}
Use Jquery. http://jquery.com/
$(function() {
$('#form_id').submit(function(){
$('#form_id').find('#A2').val('New value');
return true;
});
});
Have you tried to use onkeyup event? It might be so that onkeypress event is triggered before the character is added to text field.
<input type="text" ID="A1" name="amount" onkeyup="process1()">
Also, I would suggest that you try to convert the value of the textfield to integer and add other input handling too. Users might enter any kind of data there and it can crash your javascript code.
This code should work:
document
.getElementById('A1')
.addEventListener('keyup', function (e) {
document.getElementById('A2').value = parseInt(this.value) * 1000;
})
keypress event triggers before value changes in text field and keyup after value has changed.
Basically event trigger in order:
keydown (onkeydown)
keypress (onkeypress)
keyup (onkeyup)
Force value to be integer or you will get NaN in some cases.
I will suggest to use onblur this is the best way if you want to use the build in attribute listener if you don't use jquery. Here is example:
<!DOCTYPE html>
<html>
<body>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
And url to the example in w3 school :) http://www.w3schools.com/jsref/event_onblur.asp
First of all, I think you should use onkeypup event and not onkeypress
<input type="text" id="A1" name="amount" onkeyup="process1()" value="" />
<input type="hidden" id="A2" name="vpc_Amount" value="" />
Javascript code -
function process1() {
var f1 = parseFloat(document.getElementById("A1").value);
var total = f1*100; //you said 100 so, I changed to 100
document.getElementById("A2").value = total;
}
jQuery code for the same -
jQuery(document).ready(function($){
$("#A1").keyup(function(){
var total = parseFloat($("#A1").val()) * 100;
$("#A2").val(total);
});
});
Your code can be simplified by making use of the fact that form controls are available as named properties of the form baed on their name. This removes the requirement to add IDs to form controls that must have a name anyway.
Pass a reference to the control in the listener:
<input type="text" name="amount" onkeyup="process1(this)">
<input type="hidden" name="vpc_Amount">
Then use the passed reference to get the form and other controls:
function process1(element) {
element.form.vpc_Amount.value = element.value * 100;
}
You may wish to use the change event instead to save updating the hidden field unnecessarily while the user is typing and also to catch changes that aren't based on key presses (e.g. pasting from the context menu).
You should also do some validation of the values entered so the user doesn't attempt to send the form with invalid values (noting that you must also do validation at the server as client side validation is helpful but utterly unreliable).

Pass variable value from form javascript

Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
Here are a couple of examples:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
You don't really need a method or an action attribute if you're simply using the text fields in Javascript
Add a submit button and an onsubmit handler to the form like this,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm function
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}
Try the following in your "submit":
var input = $("#testfield1").val();

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources