Add non-editable text before/after input value without changing value - javascript

Can I add a value before or after an input value?
I want to modify the text shown for the value, but without actually changing the value. So If I read out the value then it should still return 1000.
<input id="myInput" type="text" value="1000">
How can I add the text Foo before or Bar after 1000 withouth changing the value itself?
Foo and Bar should NOT be editable by the user.

Though it's not the most elegant, one possibility would be to include the "Foo" and "Bar" parts of the string in the element's value attribute via a helper function (ie setValue() below), and then "sanitize" these extra parts out of the inputs value when accessing the desired value of the input (ie getValue() below):
/* Pad input value with foo bar via custom set helper function */
function setValue(value) {
$('input').val('Foo' + value + 'Bar');
}
/* Extract real value from input value padded with foo bar via
custom get helper function */
function getValue() {
const lengthOfRealValue = $('input').val().length - 6;
return $('input').val().substr(3, lengthOfRealValue);
}
/* Set value and cause padded side effect */
setValue('hello-world');
/* Get value from padded input value */
console.log(getValue())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="myInput" type="text" value="1000">

var input = document.getElementById('myInput');
input.value = "Foo" + input.value + "Bar";
Edit
The markup
span {
display: inline-block;
position: relative;
}
span::after {
content: 'mm';
position: absolute;
right: 5px;
top: 0;
}
<span>
<input id="myInput" type="text" value="1000">
</span>

Use data attribute for multiple input
$('.myInput').val(function(){
var bef =$(this).attr('data-before');
var aft =$(this).attr('data-after');
return bef+$(this).val()+aft;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input class="myInput" type="text" data-before="foo" data-after="bar" value="1000">
<input class="myInput" type="text" data-before="foo1" data-after="bar1" value="1000">
<input class="myInput" type="text" data-before="foo2" data-after="bar2" value="1000">

can save value 1000 in data-value="1000"
and can select this value by
document.querySelectorAll('[data-value]');
or
using
first input to display and second to post to server

This simplest way would be to and some elements before and after:
<span>foo</span>
<input id="myInput" type="text" value="1000">
<span>bar</span>
Then use CSS to style the <input />

Related

Simple JS to change field color when changed

I have a form with several fields that are required, and many that are not required. I want the required fields to be pale pink until they are clicked on and then revert to the default color of all of the fields. I haven't really tried anything because I am not sure how to formulate it. I created a different class for the fields with rgba color value. One example I found does addClass, but the fields I need to change already have a class to define their width, outline, etc. Would addClass CHANGE an existing class, OR is there a "changeClass" functionality or something like that? I tried to modify the answer here: Change Class value With Javascript to work when I clicked the field but that did not work. I tried using document.querySelectorAll too because I have multiple fields separated by other non-required fields and I do not want them to all have the same id or be in the same divs.
I tried
function changeClass(){
document.getElementByClass(".reqd").className = "ssmall4";
}
or
function changeClass(){
document.querySelectorAll(".reqd").className = "ssmall4";
}
with
<input onClick="changeClass()" type="number" id="certYear" name="certYear"value="2020" class ="reqd">
Can anyone connect the dots for me?
I can now get it to work on one field by using:
`<label for="certYear">Certification Year:
<br>
</label>
<input type="number" id="certYear" name="certYear"value="2020"
onclick="myFunction()" class="reqd">`
and
`function myFunction() {
document.getElementById('certYear').style.backgroundColor = "white";
}`
But if I change the function to document.getElementsByClassName I get
"Uncaught TypeError: Cannot set property 'backgroundColor' of undefined"
Same if I try to use document.querySelectorAll (I assume in this one it's because I have to define a variable and I do not know how to enact the bg style color change any way other than above)
I suppose I could just copy the function like 10 times, once for each field and just rename the function and change the id but this seems rather inelegant.
You can do what you're looking for with pure CSS:
.reqd {
background: pink;
}
.reqd:active {
background: white;
}
Substitute in your proper colours, and if you need you can target just the background-color, but essentially this should do it if all you're looking for are pink text fields that are white when they are clicked on ("active").
Actually you can do it without classes.
Do you mean something like this?
const reqInp = document.querySelectorAll('input[required]'); // same as css selector
const allInp = document.querySelectorAll('input[type="text"]'); // all inputs
for (var i=0; i < reqInp.length; i++) { // iterate the required ones
reqInp[i].addEventListener('focus', function() { // if one of them has focus on it
allInp.forEach(function(element){ element.style.background = 'pink'; }) // color all input to pink (or whatever you want)
this.style.background = 'white'; // except this
});
// edit:
reqInp[i].addEventListener('blur', function() { // if one of them loose focus
allInp.forEach(function(element){ element.removeAttribute('style'); }) // remove style attribute so it will return to intial state
});
}
input {display: block; width: 100%;}
input[required] {background: pink;}https://stackoverflow.com/questions/59831874/simple-js-to-change-field-color-when-changed/59832111#
<input type="text" />
<input type="text" />
<input type="text" placeholder="required" required />
<input type="text" placeholder="required" required />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" placeholder="required" required />
<input type="text" placeholder="required" required />
<input type="text" />
<input type="text" />
<input type="text" />

Multiple input save one input value

I have Input section like i want to pass this 3 value in one input value with onchange
<script type="text/javascript">
function updateInput($i){
$('updateval').val($i);
}
</script>
<input type="text" onchange="updateInput(this.value)" >
<input type="text" onchange="updateInput(this.value)" >
<input type="text" onchange="updateInput(this.value)" >
<input type="text" id="updateval" >
i want to show here the all 3 value and with a seperation
like value1:value2:value3
in my last input section
Give the 3 input id not name, eg v1,v2,v3
onchange jquery those 3 input value. $('#updateval').val( [ $('#v1').val(),$('#v2').val(),$('#v3').val()].join(':'));
You're missing the position of source input on your function.
Input without name not passed in form submitted, except you send itvia coding.
<input type="text" class='val' >
<input type="text" class='val' >
<input type="text" class='val' >
<input type="text" id="updateval" >
<script>
$(document).ready(function(){
$('.val').on('keyup',function(){
let out=''
$(".val").each(function() {
out+= $(this).val()+":";
});
$('#updateval').val(out);
})
})
</script>
fiddle
<script type="text/javascript">
function updateInput(){
var val1 = $('#value1').val();
var val2 = $('#value2').val();
var val3 = $('#value3').val();
var output = val1 + ':' + val2 + ':' + val3
$('#updateval').val(output);
}
</script>
<input id="value1" type="text" Onkeyup="updateInput(this.value)" >
<input id="value2" type="text" Onkeyup="updateInput(this.value)" >
<input id="value3" type="text" Onkeyup="updateInput(this.value)" >
<input type="text" id="updateval" value="">
Fiddle
Details commented in demo.
// Reference the first form on page
const form = document.forms[0];
/*
Register form to the input event (or change event with .onchange)
The input event will fire immediately after the user has entered any data
The change event will fire when the user has entered data then triggers a blur event by
focusing elsewhere.
*/
form.oninput = display;
/*
//A Pass Event Object
/*
B1 event.currentTarget is the tag registered to event (form)
B2 .elements.text is a collection of all the form controls [name=text] (inputs)
B3 brackets and spread operator convert collection into an array [...all input]
B4 .map() returns each input value into an array
*/
/*
//C Get output.all and assign its value to the new array then convert it into a string
delimited by colons
//D End function
*/
function display(event) {//A
let texts = [...event.currentTarget.elements.text].map(txt => txt.value);//B1-4
event.currentTarget.elements.all.value = texts.join(':');//C
return false;//D
}
:root {
font: 400 5vw/1.2 Consolas
}
input,
output {
display: block;
font: inherit
}
<form>
<input name='text'>
<input name='text'>
<input name='text'>
<output name='all'></output>
</form>

Set .focus on second last input, not first or last

I have dynamically created inputs via a button, two get created at a time and I'd like the focus to be on the first of the two each time a set is added, so theoretically it'll always be the second last input
I currently use $('input:text:visible:first').focus(); but is there a way to do this but get the second last?
Input1.1
Input1.2
Input2.1
Input2.2
# user creates new input set via button
Input3.1 <---Focus on this one
Input3.2
One solution is to use eq(-2).focus(); (eq() documentation). From there you can read that the argument can be a negative number that represent the next:
indexFromEnd / Type: Integer / An integer indicating the position of the element, counting backwards from the last element in the set.
I have made a simple example to demostrate his use:
$("#myBtn").click(function()
{
$('<input value="new">').appendTo(".wrapper");
$('<input value="new">').appendTo(".wrapper");
$(".wrapper input").eq(-2).focus();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<input type="text" value="input1">
<input type="text" value="input2">
<input type="text" value="input3">
<input type="text" value="input4">
</div>
<button id="myBtn">ADD</button>
You can use input:nth-last-child(n) where n is any number
function createInput() {
let str = `<div class ='ipCon'>
<input type='text'>
<input type='text'>
<input type='text'>
</div>`;
document.getElementById('con').innerHTML = str;
document.getElementsByClassName('ipCon')[0].querySelector('input:nth-last-child(2)').focus()
}
input:focus {
background-color: yellow;
}
<div id='con'>
</div>
<button type='button' onclick='createInput()'> Create Inputs</button>

JS input type date field, keep values selected after form submission

Is there a way for the
<input type="date" id="from" class="mdl-textfield__input" name="from" value="{{moment date=d format='YYYY-MM-DD'}}" style="position:relative; float: left; width: 180px; bottom: 10px;"/>
field to remember selected value after form submission?
You can use the HTML5 Local Storage to save the date after the submit.
This is how you can do it:
1) Add to your form onsubmit function:
<form onsubmit="setDate()">
2) Create Setter and Getter functions to the date:
function setDate(){
var value = document.getElementById('from').value;
localStorage.setItem("user_selected_date", value);
}
function getDate(){
if (localStorage.getItem("user_selected_date") === null) {// Check if there is selected date.
return "{{moment date=d format='YYYY-MM-DD'}}";
}
return localStorage.getItem("user_selected_date");
}
3) Set the value to your input:
document.getElementById('from').value = getDate();
i guess you want something like this ? :
stored the value in a variable after clicking the submit button. you can do whatever you want with that variable
$("#submit").click(function(){
var dateStore = $("input[type='date']").val()
alert(dateStore)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="date" id="from" class="mdl-textfield__input" name="from" value="{{moment date=d format='YYYY-MM-DD'}}" style="position:relative; float: left; width: 180px; bottom: 10px;"/>
<button type="submit" id="submit">
Submit
</button>
Use HTML5 with storage
stored the value in a variable after clicking the submit button. you can do whatever you want with that variable
localStorage.setItem("user_selected_date", value);

How do I create a div element with an id that is dynamically used when calling a method on the div element?

First of all I am new to JavaScript. I am using the aloha editor. I want to create text areas dynamically using div tags by assigning id's for each div. Using that id I have to call a method, which is the aloha method. Everything goes fine but the aloha method is not getting the id. On the browser I am getting an empty space rather than an aloha box.
Here is my code..
javascript
var screen=document.getElementById('addScreens');
num_q=document.getElementById('numquest').value;
for(i=0;i<num_q;i++) {
div1=document.createElement("div");
div1.id="multicolumn";
screen.appendChild(div1);
}
//aloha
$(document).ready(function() {
$('#multicolumn').aloha(); //multicolumn is not defined
});
**HTML**
<html>
<body>
<br><input type="text" name = "numquest" id ="numquest" value="" size="5" style="" disabled>
<input type="button" value="submit" onclick="getFields();">
<div id="addScreens"> <br> </div>
</body>
</html>
<style type="text/css">
#multicolumn {
-webkit-column-width:300px;
-webkit-column-gap:30px;
-moz-column-width:300px;
-moz-column-gap:30px;
column-width:100px;
column-gap:30px;
width:550px;
height: 150px;
margin: 0 auto;
overflow-x: auto;
overflow-y: auto;
}
</style>
So, how do I have the id of the dynamically created div's accessible everywhere??
Thanks in advance for any ideas.
You can create the div inside $document ready and then call aloha on it. See the below code for dynamic id generation
//aloha
$(document).ready(function() {
var screen=document.getElementById('addScreens');
var num_q=document.getElementById('numquest').value;
for(i=0;i<num_q;i++)
{
var div1=document.createElement("div");
div1.id = "multicolumn_" + i;
screen.appendChild(div1);
$('#' + div1.id).aloha();
}
//multicolumn is not defined
});
From the code you have shared no multicolumn div will be created at all because the value of your input field is never set to a numeric value. Considering this line in your code
<input type="text" name = "numquest" id ="numquest" value="" size="5" style="" disabled>
and calling this line in JS
num_q=document.getElementById('numquest').value;
will result in num_q evaluated to an empty string. Hence your loop won't have any effect. You could try to give a default value for your input and access its value a bit differntly with something like this :
<input type="text" name = "numquest" id ="numquest" value="1" size="5" style="" disabled>
//JS
num_q= parseInt(document.getElementById('numquest').value, 10);
On Top of that I must agree with Saravana it will be a better approach to put everything in the $(document).ready function.

Categories

Resources