How to save user input into variable in JavaScript? - javascript

Given the following HTML:
<div id= "playerNames" class="playerInfo">
<form name="form1" method="post" action="http://examples.funwebdev.com/process.php" id="newGame">
<p id= "userInput">
<label>Player 1 name: </label></br><input type="text" name="p1" id="nameOne" value="" required></input></br>
<label>Player 2 name: </label></br><input type="text" name="p2" id="nameTwo" required></input> <input id="submit" type="submit" value="New Game"/>
</p>
</form>
</div>
And the following javascript:
$(document).ready(function () {
console.log("jQuery is ready to use...");
$("#newGame").on("submit", newGameListener);
});
function setUpUsers(){
var player_One = document.getElementById("nameOne").value;
var player_Two = document.getElementById("nameTwo").value;
document.getElementById("pTurns").innerHTML = (+nameTwo+ ", its your turn");
document.getElementById("pScores").innerHTML = (+nameOne+ ": 50pts </br>" (+nameTwo+ ": 50pts </br>"
}
function newGameListener(e) {
e.preventDefault();
setUpUsers();
}
I am trying to append these two variables (nameOne, nameTwo) within p elements. However when this code is run I get NaN (Not a Number) Instead of the user input as a string. Not sure how I should go about achieving this!

That's because you are converting a DOM element to a number. The result will be, em.., NaN. What you want is the value of the element. You can get the value by reading the .value property.
document.getElementById("pTurns").innerHTML = (+nameTwo.value + ", its your turn");
However, since you want to concatenate the value with a string there is no need to use + operator.
Also note that should not rely on the global variables (some browsers like Chrome creates global variables that refer to elements that have the corresponding IDs) for accessing the elements, it's fragile and may fail miserably. Yes, it has been standardized by HTML5, but in my opinion it's a bad practice. Use the document.getElementById method for selecting the elements by their id.

As #Vohuman and #guest271314 answered about your problem(NaN) but you have several syntax error in your HTML and javascript, however I fixed that I optimized your javascript.
Jsfiddle
$(document).ready(function() {
console.log("jQuery is ready to use...");
$("#newGame").submit(function(e) {
e.preventDefault();
var player_One = $('#nameOne').val();
var player_Two = $('#nameTwo').val();
$('#pTurns').html(player_One + ", its your turn");
$('#pScores').html(player_One + ": 50pts </br>" + player_Two + ": 50pts </br>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="playerNames" class="playerInfo">
<form name="form1" method="post" id="newGame">
<p id="userInput">
<label>Player 1 name:</label>
<br />
<input type="text" name="p1" id="nameOne" value="" required />
<br />
<label>Player 2 name:</label>
<br />
<input type="text" name="p2" id="nameTwo" required />
<input id="submit" type="submit" value="New Game" />
</p>
</form>
</div>
<p id="pTurns"></p>
<p id="pScores"></p>

Related

Simple form validation help "Cannot read property 'elements' of undefined"

newbie here, im trying to figure out why i get "Cannot read property 'elements' of undefined ".
javascript:
function conf()
{
for (i=0; i<5; i++)
{
box = document.project.elements[i];
if (!box.value)
{
alert('You haven\'t filled in ' + box.name + '!');
return false
}
}
return true;
}
html:
<form id="project" onsubmit="return conf()" action="#">
<fieldset>
<legend>Contact Details</legend>
<label for="txtname">Your Name:</label> <input type="text" class="text" name="txtname" id="1" /><br/>
<label for="txtemail">Email:</label> <input type="text" class="text" name="txtemail" id="2"/><br/>
<label for="txtartist">Artist:</label> <input type="text" class="text" name="txtartist" id="3"/><br/>
<label for="txtalbum">Song / Album:</label> <input type="text" class="text" name="txtalbum" id="4"/><br/>
<label for="txtcomments">Comments:</label> <textarea class="ta" name="txtcomments" id="txtcomments" cols="30" rows="20"></textarea><br/>
<input type="submit" class="buttons" id="btnSubmit" name="btnsubmit" value="Send Enquiry"/>
</fieldset>
</form>
To get at the form elements you need to use the form id,
document.getElementById('project').elements[i];
a better approach would be use the document.querySelectorAll() and get the elements you are interested in, which would be in this case,
document.querySelectorAll('#project input[type="text"], textarea')
which gives you an array of elements that you could loop through and perform the checks.
BTW, you will probably sooner or later start needing individual checks for each of the inputs. One approach to this would be use the new HTML5 input types.
The approach you have tried should work, since forms with an ID are made named properties of the document object. Perhaps you have another element with a name or id of project.
If the form is the only element with a name or ID of project, you write, formally:
document.forms.project.elements...
or shorter:
document.project.elements...
But that issue can be avoided. Since you have a submit listener on the form, you can pass a reference to the form directly by passing this:
<form id="project" onsubmit="return conf(this)" action="#">
And within the function (don't forget to declare variables!!):
function conf(form)
{
var box;
for (var i=0; i<5; i++) {
box = form.elements[i];
if (!box.value) {
alert('You haven\'t filled in ' + box.name + '!');
return false
}
}
return true;
}
Now you can change the form ID to anything (or remove it) and the function still works.
Also, the label element is associated with a form control by ID, not by name so:
<label for="txtalbum">Song / Album:</label> <input ... name="txtalbum" id="4">
should be:
<label for="4">Song / Album:</label> <input ... name="txtalbum" id="4">
Otherwise the label will not be associated with the element (and therefore may as well be a span or similar and not have a for attribute).
Lastly, please don't use XML syntax in an HTML document. In an HTML document, the / in <br /> and <input ... /> is simply ignored.

Show a javascript variable on html textbox

All I have to do is to show a number in a textbox and a button which add 10 every time I press it, here's my code (it doesn't work).
<head>
<script type="text/javascript">
var n=parseInt(ocument.forms["formNum"]["numero"].value);
document.getElementById("numero").value=n;
function sumar() {
n=document.forms["formNum"]["numero"].value+10;
document.forms["formNum"]["numero"].value=n;
}
function inicializar() {
n=document.forms["formNum"]["numero"].value=0;
}
</script>
</head>
<body>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" />
</p>
<p>
<input type="button" name="sumar" value="Sumar" onclick="sumar()" />
<input type="button" name="inicializar" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
<body>
<script type="text/javascript">
function sumar(){
document.getElementById("numero").value = parseInt(document.getElementById("numero").value)+10;
}
function inicializar(){
document.getElementById("numero").value=0;
}
</script>
<form name="formNum">
<p>
<input type="text" size="10" name="numero" id="numero" value="0" />
</p>
<p>
<input type="button" value="Sumar" onclick="sumar()" />
<input type="button" value="Iniciar a 0" onclick="inicializar()" />
</p>
</form>
</body>
Five suggestions.
It is always better to give unique ids to your html elements.
Never name your HTML elements and javascript functions the same.
If you want to access the html element from javascript, if you know the id, use getElementById.
Use Firebug or Developer tools from the browser, to debug.
If you want to access your elements with the hierarchy, use elements in the form like this document.forms["formNum"].elements["numero"].value. Check this example
Demo: http://jsfiddle.net/DPJCR/
This code should work:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
See: Set the value of an input field
Maybe you are getting an exception from the parseInt that prevents the value from changing.
If it is an option to use jQuery, try this:
function sumar(){
$("#numero").attr("value", parseInt($("#numero").attr("value"), 10)+10);
}
Try this this will help you
var count=10;
$('#btnSumar').click(function(){
if($('#numero').val()=='')
{
$('#numero').val(count);
}else
$('#numero').val(eval($('#numero').val())+count);
});
$('#btnInc').click(function(){
$('#numero').val('');});
Fiddle here

How to chang all <input> to its value by clicking a button and change it back later?

The problem: I have a page with many <input> fields (just say all are text fields)
I would like to have a button, when click on it, all input fields will become plaintext only.
e.g. <input type="text" value="123" /> becomes 123
and if I click on another button, the text will change back to
e.g. 123 becomes <input type="text" value="123" />
Is there an automatic way to scan for all the <input>s and change them all at once using javascript and jquery.
Thank you!
Edited
Seems you guys are getting the wrong idea.
Read what I have written again: e.g. <input type="text" value="123" /> becomes 123
I have value="123" already, why would I want to set the value again???
What I want is e.g.
<body><input type="text" value="123" /><input type="text" value="456" /></body> becomes <body>123456</body> and later <body>123456</body> back to <body><input type="text" value="123" /><input type="text" value="456" /></body>
Use this to go one way,
$('input').replaceWith(function(){
return $('<div />').text(this.value).addClass('plain-text');
});​​​
and this to go the other.
$('.plain-text').replaceWith(function(){
return $('<input />').val($(this).text());
});
​
Check this link http://jsfiddle.net/Evmkf/2/
HTML:
<div id='divInput'>
<input type="text" value='123' />
<br/>
<input type="text" value='456' />
<br/>
<input type="text" value='789' />
</div>
<div id='plainText' style='display:none'></div>
<div>
<input type="button" id='btnPlain' value='Make It Plain' />
<input type="button" id='btnInput' value='Make It Text' />
</div>​
Javascript:
$("#btnPlain").bind('click',function(){
$("#plainText").html('');
$("#divInput input[type=text]").each(function(index){
$("#plainText").append('<span>'+$(this).val()+'</span>');
$("#divInput").hide();
$("#plainText").show();
});
});
$("#btnInput").bind('click',function(){
$("#divInput").html('');
$("#plainText span").each(function(index){
$("#divInput").append('<input type="text" value="'+$(this).text()+'"/><br/>');
$("#plainText").hide();
$("#divInput").show();
});
});
​
Try this FIDDLE
$(function() {
var arr = [];
$('#btn').on('click', function() {
var $text = $('#inp input[type="text"]');
if( $text.length > 0){
$text.each(function(i) {
arr[i] = this.value;
});
$('#inp').html(arr.join());
}
else{
if(arr.length <= 0){
}
else{ // Add Inputs here
var html = '';
$.each(arr, function(i){
html += '<input type="text" value="' + arr[i]+ '"/>'
});
$('#inp').html(html);
}
}
});
});
​
You need to create a hidden element for each input, then use jquery to hide the input, show the hidden element and give it the inputs value.
<input type="text" value="123" id="input_1" />
<div id="div_1" style="display:none;"></div>
$("#div_1").html($("input_1").val());
$("#input_1").hide();
$("#div_1").show();

Putting specific element into variable

how can i get a specific element of a text input into a variable via javascript, in other words take the example below
<form id="123">
<input type="text" id="supply_qty" />
<input type="submit" name="submit" id="123" />
</form>
How do i get the element within the text input into a variable when the submit button is clicked, the problem i have is that i have multiple instances of the code above, with lots of text inputs, so i only want to get the element specific to the submit button clicked. Hopefully you will get what i mean. The reason i need this done via JavaScript and not php etc... is that i later want to use ajax with it, but for the moment i just need the variable.
Thanks
The most easiest way is to give and id to the element and user getElementById() method to grab the element on variable. Just like what you are doing right now
Simple Example:
var button = document.getElementyById("123");
button.onclick = function() {
var text = document.getElementById('supply_qty'); //now you got your element in varaiblle
};
Using jQuery make a slight change to your markup. I am just going to add some classes.
<form>
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
then
$(".submit").click(function() {
var txtbox = $(this).parent("form").children(".textbox")[0];
});
Or, it might be better to bind to the submit handler of the form, on that case, give a common class to the form.
<form class="tinyforms">
<input type="text" class="textbox" />
<input type="submit" class="submit" name="submit" />
</form>
Then
$('.tinyforms').submit(function() {
var txtbox = $(this).children(".textbox")[0];
});
If you accept using jQuery you can do this:
DOM
<form class="form" action="false">
<input type="text" value="some input" name="textInput" />
<input type="text" value="some text" name="textInput2" />
<input type="submit" class="sumbit" value="Send" />
<div id="results"></div>
</form>​​​​​​​​​​​​​​​​​​​
And JavaScript
$(".form").submit( function(){
var inputs = $(this).serializeArray();
$.each(inputs , function(i, input){
$("#results").append(input.value + "<br />");
});
return false;
} );​
EDIT: Updated code and Fiddle: http://jsfiddle.net/65Xtp/4/

Jquery get form field value

I am using a jquery template to dynamically generate multiple elements on the same page. Each element looks like this
<div id ="DynamicValueAssignedHere">
<div class="something">Hello world</div>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="FirstName" />
<input type="submit" value="Submit" />
</form>
</div>
</div>
I would like to use Jquery to process the form on submit. I would also like to revert the form values to their previous values if something should go wrong. My question is
How can I get the value of input box using Jquery? For example, I can get the value of the div with class "something" by doing
var something = $(#DynamicValueAssignedHere).children(".something").html();
In a similar fashion, I want to be able to retrieve the value of the textbox. Right now, I tried
var text = $(#DynamicValueAssignedHere).children(".formdiv").findnext('input[name="FirstName"]').val();
but it doesn't seem to be working
You have to use value attribute to get its value
<input type="text" name="FirstName" value="First Name" />
try -
var text = $('#DynamicValueAssignedHere').find('input[name="FirstName"]').val();
It can be much simpler than what you are doing.
HTML:
<input id="myField" type="text" name="email"/>
JavaScript:
// getting the value
var email = $("#myField").val();
// setting the value
$("#myField").val( "new value here" );
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
$("form").submit(function(event) {
var firstfield_value = event.currentTarget[0].value;
var secondfield_value = event.currentTarget[1].value;
alert(firstfield_value);
alert(secondfield_value);
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" >
<input type="text" name="field1" value="value1">
<input type="text" name="field2" value="value2">
</form>
if you know the id of the inputs you only need to use this:
var value = $("#inputID").val();
var textValue = $("input[type=text]").val()
this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form
$('form[name=form1] input[type=text]')
Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
You can get any input field value by
$('input[fieldAttribute=value]').val()
here is an example
displayValue = () => {
// you can get the value by name attribute like this
console.log('value of firstname : ' + $('input[name=firstName]').val());
// if there is the id as lastname
console.log('value of lastname by id : ' + $('#lastName').val());
// get value of carType from placeholder
console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="formdiv">
<form name="inpForm">
<input type="text" name="firstName" placeholder='first name'/>
<input type="text" name="lastName" id='lastName' placeholder='last name'/>
<input type="text" placeholder="carType" />
<input type="button" value="display value" onclick='displayValue()'/>
</form>
</div>

Categories