Saving user input in jQuery? - javascript

$(document).ready(function () {
var userSites = newArray();
var max_fields = 100; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 5; //initial text box count
$(add_button).click(function (e) { //on add input button click
e.preventDefault();
if (x < max_fields) {
x++; //text box increment
$(wrapper).append('<div><input type="text" name ="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) { //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
I have this code, because I want to have a lot of user inputs. However, once the user inputs this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet, is that possible as well?

However, now that the user has input this stuff, how do I save this into an array? Is that possible? I want to save it into an array that I can access from a java applet?
When the form is submitted, the event handler, collectData gathers the text in each <input> and uses the push method to populate an array. This array is then stored in a hidden <input> and that data is then extracted by the form which then posts to the server.
I don't know much about Java applets but I got you this far. I suggest you ask about Java in a new question. Your tags are of a JavaScript/jQuery nature.
My demo actually functions with a test server so once submitted, the server will respond with the data that was posted to it.
This works: http://plnkr.co/edit/seD0L3oI7dTnXQrrFZPl?p=preview
Added Code
form.addEventListener('submit', collectData, false);
function collectData(e) {
var userSites = [];
var cache = document.getElementById('cache');
var z = 0;
while (z < max_fields) {
z++;
var data = inputs[z].val();
userSites.push(data);
}
e.stopPropagation();
cache.value = userSites;
}
});

Create an Array object in your one of you script tags :
<script type="text/javascript" >
var myArr=new Array();
</script>
Now add onchange to your inputs also update myArr :
$(wrapper).append('<div><input type="text" name ="myText'+x.toString()+'" onchange="myArr.push(this.value);document.getElementById('myArrInput').value=JSON.stringify(myArr);" /><a href="#" class="remove_field" onclick="myArr['+x.toString()+'].value=null;document.getElementById('myArrInput').value=JSON.stringify(myArr);" >Remove</a></div>');
Add this hiddenField to your page to send myArr to you applet as JSON string:
<input id="myArrInput" type="hidden" name="myArray" value="" />
In server you have to convert myArray Json string to object.

Related

Read data from Javascript dynamic input in node.js

I need dynamic input fields for my node-js application. I need to populate a input text are for writing their cost names on a form. I found some javascript code on internet. It works perfectly but when i try to read data from body, i only have one value. What could be the reason?
Here is my javascript code;
$(function () {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) {
//on add input button click
e.preventDefault();
if (x < max_fields) {
//max input box allowed
x++; //text box increment
$(wrapper).append(
'<div><input type="text" name="generalCostName[]" class="form-control"/>Remove</div>'
); //add input box
}
});
$(wrapper).on("click", ".remove_field", function (e) {
//user click on remove text
e.preventDefault();
$(this).parent("div").remove();
x--;
});
});
here is the part of my ejs file;
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button><div>
<input type="text" name="generalCostName[]" class="form-control"></div>
</div>
For example, i populate 2 more input fields and their values are "Test1","Test2" and "Test3". When i submit values to the node-js side, on the console( console.log(req.body.generalCostName) ) i only have Test1 value. What could be the reason?
You need to use formData to send your dynamically added element to your backend node.js. We need to use jQuery $.each function to get all the values of the input you will added.
Once we have all the value we can append them to the formData which will send via ajax or axios to the backend.
I have limited the max fields added to 3 so for demo purposes but you can use as many as you like. As soon as you hit submit - the data will be stored in the formData and then you can do POST request to node.js where you can see all this coming.
Demo: (Shows all the inputs added and their value stored in the formData)
$(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) {
//on add input button click
e.preventDefault();
if (x < max_fields) {
//max input box allowed
x++; //text box increment
$(wrapper).append(
'<div><input type="text" name="generalCostName" class="form-control"/>Remove</div>'
); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) {
//user click on remove text
e.preventDefault();
$(this).parent("div").remove();
x--;
});
});
//Send data to node.js
function sendData() {
//initialize formData
var formData = new FormData();
//Get all value of dynamically added elements
$('.form-control').each(function(index, item) {
var val = $(item).val();
//Append Data
formData.append('value[]', val)
});
// Display the key/value pairs for formData
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input type="text" name="generalCostName[]" class="form-control"></div>
</div>
<br>
<button onclick="sendData()">
Submit
</button>

Unique name for Add More input

I am trying to create an add more button which will create a new input field. However, I would like to have an unique name set for it.
I tried to search up for an answer, but this does not answer my question.
So, basically what I tried to make my namefield unique is to use the php method rand(). The concept is that - when the add more button is clicked, it will have a name attached to the number given to me by rand().
However, what happens is that it takes the value generated by rand() and applies it to all the names of all the inputs generated.
This is my code and what I tried:
HTML:
<div class="field_wrapper">
<div>
<input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>
Add More
</div>
</div>
JQUERY / JAVASCRIPT:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 100; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[<?php echo rand(); ?>]" value=""/>Remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
As you can see, the first field generates the number as intended. If you click on the add more, the second field does create an unique number. However, if you click add more once again, the third field copies the same name as the 2nd field.
How do I go about achieving what I want and why is rand() not generating a new code?
Also, does rand() guarantee me that it will be an unique ID or is there a chance for it to repeat the same number?
If it does repeat, then what would be the best approach to take to make it as unique as possible?
If you generate random name with PHP it is done once on the server. Your JS code then copies the same element. What you need is to generate unique names with js.
Avoid random if you can, theoretically, you can hit the same number and run into mysterious bugs.
var generateField = function(name)
{
return '<div><input type="text" name="'+name+'" value=""/>Remove</div>'; //New input field html
}
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++; //Increment field counter
$(wrapper).append(generateField('field_name['+x+']' ) ); //Add field html
}
});
Random does not necessarily mean unique, even if collisions would be extremely rare. This solution simply increments a totalFieldsCreated variable to get the next unique number (up to the maximum value JavaScript can provide.)
The new fields are created dynamically instead of using a fixed string of HTML. (This technique is more flexible.)
$(document).ready(function() {
// Defines global identifiers
let
currentFieldCount = 1,
totalFieldsCreated = 1;
const
maxFieldCount = 100,
addButton = $('.add_button'),
wrapper = $('.field_wrapper');
// Calls `addField` when addButton is clicked
$(addButton).click(addField);
// Executes anonymous function when `Remove` is clicked, which removes
// the parent div, and decrements (and logs) `currentFieldCount`
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
currentFieldCount--;
console.log(`currentFieldCount: ${currentFieldCount}`);
});
// Defines the `addField` function
function addField(){
// Makes sure that `currentFieldCount` and `totalFieldsCreated`
// are not at maximum before proceeding
if(
currentFieldCount < maxFieldCount &&
totalFieldsCreated < Number.MAX_VALUE
){
// Creates an input element, increments `totalFieldsCreated`,
// and uses the incremented value in the input's `name` attribute
const input = document.createElement("input");
input.type = "text";
input.name = "field" + ++totalFieldsCreated;
input.value = "";
// Creates an anchor element with the `remove_button` class
const a = document.createElement("a");
a.href = "javascript:void(0);";
a.classList.add("remove_button");
a.title = "remove";
a.innerHTML = "Remove";
// Adds the new elements to the DOM, and increments `currentFieldCount`
const div = document.createElement("div");
div.appendChild(input);
div.appendChild(a);
$(wrapper).append(div);
currentFieldCount++;
// Logs the new values of both variables
console.log(
`currentFieldCount: ${currentFieldCount},`,
`totalFieldsCreated ${totalFieldsCreated}`
);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" name="field1" value="" />
Add More
</div>
</div>
Try Math.random() in js rather than rand() in php ,Math.floor(Math.random()*90000) + 10000 will generate a five digit random number , Hope this helps
$('.rand').attr('name',"fields["+Math.floor(Math.random()*90000) + 10000+"]")
$('.add_button').click(function(e){
$('.field_wrapper').append('<div><input type="text" name=fields['+Math.floor(Math.random()*90000) + 10000+'] value=""/>Remove</div>')
})
$(document).on('click','.remove_button',function(e){
$(this).parent().remove()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="field_wrapper">
<div>
<input type="text" class="rand" value=""/>
Add More
</div>
</div>

getting the value of a textbox when user enters the name/id of the field

Using jquery to get the value of a textbox.
BUT
i need to enter the id of the textbox, then use that value to get the value of the textbox using jquery.
var tt = $("#fieldname").val()
that works
now how do i enter the fieldname at runtime, and get jquery to execute the val command as if it was hard coded?
There are a few ways that you could do this. One way is to listen to one of the keyboard or change events on the textbox you enter the id into, to help determine when the input has changed. So for example
$("#inputText").on("keyup", function(keyupEvent){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
});
Or another way could be to use a click event with similar kind of logic, so for example
$("#clickMe").on("click", function(){
var textboxId = $("#inputText").val();
var textboxIdValue = $("#" + textboxId).val();
})
An example for the use case of both can be seen here https://fiddle.jshell.net/xpvt214o/114584/
Here is an example for you to get started with:
<body>
<p>Type "one" or "two" below</p>
<input id="search" />
<input id="one" value="This input is #one" />
<input id="two" value="And this is #two" />
<p id="result">No input specified</p>
</body>
And the corresponding jQuery code:
// Cache jQuery elements for performance and readability
var $search = $("#search");
var $result = $("#result");
$search.on("change", function() {
var search_value = $search.val();
if (search_value.length) {
search_value = "#" + search_value.toLowerCase().trim(); // Sanitise user input
if ($(search_value).length) {
$result.text($(search_value).val());
} else {
$result.text("Input not found");
}
} else {
$result.text("No input specified");
}
});
This will show the value of the specified input, if it exists.
You can see it in action here: https://jsfiddle.net/jeevantakhar/xpvt214o/114558/

Get other ID's value in form using .innerHTML

I'm trying to display the value of a text field onclick of the Search button.
On the search button, I'm using
onclick="document.getElementByid('output').innerHTML = this.value"
This gets the value of the Search button, which is just 'Search' and displays it in a 'output' div below.
Is there a way to use this to get the value of a separate text field once it is filled in by the user?
I've tried changing this.value to field1.value where field1 is the id/name of the text field, but this does not work.
Any help?
use
document.getElementByid('output').innerHTML = document.getElementById('field1').value
Try this (example):
var btn = document.getElementById('search');
var input = document.getElementById('field1');
var output = document.getElementById('output');
btn.addEventListener('click', function(e) {
output.innerHTML = input.value;
});

Javascript calculator as users type numbers

I'm a noob at Javascript, but I'm trying to implement something on my website where users can type a quantity, and the subtotal updates dynamically as they type.
For example: if items are 10 dollars each, and a user types 5 in the text field I would like it to show $50 next to the text box. Pretty simple multiplication, but I don't know how to do it with Javascript. I think onKeyPress somehow? Thanks!
Assuming the following HTML:
<input type="text" id="numberField"/>
<span id="result"></span>
JavaScript:
window.onload = function() {
var base = 10;
var numberField = document.getElementById('numberField');
numberField.onkeyup = numberField.onpaste = function() {
if(this.value.length == 0) {
document.getElementById('result').innerHTML = '';
return;
}
var number = parseInt(this.value);
if(isNaN(number)) return;
document.getElementById('result').innerHTML = number * base;
};
numberField.onkeyup(); //could just as easily have been onpaste();
};
Here's a working example.
You should handle 'onkeyup' and 'onpaste' events to ensure you capture changes by keyboard and via clipboard paste events.
<input id='myinput' />
<script>
var myinput = document.getElementById('myinput');
function changeHandler() {
// here, you can access the input value with 'myinput.value' or 'this.value'
}
myinput.onkeyup = myinput.onpaste = changeHandler;
</script>
Similarly, use getElementById and the element's innerHTML attribute to set the contents of an element when you want to show the result.

Categories

Resources