html text field to have pre appended text which is not modifiable - javascript

I would like to have a text field which has pre appended text which is not modifiable.
So when user tries to add text it starts after the pre text.
Also when the form is submitted it should not pass the pre appended text. Its mainly for display purpose but within the text field. I have attached the image which will clarify my question further. For example I would like to add "$" as pre text in the image below. Any help is greatly appreciated.
Note: the $ is dynamic text and so could not be image.

I've made a fiddle with two solutions, both using CSS.
The first uses a data URI of a PNG that contains a dollar sign for the background image of the text input. The second uses a label containing a dollar sign and shifts it over to be on top of the input (you probably should use a span instead of a label, for accessibility's sake).
HTML:
<input type="text" id="bob" />
<br/>
<label for="fred">$</label><input type="text" id="fred" />
CSS:
#bob {
background: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAG1BMVEX///8AAAC/v7/f398/Pz8fHx9/f3+fn59fX19QuZN1AAAAbElEQVQokWNgGFyASRiN7ygYhiKgGCYW6IAs4KgsYCqELCDKLMCehCwQyCyAamhjM5qAiaC4AqpIiaAoqgizuKMQqoAAuwgytxxoiyiSABvQHcwoKgSVBVjEkI1IlEDzCzu6bxnQnY4pQFsAAC/cCbAPkBI2AAAAAElFTkSuQmCC') no-repeat;
background-size: contain;
padding-left: 1.1em;
}
label[for="fred"] {
position: relative;
left: 15px;
z-index: 1000;
font-size: smaller;
}
#fred {
padding-left: 1.2em;
}
Both of these methods are hacky. A JS solution would be more involved, but handle much more nicely (I just don't have time to implement one).

Here's a neat way using background-image
http://jsfiddle.net/dxu2s/1/
HTML:
<label for="RefundAmount">Enter a refund amount: </label>
<input type="text" name="RefundAmount" id="RefundAmount">
CSS:
#RefundAmount {
margin: 0;
padding: 0 0 0 25px;
width: 100px;
height: 25px;
background: #FFF url(http://oi57.tinypic.com/nmncz5.jpg) no-repeat left center;
}
I've also tried using the css psuedo-element :before but it didn't work as input tags doesn't have content in em'.

This is a class i wrote you can use it for free, i didnt test it a lot. if you find a bug let me know
HTML: <input type="text" id="inputA" value="$" />
in script add this Class constructor
//***************************************************************
//-------------------------------------- Class halfEditable_INPUT
//***************************************************************
//-- divides an Input into an non editable area from 0 to index, but not including the index, the rest is editable
//-----------------------------------------------------
//-------- constructor
//-----------------------------------------------------
function halfEditable_INPUT (inputField,index)
{
if (typeof index=="undefined") index=inputField.value.length;
//------------------------------------ PUBLIC Objects, Properties
this.element=inputField;
this.index=index;
//-- a reference to the instance of the halfEditable_INPUT class saved in the html element, to get instance values in DOM events
Object.defineProperty (inputField,"halfEditable_instance",{value:this,writable: false, enumerable:true, configurable:true});
//-- get the value of the input directly
Object.defineProperty (this,"value", {get:this.PRIVATE_getValue,set:this.PRIVATE_setValue});
inputField.addEventListener ("keydown",this.PRIVATE_checkStatus_ONKEYDOWN);
}
//-----------------------------------------------------
//-------- prototype
//-----------------------------------------------------
//------------------------------------ PRIVATE Methods
/* this --- points to the input field
checks if the cursorPosition is in the non Editable area or is at the limit Point
if it is at the limitPoint - dont allow backspace or cursor left
if it is inside allow nothing and move cursorPosition to the limit
reset the Position1 key to index */
halfEditable_INPUT.prototype.PRIVATE_checkStatus_ONKEYDOWN=function (event)
{
var keyCode=event.keyCode;
var index=this.halfEditable_instance.index;
var selectionStart=this.selectionStart, selectionEnd=this.selectionEnd;
if (keyCode==36) //-- position1 key
{
event.preventDefault();
this.setSelectionRange (index,index);
return;
}
if (selectionStart<index)
{
if (selectionEnd>index) this.setSelectionRange (index,selectionEnd);
else this.setSelectionRange (index,index);
}
else if (selectionStart==index) {if (keyCode==8 || keyCode==37) event.preventDefault();} //-- backspace, left cursor
}
halfEditable_INPUT.prototype.PRIVATE_setValue=function (value) {this.element.value=value;}
halfEditable_INPUT.prototype.PRIVATE_getValue=function () {return this.element.value;}
//-----------------------------------------------------
//-------- prototype -- END
//-----------------------------------------------------
//***************************************************************
//-------------------------------------- Class halfEditable_INPUT -- END
//***************************************************************
var inputA=new halfEditable_INPUT(document.getElementById ("inputA"));
if you have further questions let me know.

Related

I want to have a check box highlight when a user selects it

I have build a template in HTML, using CSS and part of java. I have added check boxes example quesiton1, do you have trouble lifting above your arm> Yes or no with 2 check boxes and or radio buttons. I want to be able to highlight the box the user selects I've been working on this trying to use this script but its not working.
function checkYellow() {
var ins = document.getElementsByTagName('input');
for (var i=0; i<ins.length; i++) {
if (ins[i].getAttribute('type') == 'checkbox') {
if ( ins[i].checked == true)
ins[i].style.backgroundColor="yellow";
else
ins[i].style.backgroundColor="white";
}
}
}
I'm still learning HTML, CSS, and javascript. Thanks for any help. I copied this from a previous form, and inserted it into mine but Its not working.
You can do this with CSS alone - no scripting required!
Given something like this:
<div class="checkbox-holder">
<input type="checkbox" id="the-box"/></input>
<label class="checkbox-label" for="the-box">A checkbox!</label>
</div>
You can use CSS like this to highlight the label:
.checkbox-label {
border: 10px;
background: gray;
}
input[type=checkbox]:checked + .checkbox-label {
background: yellow;
}
The key part here is how we select the labels to turn yellow:
input[type=checkbox]:checked + .checkbox-label
This selects anything with the class checkbox-label that comes immediately after an input tag, whose type is checkbox, and which is also marked as checked.
CSS selectors are very useful. You can read more about them here - the Mozilla docs go into detail about all the options you have.

Getting User input with javascript while using three.js?

I am working off of this three.js example (http://threejs.org/examples/#webgl_interactive_cubes) and am trying to find a way for the user to add boxes with specified X, Y, & Z positions.
I could do this with a javascript prompt
var boxes = prompt("X Position", 500); // 500 = Default position
However, I want to make it possible for the user to enter multiple fields (E.g. x, y, z positions; size of box, etc.), so I want to add input boxes. The only way I know how to do this is to use html/css/javascript with something like this -
<!-- CSS formating of Input Boxes -->
<style type = "text/css">
#x_pos {
position: absolute;
bottom: 120px;
left: 10px;
width: 130px;
background-color: #3c4543;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
border: 2px solid #000000;
font-family: Futura;
}
... Repeat for #y_pos & #z_pos
</style>
<!-- Adding a div for each Input Box -->
<div id="x_pos">
<input type="text" id="xpos">
</div>
... Repeat for #y_pos & #z_pos
<h1>Add Node here...</h1>
<!--Allowing user to add input to the Input Box and saving that value as the x, y, & z positions -->
<script text="text/javascript">
var xPosition;
$(document).ready(function(){
$('#xpos').val('Longitude');
$("#xpos").change(function(){
xPosition = $('#xpos').val();
})
... Repeat for #ypos & #zpos
});
However, while I can get the Header and input box to appear, they have absolutely no functionality. I can't type anything in the text boxes and I can't add .click(function () ...) functionality to the h1 text. It's almost like all html and javascript functionality I am used to has been disabled by the rest of the three.js code. My final goal will be to have .click call a function that I can have the divs I defined above appear underneath the h1 "Add Node here..." like this (http://jsfiddle.net/zsfE3/9/).
Can anyone explain to me what is going on here and how I might be able to fix it? Or does anyone have a better way to do this? Thanks guys for any help!
Consinder using the datGUI lib for your project. I had great success with it together with Three.Js. Also there are a number of examples also using it. See this blog post for a tutorial.
Try Something Like This:
html:
<input type = "text" id = "input1">
<button>ADD BOX</button>
</input>
css:
canvas{z-index:-1;}
#input1{
position:fixed;
right:40px;
top:40px;
z-index:1;
width:5%;
height:60px;
}
Good Luck!

CSS Browser's text selection highlight color

Is it possible to get the browser's default (or themed, assuming there are browser themes? I've never looked) text selection color?
Background
I'm trying to make an <input type="date" /> act like it has a placeholder attribute, like the HTML5 <input type="text" /> does. In case it matters, I'm using Bootstrap.
So far, I've got
CSS
/* allow date inputs to have placeholders */
/* display placeholder text */
input[type="date"].emptyDate:before {
content: attr(placeholder);
color: #999;
}
/* hide default mm/dd/yyyy text when empty value and not in focus */
input[type=date].emptyDate:not(:focus) {
color: transparent;
}
/* hide default mm/dd/yyyy text when empty value, not in focus, and
selected (ctrl + a) */
input[type="date"].emptyDate::selection:not(:focus) {
color: transparent;
background-color: lightblue;
}
/* hide placeholder text when empty value, but in focus */
input[type="date"].emptyDate:focus:before {
content: "";
}
Javascript
function setEmptyDateInputClass(input) {
if ($(input).val()) {
$(input).removeClass("emptyDate");
} else {
$(input).addClass("emptyDate");
}
}
$(document).ready(function () {
$.each($("input[type=date]"), function (i, input) {
// set initial class
setEmptyDateInputClass(input);
// set class on value change
$(input).change(function () { setEmptyDateInputClass(this);});
});
});
Issues
I'm having two issues. The first, and the one I'm asking in this question (I'll post another question if everyone obeys the rules and no one posts answers to multiple questions) is, is there a way to get the browser's default (or themed) selection background color so that, either with CSS or manually with Javascript, the lightblue isn't static? (Also, light blue isn't the right color, but that's just a matter of a screenshot and mspaint.)
input[type="date"].emptyDate::selection:not(:focus) {
background-color: lightblue;
}
My second, bonus issue is, I'm having issues selecting :before::selection in order to set the background color of selected ::before content.
/* always active when .emptyDate */
input[type="date"].emptyDate::selection:before {
background-color: lightblue;
}
/* never active */
input[type="date"].emptyDate:before::selection {
background-color: lightblue;
}
You can use specificity on ::selection like so:
CSS
.red::selection {
background-color: red;
color: #fff;
}
.green::selection{
background-color:green;
color:#fff;
}
HTML
<span class="red">I am highlighted in red, </span>
<span class="green">and I am highlighted in green,</span>
<span class="">and I am highlighted as per browser default.</span>
Example: http://www.bootply.com/KEEvWSlP0F

How to get Formee legend border to grow with DOM elements added programmatically

So I have an application where a user should be able to add an indeterminate number of paired text boxes representing the name and phone number of a person to be submitted to a database. The relevant markup is below...
<div id="divAddVoters">
<form class="formee" action="">
<fieldset id="appendVoters">
<legend>Enter Voter Name and Phone Number:</legend>
<!--<div id="appendVoters">-->
<div class="grid-4-12" id="appendVoterName">
<label>Name:</label>
<input type="text" class="txtAddVoter" value="" />
</div>
<div class="grid-4-12" id="appendVoterNumber">
<label>Phone Number</label>
<input type="text" class="txtAddNumber" value="" />
</div>
<div class="grid-4-12"></div>
<!--</div>-->
<div class="grid-12-12">
<button id="btnAddVoter" class="formee-button"
onclick="addVoter(); return false;">ADD VOTER</button>
<button id="btnSubmitVoters" class="formee-button"
onclick="submitVoters(); return false;">SUBMIT VOTER(S)</button>
<p id="pError"></p>
</div>
</fieldset>
</form>
</div>
...so if the user selects the btnAddVoter button any number of times, any number of txtAddVoter text boxes should be added to div appendVoterName and txtAddNumber text boxes should be added to div appendVoterNumber. The javascript function to do this is below...
function addVoter()
{
$('fieldset#appendVoters div#appendVoterName').append("<label>Name</label><input type='text'" +
"class='txtAddVoter' value='' />");
$('fieldset#appendVoters div#appendVoterNumber').append("<label>Phone Number</label>" +
"<input type='text' class='txtAddNumber' value='' />");
}
I'm using Formee to make everything look nice, which explains the fieldset, legend and form class="formee" (my application is actually entirely javascript driven, so I don't need a form at all except that formee styles demand it). The problem is that the border drawn by the legend tag does not grow with the elements added inside of it, so as a user adds textboxes the eventually they overrun the bounds of the legend, over the buttons, and the whole thing looks completely ridiculous.
I'm wondering what the best way to make the legend border grow with the number of contained textbox elements would be. I was thinking about maintaining a count of textboxes, and when they reach a certain number using javascript/jQuery to alter the Formee style sheet to make the legend larger? Not quite sure how to go about this, though, looking for some good ideas.
EDIT - Ok, here's the relevant portion of CSS...
.formee fieldset {
border: 1px solid #d4d4d4;
position: relative;
height:30%;
padding: 1.2em 0;
margin: 0 0 4em;
}
What I want to do is, every time the user adds a textbox pair, read out the height attribute value, double that value, and then set this value as the new height in this CSS rule. Is this possible?
EDIT - I ended up making it happen with this function...
function doubleFieldSetSize(divName)
{
var height = $('fieldset#' + divName).css('height');
height = height.replace(/px$/, '');
height = parseInt(height) + 70;
height = height + "px";
$('fieldset#' + divName).css('height', height);
}
Try to add this css, float and height?
.formee fieldset {
float:left;
height:auto;
border: 1px solid #d4d4d4;
position: relative;
padding: 1.2em 0;
margin: 0 0 4em;
}

The CSS input[value=whatever] selector doesn't seem to match against input.value. What am I missing?

N.B.: I should note that the proper solution to this is to just use the 'placeholder' attribute of an input, but the question still stands.
Another N.B.: Since, as Quentin explains below, the "value" attribute stores the default value, and the input.value IDL attribute stores the current value, the JavaScript I used to "fix" the problem in my below example is non-conforming, as it uses the (non-IDL) value attribute to store current, rather than default, values. Besides, it involves DOM access on every key press, so it was always just a flawed demo of the problem I was having. It's actually quite terrible code and shouldn't be used ever.
CSS selectors made me think that I could make an input with a label that acts as a preview without any JS. I absolutely position the input at 0,0 inside the label (which is displayed as an inline-block) and give it a background of "none", but only if it's got a value of "" and isn't focussed, otherwise it has a background colour, which obscures the label text.
The HTML5 spec says that input.value reflects the current value of an input, but even though input.value updates as you type into an input, CSS using the input[value=somestring] selector applies based only on what was explicitly typed into the document, or set in the DOM by the JavaScript setAttribute method (and perhaps by other DOM-altering means).
I made a jsFiddle representing this.
Just in case that is down, here is an HTML document containing the relevant code:
<!doctype html>
<head>
<meta charset="utf-8" />
<title>The CSS Attribute selector behaves all funny</title>
<style>
label {
display: inline-block;
height: 25px;
line-height: 25px;
position: relative;
text-indent: 5px;
min-width: 120px;
}
label input[value=""] {
background: none;
}
label input, label input:focus {
background: #fff;
border: 1px solid #666;
height: 23px;
left: 0px;
padding: 0px;
position: absolute;
text-indent: 5px;
width: 100%;
}
</style>
</head>
<body>
<form method="post">
<p><label>name <input required value=""></label></p>
</form>
<p><button id="js-fixThis">JS PLEASE MAKE IT BETTER</button></p>
<script>
var inputs = document.getElementsByTagName('input');
var jsFixOn = false;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].parentNode.tagName == 'LABEL') { //only inputs inside a label counts as preview inputs according to my CSS
var input = inputs[i];
inputs[i].onkeyup= function () {
if (jsFixOn) input.setAttribute('value', input.value);
};
}
}
document.getElementById('js-fixThis').onclick = function () {
if (jsFixOn) {
this.innerHTML = 'JS PLEASE MAKE IT BETTER';
jsFixOn = false;
} else {
this.innerHTML = 'No, actually, break it again for a moment.';
jsFixOn = true;
}
};
</script>
</body>
</html>
I could be missing something, but I don't know what.
The value attribute sets the default value for the field.
The value property sets the current value for the field. Typing in the field also sets the current value.
Updating the current value does not change the value attribute.
Attribute selectors only match on attribute values.
There are new pseudo classes for matching a number of properties of an input element
:valid
:invalid
:in-range
:out-of-range
:required
A required element with no value set to it will match against :invalid. If you insist on using the value instead of placeholder, you could simply add a pattern or a customValidity function to force your initial value to be counted as invalid.

Categories

Resources