Dynamically create a matrix of radiobutton from two textbox inputs - javascript

I would like to create a matrix of radio buttons based on two arrays one having label and count for rows and another one having label and count for column.
These arrays are obtained from two textboxes, where users enters texts separated by semicolon:
<input type="text" name="criteria" id="criteria" class="Textbox autobox default" value="row1;row2;row3;row4" autocomplete="off">
<input type="text" name="levels" id="levels" class="Textbox autobox default" value="level1;level2;level3;level4;level5" autocomplete="off">
Then I tried to create radio buttons dynamically for a row using:
var array1 = $('#criteria').val().split(";");
var array2 = $('#levels').val().split(";");
for (j = 0; j < array2.length; j++) {
for (i = 0; i < array1.length; i++) {
var radioBtn = $('<input type="radio" name="rbtnCount" />');
radioBtn.appendTo('#matrix');
}
$('#matrix').append("<br/>");
}
I manage to produce rows of radio buttons but I could not get for each new row as new group and with labels.
I expected a matrix of radio buttons like in the following figure:
Users should be able to select one in each row therefore each row is in different groupings so that selection in one row does not affect other.

Different row wise groupings can be made by setting same name for every radio element in that row. In the following snippet, names of radio buttons are set from the criteria array elements.
The id for every radio button should be unique, hence a combination of row and column iterators can be made to set up their ids (e.g. '00','01','02', etc.).
It is advised not to make too many DOM update calls by using element.append() inside loops. Instead, you can form your entire HTML string and append it at the very end of your script.
$('#criteria').change(function() {
updateMatrix();
});
$('#levels').change(function() {
updateMatrix();
});
updateMatrix();
function updateMatrix() {
var innerHTML = "";
var criterias = $('#criteria').val().split(";");
var levels = $('#levels').val().split(";");
$.each(criterias, function(i) {
if (i === 0) {
innerHTML += "<tr><th></th>";
$.each(levels, function(j) {
innerHTML += `<th> ${levels[j]} </th>`;
});
innerHTML += "</tr>";
}
innerHTML += "<tr>";
$.each(levels, function(j) {
if (j === 0) innerHTML += `<td> ${criterias[i]} </td>`;
innerHTML += `<td><input type="radio" name="${criterias[i]}" id="${i}${j}"></td>`;
});
innerHTML += "</tr>";
});
$('#matrix').html(innerHTML);
}
body {
font-family: Arial, Helvetica, sans-serif;
}
div {
margin-bottom: 10px;
}
.text-label {
display: block;
text-transform: uppercase;
font-size: 12px;
font-weight: bold;
padding: 3px 5px;
}
.textbox {
padding: 10px;
width: 300px;
}
table {
border-collapse: collapse;
text-transform: uppercase;
font-size: 10px;
border: 1px solid #333;
margin-top: 20px;
}
table input {
display: block;
margin: 0 auto;
}
th,
td {
text-align: left;
padding: 10px 20px;
}
th {
background-color: #333;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="text-label">Criteria</span>
<input class="textbox" type="text" name="criteria" id="criteria" value="row1;row2;row3;row4" autocomplete="off">
</div>
<div>
<span class="text-label">Levels</span>
<input class="textbox" type="text" name="levels" id="levels" value="level1;level2;level3;level4;level5" autocomplete="off">
</div>
<table id="matrix">
</table>

Related

JavaScript functions not working together to display image

I am trying to get user input and then print that number of boxes on the screen, I can get the boxes spawning if I do no checks and just set them to spawn whenever I click one, However, once I start adding in checks the boxes just stop spawning.
var count = 1;
function spawnBox() {
var container = document.getElementById("container");
var newBox = document.createElement("div");
newBox.className = "box";
newBox.innerHTML = count;
container.appendChild(newBox);
count++
}
function checkIfCanSpawn() {
while (count < inputNumber) {
spawnBox();
}
}
div.box {
width: 10vw;
height: 8vw;
background: rgb(8, 144, 168);
margin: 1vw;
float: left;
text-align: center;
font-size: 5vw;
padding-top: 1vw;
font-family: sans-serif;
}
<label id="type in a number" name="Input a number"> Type In a number </label>
<input id="inputNum" type="number" name="inputNumber"> </input>
Tweaked a little to make it work.
Added onchange event on input class.
then instead of using the count, i made use of the available while loop and passed the count instead.
then clear the "container" every run.
function spawnBox(count) {
// Get the container
var container = document.getElementById("container");
// Create a new div
var newBox = document.createElement("div");
newBox.className = "box";
newBox.innerHTML = count;
// Append it to the container
container.appendChild(newBox);
// Increment count
count++
}
function checkIfCanSpawn() {
document.getElementById("container").innerHTML = "";
var inputNumber = document.getElementById("inputNum").value;
var x = 1;
while (x <= inputNumber) {
spawnBox(x);
x++;
}
}
div.box {
width: 10vw;
height: 8vw;
background: rgb(8, 144, 168);
margin: 1vw;
float: left;
text-align: center;
font-size: 5vw;
padding-top: 1vw;
font-family: sans-serif;
}
<label id="type in a number" name="Input a number"> Type In a number </label>
<input id="inputNum" type="number" name="inputNumber" onchange="checkIfCanSpawn()" />
<div id="container"></div>
https://jsfiddle.net/Lqj4dktw/
Add a button with a click-eventHandler to call the spawnBox():
$(document).ready(function() {
$("#btn" ).click(function(){
let inputNumber = $("#inputNum").val();
while (count < inputNumber) {
spawnBox();
}
})
})
Her is a working fiddle

Javascript Object Move and Drop

I'm learning how to code javascript, please do not reply that this can be done by using someone else's code that already exists. I am doing this to learn.
I have a situation whereby the below CSS and HTML code:
CSS:
div.miniblock {
font-size: 12px;
background-color: #333333;
text-align: center;
vertical-align: middle;
border: thin dotted #CCCCCC;
color: #FFFFFF;
padding: 2px;
margin: 5px;
cursor: move;
position: relative;
}
div.miniblock_unsaved {
font-size: 12px;
background-color: #55AAAA;
text-align: center;
vertical-align: middle;
border: thin dotted #000;
color: #000;
padding: 2px;
margin: 5px;
cursor: move;
position: relative;
}
div.dropinto {
font-size: 12px;
background-color: #575757;
text-align: center;
vertical-align: middle;
border: thin dotted #AAAAAA;
color: #FFFFFF;
padding: 2px;
margin: 5px;
}
div.dropinto_over {
font-size: 12px;
background-color: #FFFFFF;
text-align: center;
vertical-align: middle;
border: thin dotted #000000;
color: #000000;
padding: 2px;
margin: 5px;
}
div.moving {
font-size: 12px;
background-color: #CCCCCC;
text-align: center;
vertical-align: middle;
border: thin dotted #000000;
color: #000000;
z-index:1;
height: 80px;
width: 80px;
opacity: 0.7;
padding: 5px;
cursor: move;
}
div.OPAQUE {
font-size: 12px;
background-color: #FFF;
text-align: center;
vertical-align: middle;
color: #000000;
opacity: 0.5;
}
HTML:
<INPUT TYPE="HIDDEN" NAME="block_side[3]" VALUE="" ID="block_side0">
<INPUT TYPE="HIDDEN" NAME="block_order[3]" VALUE="" ID="block_order0">
<INPUT TYPE="HIDDEN" NAME="block_side[4]" VALUE="" ID="block_side1">
<INPUT TYPE="HIDDEN" NAME="block_order[4]" VALUE="" ID="block_order1">
<INPUT TYPE="HIDDEN" NAME="block_side[5]" VALUE="" ID="block_side2">
<INPUT TYPE="HIDDEN" NAME="block_order[5]" VALUE="" ID="block_order2">
<INPUT TYPE="HIDDEN" NAME="block_side[6]" VALUE="" ID="block_side3">
<INPUT TYPE="HIDDEN" NAME="block_order[6]" VALUE="" ID="block_order3">
<INPUT TYPE="HIDDEN" NAME="block_side[2]" VALUE="L" ID="block_side=4">
<INPUT TYPE="HIDDEN" NAME="block_order[2]" VALUE="1" ID="block_order4">
<INPUT TYPE="HIDDEN" NAME="block_side[1]" VALUE="L" ID="block_side=5">
<INPUT TYPE="HIDDEN" NAME="block_order[1]" VALUE="2" ID="block_order5">
<DIV CLASS="OPAQUE" ID="instruct"></DIV>Set your preferences for the blocks of information and their display location here.<TABLE height="100%" width="100%"><TR ><TH COLSPAN="2">Assigned Blocks</TH></TR><TR ><TD COLSPAN="2">Here are the blocks that are currently displayed during your experience.</TD></TR><TR ><TD WIDTH="50%" VALIGN="TOP"><DIV CLASS="dropinto" ID="leftblocks" SLOT="L">Left Blocks<div onmousedown="grabobj(4)" onmousemove="dragobj(4)" onmouseup="dropobj(4)" id="4" name="2" class="miniblock">Quick Links [2]</div><div onmousedown="grabobj(5)" onmousemove="dragobj(5)" onmouseup="dropobj(5)" id="5" name="1" class="miniblock">Session Information [1]</div></DIV></TD><TD WIDTH="50%" VALIGN="TOP"><DIV CLASS="dropinto" ID="rightblocks" SLOT="L">Right Blocks</DIV></TD></TR><TR ><TH COLSPAN="2">Unassigned Blocks</TH></TR><TR ><TD COLSPAN="2" ID="unassigned_blocks">Here are the blocks that are not currently displayed during your experience.<div onmousedown="grabobj(0)" onmousemove="dragobj(0)" onmouseup="dropobj(0)" id="0" name="3" class="miniblock">Another Block [3]</div><div onmousedown="grabobj(1)" onmousemove="dragobj(1)" onmouseup="dropobj(1)" id="1" name="4" class="miniblock">And Another [4]</div><div onmousedown="grabobj(2)" onmousemove="dragobj(2)" onmouseup="dropobj(2)" id="2" name="5" class="miniblock">Poll Voting [5]</div><div onmousedown="grabobj(3)" onmousemove="dragobj(3)" onmouseup="dropobj(3)" id="3" name="6" class="miniblock">SysAdmin Block [6]</div></TD></TR></TABLE>
and the below Javascript:
window.instruct = function(id, instr){
var el = document.getElementById(id);
el.innerHTML = instr;
}
window.blockprefs = function(id, thisblock){
// determine which slot thisblock belongs to
s = id.getAttribute('SLOT');
// identify all the child nodes associated to this slot
c = id.childNodes;
for(var i=1;i < c.length; i++) { // I set i = 1 here because I don't care about the parent element at this time.
name = c[i].getAttribute('NAME');
// console.log(c.length,c[i]);
pos = document.getElementById('block_side'+name);
ord = document.getElementById('block_order'+name);
pos.setAttribute('VALUE',s);
ord.setAttribute('VALUE',i);
console.log(name,pos,ord,c[i]);
}
};
window.grabobj = function(id){
// console.log('moving object: '+id);
// console.log(document.getElementById(id));
// console.log(event.clientX+', '+event.clientY);
thisblock = document.getElementById(id);
thisblock.setAttribute('CLASS','moving');
thisblock.setAttribute('STATUS','click');
thisblock.style.position = 'absolute';
thisblock.style.left = event.pageX - 40;
thisblock.style.top = event.pageY - 20;
// id.addEventListener('mousemove',function(){console.log('moving mouse: x('+event.clientX)+') y('+event.clientY+')';},false);
};
window.drop = function(id, hit) {
id.setAttribute('STATUS','drop');
id.setAttribute('CLASS','miniblock_unsaved');
id.setAttribute('STYLE','');
instruct('instruct','You have unsaved changes, be sure to commit your changes below.');
};
window.dropobj = function(id){
thisblock = document.getElementById(id);
if(thisblock.getAttribute('STATUS') == 'drag' || thisblock.getAttribute('STATUS') == 'click'){
// determine if the block was dropped within one of the drop object targets
// if it was not, return it to the original location, otherwise, drop it into the new location
var left = document.getElementById("leftblocks"),
right = document.getElementById('rightblocks'),
leftbounds = left.getBoundingClientRect(),
rightbounds = right.getBoundingClientRect(),
t = window.pageYOffset || document.documentElement.scrollTop,
l = window.pageXOffset || document.documentElement.scrollLeft;
if(event.clientX >= leftbounds.left && event.clientX <= leftbounds.right && event.clientY >= leftbounds.top && event.clientY <= leftbounds.bottom){
// hit on the left blocks bounds, drop it into the left block
left.appendChild(thisblock);
//thisblock.insertBefore(left.firstchild);
drop(thisblock);
// now assign the hidden form element the correct values based on the current config in the left block then
// here is what I think will have to happen:
// identify all child nodes of the parent node
// identify all of the hidden form fields associated to those child nodes
// update all of the hidden form fields associated to those child nodes with
// the correct order and L / R flag.
// not sure how to complete those tasks at this time.
// console.log( document.getElementById('block_order' + thisblock.getAttribute('ID')));
// console.log( left.childElementCount );
blockprefs(left, thisblock);
} else if(event.clientX >= rightbounds.left && event.clientX <= rightbounds.right && event.clientY >= rightbounds.top && event.clientY <= rightbounds.bottom){
// hit on the right blocks bounds, drop it into the right block
right.appendChild(thisblock);
//thisblock.insertBefore(right.firstchild);
drop(thisblock);
// now assign the hidden form element the correct values based on the current config in the left block then
} else {
// user missed dropping into the left or right box, drop it back into unassigned.
var u = document.getElementById("unassigned_blocks");
u.appendChild(thisblock);
drop(thisblock);
}
}
};
window.dragobj = function(id){
thisblock = document.getElementById(id);
if(thisblock.getAttribute('STATUS') == 'click' || thisblock.getAttribute('STATUS') == 'drag'){
thisblock.style.left = event.pageX - 40;
thisblock.style.top = event.pageY - 20;
thisblock.setAttribute('STATUS','drag');
}
};
window.onload = function() {
// on mouseover change color of leftdiv or right div
var left = document.getElementById("leftblocks");
var right = document.getElementById('rightblocks');
console.log(left.nodeValue);
function block_over(block){ // set the attribute of the block on mouse over
// console.log('setting property of block: '+block);
block.setAttribute('CLASS','dropinto_over');
}
function block_out(block){ // set the attribute of the block on mouse out
block.setAttribute('CLASS','dropinto');
}
left.addEventListener('mouseover',function(){block_over(left); },true); // listener to set the left block's attributes
left.addEventListener('mouseout',function(){block_out(left); },true);
right.addEventListener('mouseover',function(){block_over(right); },true); // listener to set the right block's attributes
right.addEventListener('mouseout',function(){block_out(right); },true);
};
I attempted to put this into a JSFIDDLE https://jsfiddle.net/vt1hcLL6/ but the frames were throwing it off so it might have to just go into a flat html file sorry.
As a user, the intent of this code is to be able to pick up the blocks and move them into the slots (either the left or the right side) blocks, or remove them from those blocks.
After doing so, javascript will set some values in the hidden form fields so that upon saving the page php will grab those values.
Currently it's only setup to do so if you move a block into the left side and yes once I get this all nailed from a hardcoded perspective I will abstract it further, for now some of this is hard coded.
My problem is that upon the first instance of dropping a block into the Left Side Block, everything works fine all the HIDDEN form fields update correctly with the SLOT="L" Attribute and the ORDER="i" attribute (i being the number corresponding to the child iteration.
Great! It works! Now... once a second block is added to that set from down below, the code breaks and I can't figure out why.
The code that is performing this functionality is in the blockprefs( ) function where I iterate through all the child nodes of the Left block and attempt to bring in the hidden form elements belonging to each child. I get a:
divblock.js:33 Uncaught TypeError: Cannot read property 'setAttribute' of null

My css rules apply to all input elements except for one I made during the script

For some reason, the input I created with the table is NOT AS LONG. I used normalize.css too, and all that did is made it slightly longer. I need it to fill the page and I have no idea where to even begin wording my google searches for such an issue.
Also, all of the css rules DO apply except for width (i think). My dynamically created input is just not as long as the others. Blows my mind.
function makeInput() {
var myInput = document.createElement("input");
myInput.type = "text";
myInput.value = "Here is where the quetsion goes";
return myInput;
}
function makeTable() { // make table with one row and one td
var myTable = document.createElement('table'); // Create table called myTable
var myRow = document.createElement('tr'); // create row called myTr
myTable.id = "myTalbe"
myTable.border = "0"
myTable.cellspacing = "2"
myTable.cellpadding = "0"
myTable.width = "100%"
myTable.type = "text"
var td1 = document.createElement('td'); // td1 for input
var td2 = document.createElement('td'); // td2 for button
var text1 = document.createTextNode('Here is my text');
td1.appendChild(makeInput()); // append makeInput();
td2.appendChild(makeButton()); // append my input form to td1
myRow.appendChild(td1);
myRow.appendChild(td2); // append td1 element to my table
myTable.appendChild(myRow); //
document.body.appendChild(myTable);
}
Game plan: makeInput() returns an input element. makeTable() puts it inside a <td>. makeTable() runs under $(document).ready (jQuery).
I have 5 other inputs on the page. All of which are managed by this:
input[type="text"] {
height: 30px;
display: block;
margin: 0;
width: 98%;
font-family: sans-serif;
font-size: 18px;
appearance: none;
box-shadow: none;
border-radius: none;
}
table tr td input[type="text"] {
height: 30px;
display: block;
margin: 0;
width: 98% !important;
font-family: sans-serif;
font-size: 18px;
appearance: none;
box-shadow: none;
border-radius: none;
}
You try this css....
Tables come with spacing between cells, borders, and padding on cells. Reset those to 0 and it should fill the available space, matching the other inputs. Since there is a cell next to the inputs they will not be the exact same width, since the other cell pushes it to be narrower, but they will line up at least.
function makeInput() {
var myInput = document.createElement("input");
myInput.type = "text";
myInput.value = "Here is where the quetsion goes";
return myInput;
}
function makeTable() { // make table with one row and one td
console.log("Make a table");
var myTable = document.createElement('table'); // Create table called myTable
var myRow = document.createElement('tr'); // create row called myTr
myTable.id = "myTalbe"
myTable.border = "0"
myTable.cellspacing = "2"
myTable.cellpadding = "0"
myTable.width = "100%"
myTable.type = "text"
var td1 = document.createElement('td'); // td1 for input
var td2 = document.createElement('td'); // td2 for button
var text1 = document.createTextNode('Here is my text');
td1.appendChild(makeInput()); // append makeInput() to td1
td2.appendChild(makeButton()); // append makeButton() to td2
myRow.appendChild(td1); // append td1 to the row
myRow.appendChild(td2); // append td2 to the row
myTable.appendChild(myRow); // append the row to the table
document.body.appendChild(myTable); // append the table to the body
}
function makeButton() {
var myButton = document.createElement('button');
var txt = document.createTextNode('Test');
myButton.appendChild(txt);
return myButton;
}
$(document).ready(makeTable);
button, input[type="text"] {
width: 100%;
box-sizing: border-box;
height: 30px;
line-height: 30px;
font-family: sans-serif;
font-size: 18px;
}
input[type="text"] {
display: block;
margin: 0;
appearance: none;
box-shadow: none;
border-radius: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td {
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="Made on load" />
<input type="text" value="This one was made on load too" />

Set value to currency in <input type="number" />

I am trying to format a number input by the user into currency using javascript. This works fine on <input type="text" />. However, on <input type="number" /> I cannot seem to be able to set the value to anything that contains non-numeric values. The following fiddle shows my problem
http://jsfiddle.net/2wEe6/72/
Is there anyway for me to set the value to something like $125.00?
I want to use <input type="number" /> so mobile devices know to bring up a keyboard for number input.
Add step="0.01" to the <input type="number" /> parameters:
<input type="number" min="0.01" step="0.01" max="2500" value="25.67" />
Demo: http://jsfiddle.net/uzbjve2u/
But the Dollar sign must stay outside the textbox... every non-numeric or separator charachter will be cropped automatically.
Otherwise you could use a classic textbox, like described here.
In the end I made a jQuery plugin that will format the <input type="number" /> appropriately for me. I also noticed on some mobile devices the min and max attributes don't actually prevent you from entering lower or higher numbers than specified, so the plugin will account for that too. Below is the code and an example:
(function($) {
$.fn.currencyInput = function() {
this.each(function() {
var wrapper = $("<div class='currency-input' />");
$(this).wrap(wrapper);
$(this).before("<span class='currency-symbol'>$</span>");
$(this).change(function() {
var min = parseFloat($(this).attr("min"));
var max = parseFloat($(this).attr("max"));
var value = this.valueAsNumber;
if(value < min)
value = min;
else if(value > max)
value = max;
$(this).val(value.toFixed(2));
});
});
};
})(jQuery);
$(document).ready(function() {
$('input.currency').currencyInput();
});
.currency {
padding-left:12px;
}
.currency-symbol {
position:absolute;
padding: 2px 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" class="currency" min="0.01" max="2500.00" value="25.00" />
You guys are completely right numbers can only go in the numeric field. I use the exact same thing as already listed with a bit of css styling on a span tag:
<span>$</span><input type="number" min="0.01" step="0.01" max="2500" value="25.67">
Then add a bit of styling magic:
span{
position:relative;
margin-right:-20px
}
input[type='number']{
padding-left:20px;
text-align:left;
}
It seems that you'll need two fields, a choice list for the currency and a number field for the value.
A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.
I did using this . This code snippet automatically format numbers into currency and prefix a dollar sign.
<div class="main">
<h1>Auto Formatting Currency</h1>
<form method="post" action="#">
<label for="currency-field">Enter Amount</label>
<input type="text" name="currency-field" id="currency-field" pattern="^\$\d{1,3}(,\d{3})*(\.\d+)?$" value="" data-type="currency" placeholder="$1,000,000.00">
<button type="submit">Submit</button>
</form>
<p>Auto format currency input field with commas and decimals if needed. Text is automatically formated with commas and cursor is placed back where user left off after formatting vs cursor moving to the end of the input. Validation is on KeyUp and a final validation is done on blur.</p>
<p>To use just add the following to an input field:</p>
<pre>data-type="currency"</pre>
</div><!-- /main -->
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
background: #f5f5f5;
color: #333;
font-family: arial, helvetica, sans-serif;
font-size: 32px;
}
h1 {
font-size: 32px;
text-align: center;
}
p {
font-size: 20px;
line-height: 1.5;
margin: 40px auto 0;
max-width: 640px;
}
pre {
background: #eee;
border: 1px solid #ccc;
font-size: 16px;
padding: 20px;
}
form {
margin: 40px auto 0;
}
label {
display: block;
font-size: 24px;
font-weight: bold;
margin-bottom: 10px;
}
input {
border: 2px solid #333;
border-radius: 5px;
color: #333;
font-size: 32px;
margin: 0 0 20px;
padding: .5rem 1rem;
width: 100%;
}
button {
background: #fff;
border: 2px solid #333;
border-radius: 5px;
color: #333;
font-size: 16px;
font-weight: bold;
padding: 1rem;
}
button:hover {
background: #333;
border: 2px solid #333;
color: #fff;
}
.main {
background: #fff;
border: 5px solid #ccc;
border-radius: 10px;
margin: 40px auto;
padding: 40px;
width: 80%;
max-width: 700px;
}
// Jquery Dependency
$("input[data-type='currency']").on({
keyup: function() {
formatCurrency($(this));
},
blur: function() {
formatCurrency($(this), "blur");
}
});
function formatNumber(n) {
// format number 1000000 to 1,234,567
return n.replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
function formatCurrency(input, blur) {
// appends $ to value, validates decimal side
// and puts cursor back in right position.
// get input value
var input_val = input.val();
// don't validate empty input
if (input_val === "") { return; }
// original length
var original_len = input_val.length;
// initial caret position
var caret_pos = input.prop("selectionStart");
// check for decimal
if (input_val.indexOf(".") >= 0) {
// get position of first decimal
// this prevents multiple decimals from
// being entered
var decimal_pos = input_val.indexOf(".");
// split number by decimal point
var left_side = input_val.substring(0, decimal_pos);
var right_side = input_val.substring(decimal_pos);
// add commas to left side of number
left_side = formatNumber(left_side);
// validate right side
right_side = formatNumber(right_side);
// On blur make sure 2 numbers after decimal
if (blur === "blur") {
right_side += "00";
}
// Limit decimal to only 2 digits
right_side = right_side.substring(0, 2);
// join number by .
input_val = "$" + left_side + "." + right_side;
} else {
// no decimal entered
// add commas to number
// remove all non-digits
input_val = formatNumber(input_val);
input_val = "$" + input_val;
// final formatting
if (blur === "blur") {
input_val += ".00";
}
}
// send updated string to input
input.val(input_val);
// put caret back in the right position
var updated_len = input_val.length;
caret_pos = updated_len - original_len + caret_pos;
input[0].setSelectionRange(caret_pos, caret_pos);
}
https://codepen.io/akalkhair/pen/dyPaozZ
The browser only allows numerical inputs when the type is set to "number". Details here.
You can use the type="text" and filter out any other than numerical input using JavaScript like descripted here

What are the CSS secrets to a flexible/fluid HTML form?

The below HTML/CSS/Javascript (jQuery) code displays the #makes select box. Selecting an option displays the #models select box with relevant options. The #makes select box sits off-center and the #models select box fills the empty space when it is displayed.
How do you style the form so that the #makes select box is centered when it is the only form element displayed, but when both select boxes are displayed, they are both centered within the container?
var cars = [
{
"makes" : "Honda",
"models" : ['Accord','CRV','Pilot']
},
{
"makes" :"Toyota",
"models" : ['Prius','Camry','Corolla']
}
];
$(function() {
vehicles = [] ;
for(var i = 0; i < cars.length; i++) {
vehicles[cars[i].makes] = cars[i].models ;
}
var options = '';
for (var i = 0; i < cars.length; i++) {
options += '<option value="' + cars[i].makes + '">' + cars[i].makes + '</option>';
}
$("#make").html(options); // populate select box with array
$("#make").bind("click", function() {
$("#model").children().remove() ; // clear select box
var options = '';
for (var i = 0; i < vehicles[this.value].length; i++) {
options += '<option value="' + vehicles[this.value][i] + '">' +
vehicles[this.value][i] +
'</option>';
}
$("#model").html(options); // populate select box with array
$("#models").addClass("show");
}); // bind end
});
.hide {
display: none;
}
.show {
display: inline;
}
fieldset {
border: #206ba4 1px solid;
}
fieldset legend {
margin-top: -.4em;
font-size: 20px;
font-weight: bold;
color: #206ba4;
}
fieldset fieldset {
position: relative;
margin-top: 25px;
padding-top: .75em;
background-color: #ebf4fa;
}
body {
margin: 0;
padding: 0;
font-family: Verdana;
font-size: 12px;
text-align: center;
}
#wrapper {
margin: 40px auto 0;
}
#myFieldset {
width: 213px;
}
#area {
margin: 20px;
}
#area select {
width: 75px;
float: left;
}
#area label {
display: block;
font-size: 1.1em;
font-weight: bold;
color: #000;
}
#area #selection {
display: block;
}
#makes {
margin: 5px;
}
#models {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="wrapper">
<fieldset id="myFieldset">
<legend>Cars</legend>
<fieldset id="area">
<label>Select Make:</label>
<div id="selection">
<div id="makes">
<select id="make"size="2"></select>
</div>
<div class="hide" id="models">
<select id="model" size="3"></select>
</div>
</div>
</fieldset>
</fieldset>
</div>
It's not entirely clear from your question what layout you're trying to achieve, but judging by that fact that you have applied "float:left" to the select elements, it looks like you want the select elements to appear side by side. If this is the case, you can achieve this by doing the following:
To centrally align elements you need to add "text-align:center" to the containing block level element, in this case #selection.
The position of elements that are floating is not affected by "text-align" declarations, so remove the "float:left" declaration from the select elements.
In order for the #make and #model divs to sit side by side with out the use of floats they must be displayed as inline elements, so add "display:inline" to both #make and #model (note that this will lose the vertical margin on those elements, so you might need to make some other changes to get the exact layout you want).
As select elements are displayed inline by default, an alternative to the last step is to remove the #make and #model divs and and apply the "show" and "hide" classes to the model select element directly.
Floating the select boxes changes their display properties to "block". If you have no reason to float them, simply remove the "float: left" declaration, and add "text-align: center" to #makes and #models.

Categories