Pass variable value from form javascript - 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();

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('');

How do I store the string value from input field in an empty array?

I'm having trouble storing input values from <input> tag in HTML into array of strings, I can't figure out how am I suppose to do that. I have an idea on how that might look like, however I still can't get it to work.
I believe that I have to use .push() and .join() method and += or + operator, it's just I do not know where to put them.
The first thing I did was searching on Google How to store string value from input in an array of strings? but I only found on how to do it using <form> tag in HTML and I can't do that. I can't use the <form> tag.
Here's the code that I think should look like
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
var inputName = document.getElementById("input");
var cityArray = [""];
// This triggers immediately when the browser loads
window.onload = (
// Pickup the string from input and add it on the previously created array
function submit() {
inputName.value;
for (var i = 0; i < array.length; i++) {
array[i];
}
}
);
I also need a piece of code that will delete the value that was typed in a <input> field right after the Submit button is pressed, so that the user doesn't need to press Backspace in order to type the second input value.
Here is a working code snippet.
When you click the submit button, that will call the submit() function. Since your array is defined to be global, you can access it within the function. You do not need to iterate over the array, and you can simply use the .push() method to easily append a string to your array.
var inputName = document.getElementById("input");
var cityArray = [];
function submit() {
cityArray.push(inputName.value);
console.log(cityArray);
}
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>
Hope this helps!
Yes you need to use .push() method it will add the new entered string to the array, without the need to iterate it:
function submit() {
cityArray.push(inputName.value);
}
And you need to initialize your array as an empty array with [] :
var cityArray = [];
And you don't need to create the submit function in the body.onload event handler because it won't be accessible outside of it and may lead for an error.
Demo:
var inputName = document.getElementById("input");
var cityArray = [];
function submit() {
cityArray.push(inputName.value);
console.log(cityArray);
}
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
Js Code
//declare your array like this
var yourArray = new Array();
//To add items to array:
yourArray.push(yourString);
//To get you can use indexing like(almost any other language)
yourArray[i]
//You can even set as an object array like this:
yourArray.push({
text: 'blablabla'
})
//So, in your case, filling up the array could be something like this:
var inputText = document.getElementById('input').value;
yourArray.push(inputText);
// show it
for (var i = 0; i < yourArray.length; i++) {
alert(yourArray[i]);
}
HTML Script
<body>
<input type="text" id="input" />
<button onclick="submit()">Submit</button>
<div id="placeholder"></div>
</body>

Function to get input and assigns it to variable

I'm trying to make something using javascript/jquery that is similar to java.
The way to get input in java:
String x = JOptionPane.showInputDialog("Enter a value: ");
.showInputDialog shows GUI and submits a value after "Submit" is clicked.
This is what I've tried: https://jsfiddle.net/1t5pxhj5/2/
This behavior is not possible with Javascript.
You should use events and callbacks to retrieve the specified value.
Your Java code:
String x = JOptionPane.showInputDialog("Enter a value :");
Your Javascript code:
function showInput(message, callback) {
// display dialog
// ...
callback($("input").val()); // this should be returned to getInput after Submit is clicked
});
showInput("Enter a value:", function(x) {
// do something now
});
<input type="text" name="txt" id="txt"/>
<input type="button" onclick="gettext('txt');"/>
to retrieve data use code below
function gettext(id) {
var entereddata = document.getElementById(id);
var value = entereddata.value;
}
Hope my code works. Keep coding
Supposing you have
<input type="text" class="my-input">
<button>click me!</button>
you can retrieve input value in jQuery/Javascript with this instruction;
$(".my-input").val();
if you want to bind the data retrieval to the "click me!" button there is the complete code:
$(".click-me").click(function() {
alert($(".my-input").val());
});

Accessing input fields not working

i have 8 text fields and two textareas in my form.i am trying to access all of them and check whether they are empty or not.But somehow the javascript i wrote is not working.here is the code:
javascript:
function textboxes(formobj)
{
var ip = formobj.getElementsByTagName('input');
for(var i=0; i<ip.length; i++)
{
if(ip[i].value == "")
{
alert("empty field");
ip[i].focus();
return false;
}
}
}
The id of the form is 'genform' and this is passed as an arguement to the above javascript code while the button is clikced :
HTML:
<input type="submit" name="submit" value="Generate Questions"
onclick="return textboxes('genform'); return false;" />
This would be a lot easier with jQuery. Thats for another day :)
The onclick event handler passes the text 'genform' to your function. You have to grab the DOM element from this.
var ip = document.getElementById(formobj).getElementsByTagName('input');

How to make simplier the jquery code

Aim is to detect if after page load input values are changed.
Input fields (19 fields) for example
<input type="text" name="date_day1" id="date_day1" value=" >
<input type="text" name="date_month1" id="date_month1" value=" >
<input type="text" name="date_year1" id="date_year1" value=" >
<input type="text" name="amount1" id="amount1" value=" >
Then hidden input field like this
<input type="text" name="is_row_changed1" id="is_row_changed1" value="">
<script>
$("#date_day1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
$("#date_month1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
If in any of input fields (19 fields) value is changed, then I need to reflect it in this hidden input field (I decided to set the hidden input field value to 1).
After that ajax with php where I check if the hidden input field value is 1. If 1, then update mysql. Aim is to reduce usage of server resources.
Question
Javascript code for the hidden input field would be long. May be some way (code) to make is shorter (simplier)?
Add a row_changed class to each input then you can target them all with one call:
$(".row_changed").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
(you can also simplify it even more with QuickSilver's comment.)
You could use JQuery selectors in order to set the same "input changed" callback for all input elements declared in your HTML code:
var anyFieldChanged = false; //Global variable
function changedCallBack()
{
anyFieldChanged = true;
alert('Fields changed');
}
allInputs = $('input');
allInputs.each(function() { this.onchange = yourCallBack(); });
I don't know if it's just in your example code, but you have several elements with the same ID, which is not valid. Each ID should be unique (which is the purpose of any ID). You can either add a class to each input you want to track and select on that like Shawn said or if you want to track every input except the hidden on the page you can use
$("input:[type!=hidden]").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
Use like this.
<script>
$("#date_day1").on("change", function () {
$('#is_row_changed1').val(1);
});
$("#date_month1").on("change", function () {
$('#is_row_changed1').val(1);
});
// etc
</script>

Categories

Resources