This code is functioning correctly. However, I need help getting the "input" tag to display like a combobox. I have tried to styled the inputbox as a combobox without success. I am also looking for a way to make the code work with a combobox by building the options dynamically. Any and all help is appreciated.
$(function () {
var availableTags = new Array(1000000);
var j = 0;
for (var i = 1; i < availableTags.length; i++) {
availableTags[j++] = i.toString();
}
$("#tags").autocomplete({
source: function (req, responseFn) {
var re = req.term;
var matcher = new RegExp("^" + re, "i");
var a = $.grep(availableTags, function (item) {
return matcher.test(item);
});
responseFn(a.slice(0, 5));
},
select: function (event, ui) {
if (ui.item && ui.item.value) {
var titleinput = ui.item.value;
ui.item.value = $.trim(titleinput);
alert(ui.item.value);
}
},
change: function (event, ui) {
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
return false;
}
}
});
});
.custom-combobox {
position: relative;
display: inline-block;
border-style: solid;
border-width: 1px;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
}
/*
.custom-combobox-list-item {
color: blue;
font-weight: bold;
}
.custom-combobox-input , .custom-combobox-list-item.ui-state-focus {
color: black;
font-weight: bold;
font-style: italic;
}
*/
#tags {
width: 40px;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<label for="tags">Tags: </label>
<input id="tags" type="text" class="custom-combobox" value="">
You could use a datalist to transfer the options to the text input which will then turn it into a combobox
I slimmed your code write down to the very basics to make a simple example.
<label for="tags">Tags: </label>
<input id="tags" name="tags" type="text" list="options" class="custom-combobox" value="">
<datalist id="options">
<!-- it puts the options here then the input type text gets them as select options -->
</datalist>
$(function () {
var availableTags = new Array(10);
var j = 0;
for (var i = 1; i < availableTags.length; i++) {
$('#options').append("<option value='" + i + "'>");
}
});
here is a JSFIDDLE showing the basic functionality
After a research I found Combo-Box-jQuery-Plugin written by dellsala.
What is it ?
Turns a <input type="text"> into a combo box.
autocomplete
keyboard controls
most styles can be customized via css
list of values can be changed dynamically
How it looks like ?
Why I suggest that ?
This is not intended for extending <select> elements. Many other jquery "combo box" plugins out there behave more like searchable select elements with disctinct labels and values for each option. This plugin simply allows the user to choose from existing text values or supply their own.
How to use ? http://jsfiddle.net/csdtesting/eh0gse2f/
<div class="inputCombox">
<label for="input1">Field1:</label>
<input id="input1" type="text" value="" />
</div>
<div class="inputCombox">
<label for="input2">Field2:</label>
<input id="input2" type="text" value="" />
</div>
jQuery(function () {
var varValue = 12;
var aval = [
'Yo',
'1',
'Jo',
varValue.toString()];
//#Example 1
jQuery('#input1').combobox(aval);
//#Example 2
jQuery('#input2').combobox([
'Yo',
'1',
'Jo']);
});
Please Check this it might be helpful
http://jqueryui.com/autocomplete/#combobox
http://demos.telerik.com/kendo-ui/combobox/cascadingcombobox
Do you need this? http://jqueryui.com/autocomplete/#combobox
It's pretty simple, just look that is an input, with an anchor at the end.
Just click on "view source" to see how it's implemented.
Good luck!
Try the bootstrap tags
$("#tags").tagsinput("Amsterdam,Washington,Los Angeles");
Bootstrap Tags Input
Try to use select2.
To populate the Select2 with an ajax call, try this:
PHP:
<?php
$result = array();
//Do something with the search string ($searchfor), eg. find the desired results
$result[] = array('id' => '1', 'text' => '101');
$result[] = array('id' => '2', 'text' => '102');
$result[] = array('id' => '3', 'text' => '103');
$result[] = array('id' => '4', 'text' => '104');
$result[] = array('id' => '5', 'text' => '105');
//Send the ajax results formatted as JSON
print(json_encode($result));
?>
HTML:
<input type="hidden" id="tags" value="" style="width: 300px;">
<script>
$('#tags').select2({
minimumInputLength: 2,
ajax: {
url: 'http://yourdomain.com/ajax.php',
dataType: 'json',
type: "GET",
quietMillis: 100,
data: function (term) {
return {
searchfor: term
};
},
results: function (data) {
return {
results: data
};
}
}
});
</script>
Here's a quick workaround to make your inout look like a select. No code changes needed, just some HTML/CSS. I made your input transparent, and layered a select behind it. The functionality is still handled by your input, but now it looks exactly like the select.
Demo - http://jsfiddle.net/sifriday/xy0mxst4/1/
Trick - Do this with the HTML:
<div id="wrapper">
<select id="fake-tags"></select>
<input id="tags" type="text" class="custom-combobox" value="" />
</div>
and add this CSS to make the input appear above the select to handle the functionality:
#tags {
width: 40px;
border: 0;
background: none;
margin-left: -50px;
}
#tags:focus {
outline: 0
}
#fake-tags {
width: 50px;
}
It's a hack, but it's a super-simple one and it sounds like it might be just what you need - you already have working code, you just need it to look a bit different.
This is inspired by the 'good old day's, when people used to layer a nice looking but fake file upload control on top of the nasty default browser one. The default did the real work, and the fake one just provided the nice UI. People don't do this so much now that we have the FileAPI.
I will place the image of a clickable down arrow next to the textbox. I will display 1 to 10 in the list box if the user clicks the image instead of entering data into the text box.
Related
I am trying to copy a string from notepad to HTML form on base of new line but it is not working for me, below is the code snippet for your help. First Line Should Populate in Field 1, 2nd in Field 2 and 3rd in Field 3
$("input[name=query]").on("paste", function() {
var $this = $(this);
setTimeout(function() {
var id = $this.attr("id"), no = parseInt(id.substr(5)),
//groups = $this.val().split(/\s+/);
//groups = $this.val().split('.');
groups = $this.val().split(/[\n\r]/g);
if (groups) {
var i = 0;
while (no <= 3 && i < groups.length) {
$("#input" + no).val(groups[i]);
++no;
++i;
}
}
}, 0);
});
form {
width: 500px;
margin: 50px auto 0;
}
form h2 {
text-align: center;
text-decoration: underline;
}
form table {
width: 100%;
}
form input {
width: 100%;
height: 40px;
border-radius: 5px;
outline: none;
padding: 0 15px;
border: 1px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form name="form1" action="#" method="get" target="">
<h2>Copy/Paste String</h2>
<table cellpadding="0" cellspacing="20">
<tr>
<td width="100px"><h3>Line 1:</h3></td>
<td><input id="input1" name="query" placeholder="Line 1" type="text"></td>
</tr>
<tr>
<td width="100px"><h3>Line 2:</h3></td>
<td><input id="input2" name="query" placeholder="Line 2" type="text" ></td>
</tr>
<tr>
<td width="100px"><h3>Line 3:</h3></td>
<td><input id="input3" name="query" placeholder="Line 3" type="text"></td>
</tr>
</table>
</form>
Below is the 3 lines I am trying to copy from notepad behavior is new line
This is Line 1
This is Line 2
This is Line 3
Kindly have a look into snippet and guide, where I am doing mistake
The problem with that is your line breaks are being lost when you paste into the (single-line) inputs; only textareas will preserve line breaks; normal inputs will collapse multi-line text into a single line.
The solution is to read the pasted input not from the input but via the clipboardData() area of the event - not the contrived jQuery event, but the original (native) event. jQuery exposes this via the originalEvent property.
This also means you can avoid the timeout hack. All in all:
let fields = $('input[name=query]');
$(document).on('paste', 'input[name=query]', evt => {
evt.preventDefault();
let pasted = evt.originalEvent.clipboardData.getData('text/plain');
pasted.split(/\n/).forEach((line, i) => fields[i].value = line);
});
Fiddle
(Further reading: my blog post about hacking incoming clipboard data.)
You can try this :
$("input[name=query]").on("paste", function(e) {
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
pastedData = window.event.clipboardData.getData('Text');
// Do whatever with pasteddata
var $this = $(this);
setTimeout(function() {
var id = $this.attr("id"), no = parseInt(id.substr(5)),groups = pastedData.split("\n");
if (groups) {
var i = 0;
while (no <= 3 && i < groups.length) {
$("#input" + no).val(groups[i]);
++no;
++i;
}
}
}, 0);
});
Good luck!
This question already has answers here:
How to prevent a user from removing the first three characters in a text input?
(6 answers)
Closed 4 years ago.
So I have a text input
<input type="text" value="+98912314789" class="telinfo">
Is there a way to keep 4 letter from the begin ?
I want to keep +9891 read only and the user can delete all part of this textbox except this part.
You can capture the keyup and blur (in case user directly copy paste the value in textbox) event
function handleEv( event )
{
var thisObj = event.currentTarget;
var fixedValue = thisObj.getAttribute( "data-fixedvalue" );
if ( thisObj.value.indexOf( fixedValue ) != 0 )
{
console.log(thisObj.value, fixedValue);
event.preventDefault();
thisObj.value = fixedValue;
}
}
Demo of sample implementation
var el = document.querySelector( ".telinfo" );
el.addEventListener( "keyup", handleEv);
el.addEventListener( "blur", handleEv);
function handleEv( event )
{
var thisObj = event.currentTarget;
var fixedValue = thisObj.getAttribute( "data-fixedvalue" );
if ( thisObj.value.indexOf( fixedValue ) != 0 )
{
console.log(thisObj.value, fixedValue);
event.preventDefault();
thisObj.value = fixedValue;
}
}
<input type="text" value="+98912314789" class="telinfo" data-fixedvalue = "+9891">
try this code may be it will help to resolve your issue
<input type="text" value="+98912314789" class="telinfo" id="telphone" onchange="staticData()" onkeyup="staticData()">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function staticData(){
var data=$("#telphone");
if(data.val().length<5)
{
data.val("+9891");
data.attr("readonly",true);
}
else
{
data.attr("readonly",false);
}
}
</script>
This question solved by #gurvinder372 but you could achieve this easier than it with Regex pattern:
function phoneNumber(selector, num) {
$(selector).on('input', function() {
var reg = /\+/gi;
if (!$(this).val().match(reg)) {
$(this).val($(this).val().replace(/([\d]+)/g, "+" + num + "$1"));
}
});
}
phoneNumber('.telinfo', '9891');
phoneNumber('.mobinfo', '78');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" placeholder="+9891" class="telinfo">
<input type="text" value="" placeholder="+78" class="mobinfo">
Update: Also I converted this to function to usable multiple times.
Try using two inputs one for readonly and second for editing -
<input type="text" value="+9891" readonly>
<input type="text" value="" class="telinfo">
Wrap it in a container to add both inputs on the same line.
The easiest way is separating the read-only text from input text
<input type="text" value="+9891" size="3" disabled>
<input type="text" value="">
make css and html like below change style as per your requirement
<div class="field">
<input type="text" value="" class="telinfo">
</div>
.field{
float: left;
width: 100%;
position: relative;
max-width: 240px;
}
.field:before{
content: "+9891";
position: absolute;
left: 15px;
top: 10px
}
.field input{
background: #fff;
border: 1px solid #ddd;
padding: 10px 15px 10px 58px;
font-size: 14px;
line-height: 18px;
color: #000;
}
Ok, so I have a filterable search form that returns certain images in a grid, which works great, it resets when I delete the text in the search input, but when I click the "Clear" button, which should do the same thing as deleting the text, it doesn't work. Here is the HTML and JQuery used:
<form id="live-search" action="" class="styled" method="post" style="margin: 2em 0;">
<div class="form-group">
<input type="text" class="form-control" id="filter" value="" style="width: 80%; float: left;" placeholder="Type to search"/>
<span id="filter-count"></span>
<input type="button" class="clear-btn" value="Clear" style="background: transparent; border: 2px solid #af2332; color: #af2332; padding: 5px 15px; border-radius: 3px; font-size: 18px; height: 34px;">
</div>
</form>
This is the JQuery for the clearing text:
jQuery(document).ready(function(){
jQuery("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = jQuery(this).val(), count = 0;
// Loop through the comment list
jQuery(".watcheroo").each(function(){
jQuery(this).removeClass('active');
// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
jQuery(this).show();
count++;
}
});
// Update the count
var numberItems = count;
});
//clear button remove text
jQuery(".clear-btn").click( function() {
jQuery("#filter").value = "";
});
});
Any help would greatly be appreciated.
value is a property on a DOMElement, not a jQuery object. Use val('') instead:
jQuery(document).ready(function($) {
$("#filter").keyup(function() {
var filter = $(this).val(),
count = 0;
$(".watcheroo").each(function(){
var $watcheroo = $(this);
$watcheroo.removeClass('active');
if ($watcheroo.text().search(new RegExp(filter, "i")) < 0) {
$watcheroo.fadeOut();
} else {
$watcheroo.show();
count++;
}
});
var numberItems = count;
});
$(".clear-btn").click(function() {
$("#filter").val(''); // <-- note val() here
});
});
Note that I amended your code to alias the instance of jQuery passed in to the document.ready handler. This way you can still use the $ variable safely within the scope of that function.
As the accepted answer doesn't solve the problem.
Try input event instead of keyup
$("#filter").on("input", function() {.....
& then clear the filter input field on which event you want.
$(".clear-btn").on("click", function() {
$("#filter").val("").trigger("input");
});
Add this to your CSS:
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
<form>
<input type="search" name="search" placeholder="Search...">
</form>
I made a way to add and remove fields using the input[type"number"]. I use jquery to do this but the way I did is not perfect. If there's a value in the field, the value will get erase if the number value is change because of using .remove(). Is there a better way to doing this?
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
<script>
$('#num').bind('keyup mouseup', function () {
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
</script>
My Fiddle
Try something like this. Instead of removing all of the inputs every time, this just removes the ones on the end, or adds more to the end.
The main difference between this one and yours is that I added var totNum = 0; to keep track of the current number of input there are. I then used that to determine how many to add/remove.
var totNum = 0;
$(document).on('keyup mouseup', '#num', function(){
var num = $(this).val();
if (num != "")
{
if (totNum == 0)
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
for (var i = num; i < totNum; i++)
{
$('.dynamicInput .row:last-child').remove();
}
for (var i = totNum; i < num; i++)
{
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
totNum = num;
if (totNum == 0)
{
$('.dynamicInput h4').remove();
$('.dynamicInput .row').remove();
}
}
});
input[type="number"] {
width: 200px;
height: 30px;
font-family: Arial, sans-serif;
font-size: 20px;
}
.row {
display: block;
margin-bottom: 15px;
}
body {
width: 100%;
padding: 40px;
}
input[type="text"] {
width: 100%;
}
.col1,
.col2 {
width: 45%;
display: inline-block;
margin-right: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
It's easier and less likely to fail using a data structure as a skeleton upon which you can build the view. Note that this technique requires an extra computation in order to save user inputs, this is the reason why I've added the "change" event.
In the following code snippet, I've made two panels side by side. The left one is a list of inputs, very close to yours, easy to adapt to your needs, while the right one allows to see the evolution of the "data" array according to user actions.
Both panels rely on the "data" array, in other words, as soon as new items are added to or removed from "data", or a single item is updated, both panels are fully rebuilt. Note that the "change" event takes advantage of event delegation in order to deal with newly added inputs.
Finally, the "update" functions update the entire data source or a single item of the data source when the corresponding input changes, while the "render" functions draw on the data source to keep the panels in sync with the data. By the way, the right panel is rendered once at starting.
$(function () {
var data = []; // data source
var $num = $('#num'); // input for number of rows
var $left = $('#left'); // left panel
var $right = $('#right'); // right panel
// render the right panel at starting
renderRightPanel();
// when the number of rows changes:
// - rebuild the left panel entirely
// - keep the data list up to date
// - print the array to the right panel
$num.on('keyup mouseup', function () {
renderLeftPanel($(this).val());
updateList();
renderRightPanel();
});
// when a value changes:
// - keep the data item up to date
// - print the array to the right panel
$left.on('change', 'input', function () {
var i = $left.find('input').index(this);
updateItem(i, $(this).val());
renderRightPanel();
});
// updates the data list
function updateList () {
data = $left.find('input').map(function () {
return $(this).val();
}).get();
}
// updates a single data item
function updateItem (index, value) {
data[index] = value;
}
// refreshes the DOM of the right panel
function renderRightPanel () {
$right.html('<pre>data = ' + (
JSON.stringify(data, 0, 4)
) + '</pre>');
}
// refreshes the DOM of the left panel
function renderLeftPanel (nLines) {
var i;
var html = '';
if (nLines > 0) {
html = '<h4>Heading</h4>';
for (i = 0; i < nLines; i++) {
html += '<div><input value="' + (data[i] || '') + '" /></div>';
}
}
$left.html(html);
}
});
body * {
padding: 0;
margin: 0;
}
h4, input {
margin-bottom: .5em;
}
#panels {
border: 1px solid black;
}
#panels > div {
display: table-cell;
padding: 1em;
}
#right {
border-left: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panels">
<div id="left"></div
><div id="right"></div>
</div>
Disable and hide extra elements instead of removing them. That will prevent them from getting posted, and also retain the previous value of all values that have been entered. See fiddle
One last point, if you don't want to retain values of hidden elements, change .hide() to .hide().val("")
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput">
<h4>Please fill in the name and email of each extra attendees</h4>
</div>
</body>
<style>
.col1, .col2 { display: inline; width: 48%; margin-right: 2%; }
.row { padding: 5px; }
</style>
<script>
for (var i = 0; i < 20; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
$('#num').bind('keyup mouseup', function () {
var num = parseInt($(this).val());
$('.dynamicInput .row')
.slice(num)
.hide()
.attr('disabled','disabled');
if ( num > 0) {
$('.dynamicInput .row')
.slice(0,num).show()
.removeAttr('disabled');
$('.dynamicInput h4').show();
} else {
$('.dynamicInput h4').hide();
}
}).trigger('keyup');
</script>
Off-hand, you could cache the values within javascript to resist losing them between #num changes. e.g.
(function($){
var $num = $('#num'),
$dynamic = $('.dynamicInput');
cache = {};
$dynamic.on('change', 'input', function(e){
cache[$(this).prop('name')] = $(this).val();
});
$num.on('change keyup mouseup', function(e){
$dynamic.empty();
var val = parseInt($(this).val(), 10);
if (!isNaN(val) && val > 0){
$('<h4>')
.text('Please fill in the name and email of each extra attendees')
.appendTo($dynamic);
for (var i = 0; i < val; i++){
var nameName = 'attendeesName' + i,
emailName = 'attendeesEmail' + i;
var $row = $('<div>',{'class':'row'}),
$col1 = $('<div>',{'class':'col1'}).appendTo($row),
$col2 = $('<div>',{'class':'col2'}).appendTo($row);
$('<input>',{
'type': 'text',
'name': nameName,
'placeholder': 'Name',
'required': 'true'
}).val(cache[nameName] || '').appendTo($col1);
$('<input>',{
'type': 'email',
'name': emailName,
'placeholder': 'Email',
'required': 'true'
}).val(cache[emailName] || '').appendTo($col2);
$row.appendTo($dynamic);
}
}
});
})(jQuery);
input[type="number"] {
width:200px;
height:30px;
font-family:Arial, sans-serif;
font-size:20px;
}
.row {
display:block;
margin-bottom:15px;
}
body{
width:100%;
padding:40px;
}
input[type="text"]{
width:100%;
}
.col1, .col2{
width:45%;
display:inline-block;
margin-right:10px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
Here is an attempt to improve the accepted answer:
$(function () {
var $num = $('#num');
var $panel = $('#panel');
var h4 = '<h4>Heading</h4>';
var row = '<div><input /></div>';
$num.on('mouseup keyup', function () {
var n, $inputs;
var value = $(this).val();
if (value <= 0) {
$panel.empty();
}
else {
$inputs = $panel.find('input');
// get the number of inputs already added
n = $inputs.size();
// add your heading if there is no input
if (n === 0) {
$panel.append(h4);
}
// the user wants less inputs
if (value < n) {
$inputs.slice(value).remove();
}
// the user wants more inputs
else if (value > n) {
$panel.append(
// a little trick, see below
new Array(value - n + 1).join(row)
);
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Number of inputs: <input id="num" type="number" value="0" /></div>
<div id="panel"></div>
A word on the "array join trick":
var a = [1, 2, 3, 4];
console.log(a.join('+'));
// prints "1+2+3+4"
var b = new Array(4); // an array of 4 undefined items
console.log(b.join('+'));
// prints "+++"
var c = new Array(3);
console.log('<ul>' + c.join('<li>item</li>') + '</ul>');
// prints "<ul><li>item</li><li>item</li></ul>"
This is what exactly you are looking for,
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#num").keyup(function(){
$('.dynamicInput .row').remove();
$('.dynamicInput h4').remove();
if ($(this).val() > 0) {
$('.dynamicInput').append('<h4>Please fill in the name and email of each extra attendees</h4>');
var num = $(this).val();
for (var i = 0; i < num; i++) {
$('.dynamicInput').append('<div class="row"><div class="col1"><input type="text" name="attendeesName' + i + '" placeholder="Name" required /></div><div class="col2"><input type="text" name="attendeesEmail' + i + '" placeholder="Email" required /></div></div>');
}
}
});
});
</script>
</head>
<body>
<input type="number" id="num" min="0" max="20" required/>
<div class="dynamicInput"></div>
</body>
</html>
I am having trouble trying to convert this into an array. I don't fully understand how to take input from a form and save it in an array.
My project states: Do NOT save the input in a set of variables and then put those in an array.
Use the array as your collection of data saving variables. (That is what a data
structure is for.)
I have looked for the last 2 hours trying to find something to help me. I have to do this project in JavaScript, but keep finding jquery and I'm not quite sure on how to convert it to Javascript
Any suggestions on how I can take the form input and save it in an array?
This is only a little bit of my project. I just took the first function and the HTML that is attached to the function.
Code in the snippet.
function getID() {
var studentID = new Array();
studentID = document.forms["getFormInfo"]["txtStudentID"].value;
var numberOnly = /^[0-9]+$/;
//Checks for a null/blank within Student ID: field.
if (studentID.length == 0) {
document.getElementById('divAllField').style.display = '';
document.forms["getFormInfo"]["txtStudentID"].focus();
return false;
} //End of if statement
else {
if (studentID.length == 8 && studentID.match(numberOnly)) {
//Run the next function
getFirstName();
} //End of else/if statement
else {
//Show Error Message
document.getElementById('divStudentID').style.display = "";
//Focus on input field with the error.
document.forms["getFormInfo"]["txtStudentID"].focus();
} //end of else/if/else statement
} //End of else statement
} //End of function getID()
h1 {
text-align: center;
color: teal;
}
table {
border-spacing: 8px;
border: 2px solid black;
text-align: justify;
}
th {
text-align: center;
padding: 8px;
color: blue;
font-size: 125%;
}
td {
padding: 5px;
}
input,
select {
width: 200px;
border: 1px solid #000;
padding: 0;
margin: 0;
height: 22px;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
input {
text-indent: 2px;
}
label {
float: left;
min-width: 115px;
}
div {
padding: 3px;
color: red;
font-size: 80%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Begining of the header -->
</head>
<!-- End of the header -->
<body>
<!-- Everything in the <body> </body> displays on the webpage -->
<form id="getFormInfo">
<!-- Creates a form with an ID -->
<table id="tableInfo">
<!-- Creates a table within the form -->
<!-- Creates a table header within the form and table -->
<th>User Information</th>
<!-- Error Message for all fields if they are null/blank -->
<tr>
<td><strong><div id="divAllField" style="display: none;">
Please make sure all input boxes are filled out.
</div></strong>
</td>
</tr>
<!-- Student ID Input -->
<tr>
<td><strong><label>Student ID:</label></strong>
<input type="text" name="txtStudentID" maxlength="8" placeholder="8 Digit ID" value="00149371" required>
<!-- Error Message for Student ID -->
<strong><div id="divStudentID" style="display: none;">
Please enter your 8 Digit Student ID. (Whole Numbers Only)</br>
Example: 00123456
</div></strong>
</td>
</tr>
<tfoot>
<td>
<input type="button" onclick="getID();" value="Submit">
</tfoot>
</td>
</table>
<!-- End of tableInfo -->
</form>
<!-- End of getInfo -->
</body>
</html>
Anyone know how I can save the input from the form and save it into an array?
Please help, I've been working on this project for over 10 hours.
Use the push function to add items to the array.
function getID() {
var studentID = [];
var tstStudentIdVal = document.forms["getFormInfo"]["txtStudentID"].value
studentID.push(tstStudentIdVal);
var numberOnly = /^[0-9]+$/;
//Checks for a null/blank within Student ID: field.
if (tstStudentIdVal.length == 0) {
document.getElementById('divAllField').style.display = '';
document.forms["getFormInfo"]["txtStudentID"].focus();
return false;
} //End of if statement
else {
if (tstStudentIdVal.length == 8 && tstStudentIdVal.match(numberOnly)) {
//Run the next function
getFirstName();
} //End of else/if statement
else {
//Show Error Message
document.getElementById('divStudentID').style.display = "";
//Focus on input field with the error.
document.forms["getFormInfo"]["txtStudentID"].focus();
} //end of else/if/else statement
} //End of else statement
} //End of function getID()
If you can't use jQuery, I think the most elegant solution is to use querySelectorAll() to get a nodeList of all your inputs, then use a combination of Function.prototype.call() and Array.prototype.map() to translate the array of inputs into an array of your own design.
In the snippet below, the resulting array has objects each which have a name and value, which come directly from the text inputs in your form (your question isn't quite clear on how the resulting array should look).
function getID() {
var nodes = document.forms["getFormInfo"].querySelectorAll("input[type='text']");
var array = [].map.call(nodes, function(item) {
return {name : item.name, value : item.value};
});
console.log(array);
}
<form id="getFormInfo">
<input type="text" name="txtStudentID"/>
<input type="text" name="firstName"/>
<input type="text" name="lastName"/>
<input type="button" onclick="getID();" value="Submit"/>
</form>