Getting data from input using JavaScript - 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.

Related

Javascript reset the whole form that contains default value

How can I reset a HTML form with JavaScript? My form actually contains PHP default value.
I used this to clear:
function reset(){
document.getElementById("moduleform_insert").reset();
}
It works perfectly when there is no <input value="0">.
Is there any method that can clear or I should grab each input value and one by one set to empty?
Hope someone would give some advice. Thanks.
You can use jQuery to do this.
function reset(){
jQuery("#moduleform_insert").val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="moduleform_insert" value="0" />
<input type="button" onClick="reset();" value="Reset" />
And if you have multiple input elements, you can change above reset() function to this one, which will loop through all your input elements and set their value to empty (you can put container id or class in front of input jQuery(".container input") ):
function reset(){
jQuery("input").each(function(){
jQuery(this).val('');
});
}
It works perfectly when there is no .
Is there any method that can clear or I should grab each input value
and one by one set to empty?
This is how reset works
The HTMLFormElement.reset() method restores a form element's default
values. This method does the same thing as clicking the form's reset
button.
If you want to clear the values, then simply fetch them and clear them one by one
var form = document.getElementById("moduleform_insert");
var allNumberAndTextInputs = form.querySelectorAll("input[type='number'], input[type='text'] ");
Array.from( allNumberAndTextInputs ).forEach( function( ele ){
ele.value = ""; //set the value to empty
})
function reset() {
document.getElementById("Form").reset();
}
<form id="Form">
<input type="text">
<input type="button" onClick="reset();" value="Reset" />
</form>
var form = $('#myform');
form.find('input:text,textarea,select').val('');
form.find('input:radio,input:checkbox').each(function(){
this.checked = false;
});
This is the base code. You can add 'input:email', 'input:phone' and so on if you like. Or do something like this:
form.find('input').not(':hidden,:submit').val('');

alerting the value of an input type number

Here is the code that I am having problems with. Below it I'll add an explanation:
$(function() {
var $input = $("#input");
var input = $input.val();
var $go = $("#go");
$go.click(function() {
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
The code above is a dummie example to represent my actual question, no more background is needed.
So I have one input type="number" id="input" in which you input a number, and a button type="button" id="go".
In my jQuery, I first declare $input which holds the element #input, then input which holds the value of the element #input, and finally $go which holds the element #go.
Below that I have a function, that says that when I click on #go, I should be able to alert(input).
Now, this code does not do that. In my head this makes perfect sense, but apparently it doesn't work.
That is because you are declaring input outside the click function, which means the value (simply an empty string) is set at runtime and will not be updated. You should define input within your click event handler:
$(function() {
var $input = $("#input");
var $go = $("#go");
$go.click(function() {
var input = $input.val();
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
First of all, StackOverflow seems to block alerts origination from the code snippet, it will be much easier to output them to the console instead so you can keep track of things.
Your code can be simplified way down without the need for many variables.
But your main problem was the fact that the input value was not getting reset when the click event happened but was getting picked up on page load, meaning it would be stuck at ''.
$(function() {
$("#go").click(function() {
var input = $("#input").val();
console.log(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>

Form HTML not getting updated.

Here's something weird
<form>
<input type="text" id="test" value="abc" />
<input type="submit" />
</form>
<script>
$('form').submit(function(ev){
ev.preventDefault();
alert($(this).html());
});
</script>
http://jsfiddle.net/F6XvW/
I change the value of the input field, then click submit to get the HTML, but the value is not updated inside the HTML? What's up with that? How to get the updated HTML?
What the user inputs is never changing the HTML. It's a form value which will be sent as a parameter to the server.
See here: your jsfiddle updated:
<form>
<input type="text" id="test" placeholder="abc" />
<input type="submit" />
</form>
<script>
$('form').submit(function(ev){
ev.preventDefault();
alert('inputted value = ' + $(this).find('input[type=text]').val());
});
</script>
If you really want to update the DOM, you have to manually set it: http://jsfiddle.net/F6XvW/3/
JS
$('form').submit(function(ev){
ev.preventDefault();
$('#test').attr("value", $('#test').val());
alert('changed input value to: ' + $(this).find('input[type=text]').val());
});
Changing the input of a value does not change the Document Object Model (DOM).
SOLUTION
$('form').submit(function(ev) {
ev.preventDefault();
var newinputval = $(this).find('input[type=text]').val();
var newhtml = $(this).html();
newhtml = newhtml.replace("abc", newinputval);
alert(newhtml);
});
As you see I first receive the new input value, then I get the HTML and replace the DOM's value with the current input value. Now it does exactly the thing that you want.
JSFiddle demo
The value attribute shows the default value, not the current value (which is available in the DOM property of the same name.
If you want to get the current value, then you would have to loop over all the form controls and get their values from the DOM.
You are reading out the initial HTML - changing value on the page will not change in this HTML. Try:
$('form').submit(function(ev){
ev.preventDefault();
alert($('#test').val());
});
...to get the value of the input.
If you want to get value of any input use
$('form').submit(function(ev){
ev.preventDefault();
alert($("#test").val());
});
$('input').val();
in forms you can use .serialize();

How can I count the total number of inputs with values on a page?

I'm hoping for a super simple validation script that matches total inputs on a form to total inputs with values on a form. Can you help explain why the following doesn't work, and suggest a working solution?
Fiddle: http://jsfiddle.net/d7DDu/
Fill out one or more of the inputs and click "submit". I want to see the number of filled out inputs as the result. So far it only shows 0.
HTML:
<input type="text" name="one">
<input type="text" name="two">
<input type="text" name="three">
<textarea name="four"></textarea>
<button id="btn-submit">Submit</button>
<div id="count"></div>
JS:
$('#btn-submit').bind('click', function() {
var filledInputs = $(':input[value]').length;
$('#count').html(filledInputs);
});
[value] refers to the value attribute, which is very different to the value property.
The property is updated as you type, the attribute stays the same. This means you can do elem.value = elem.getAttribute("value") to "reset" a form element, by the way.
Personally, I'd do something like this:
var filledInputs = $(':input').filter(function() {return !!this.value;}).length;
Try this: http://jsfiddle.net/justincook/d7DDu/1/
$('#btn-submit').bind('click', function() {
var x = 0;
$(':input').each(function(){
if(this.value.length > 0){ x++; };
});
$('#count').html(x);
});

Pass a javascript variable value into input type hidden value

I would like to assign value of product of two integer numbers into a hidden field already in the html document.
I was thinking about getting the value of a javascript variable and then passing it on a input type hidden.
I'm having a hard time to explain but this is how it should work:
Script Example
<script type="text/javascript">
function product(a,b){
return a*b;
}
</script>
above computes the product and i want the product to be in hidden field.
<input type="hidden" value="[return value from product function]">
How is this possible?
You could give your hidden field an id:
<input type="hidden" id="myField" value="" />
and then when you want to assign its value:
document.getElementById('myField').value = product(2, 3);
Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.
if you already have that hidden input :
function product(a, b) {
return a * b;
}
function setInputValue(input_id, val) {
document.getElementById(input_id).setAttribute('value', val);
}
if not, you can create one, add it to the body and then set it's value :
function addInput(val) {
var input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('value', val);
document.body.appendChild(input);
}
And then you can use(depending on the case) :
addInput(product(2, 3)); // if you want to create the input
// or
setInputValue('input_id', product(2, 3));
You could do that like this:
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
document.getElementById('myvalue').value = product(a,b);
</script>
<input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">
Hidden Field :
<input type="hidden" name="year" id="year">
Script :
<script type="text/javascript">
var year = new Date();
document.getElementById("year").value=(year.getFullYear());
</script>
Check out this jQuery page for some interesting examples of how to play with the value attribute, and how to call it:
http://api.jquery.com/val/
Otherwise - if you want to use jQuery rather than javascript in passing variables to an input of any kind, use the following to set the value of the input on an event click(), submit() et al:
on some event; assign or set the value of the input:
$('#inputid').val($('#idB').text());
where:
<input id = "inputid" type = "hidden" />
<div id = "idB">This text will be passed to the input</div>
Using such an approach, make sure the html input does not already specify a value, or a disabled attribute, obviously.
Beware the differences betwen .html() and .text() when dealing with html forms.
add some id for an input
var multi = product(2,3);
document.getElementById('id').value=multi;
<script type="text/javascript">
function product(x,y)
{
return x*y;
}
document.getElementById('myvalue').value = product(x,y);
</script>
<input type="hidden" value="THE OUTPUT OF PRODUCT FUNCTION" id="myvalue">
//prompts for input in javascript
test=prompt("Enter a value?","some string");
//passes javascript to a hidden field.
document.getElementById('myField').value = test;
//prompts for input in javascript
test2=prompt("Enter a value?","some string2");
//passes javascript to a hidden field
document.getElementById('myField').value = test2;
//prints output
document.write("hello, "+test+test2;
now this is confusing but this should work...

Categories

Resources