Show last 3 characters in an input only on focus? - javascript

I have inputs with hours and minutes in them, but I only want the minutes to show up if the input is focused. Is this possible?
My current approach uses jQuery to add the full time, but it would be ideal to have the full time as the value the whole time and just show what is necessary.
Also the cursor doesn't end up where you click in the input because of this (the cursor shows up at the end instead. At least in FF).
Other smarter ideas? It's not possible to do it just with css right? Set the color of the last 3 characters to transparent or similar when not focused.
$('input').on('focus', function(e) {
var full_time = $(this).attr('data-full-time');
$(this).val(full_time);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-full-time="12:30" data-short-time="12" value="12" />

To get the cursor to be in the right place, you can use a fake form field. This is mostly CSS and only JS to sync up the fields. (From your example I assume you meant you want only hours to show up, not only minutes.)
$('#real').on('input', function(e) {
$('#fake').val($(this).val().split(':')[0]);
});
.input-container {
position: relative;
}
.input-container input {
position: absolute;
}
#fake {
pointer-events: none;
}
#real {
opacity: 0;
}
#real:focus {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-container">
<input id="fake" type="text" value="12" />
<input id="real" type="text" value="12:30" />
</div>

HTML:
<input id="timeInput" value="12:30" onfocus="showMinutesOnly()" onblur="showWholeTime()"/>
And some JavaScript:
var wholeTimeString;
var minutes;
function showMinutesOnly(){
wholeTimeString = document.getElementById("timeInput").value;
minutes = wholeTimeString.substring(wholeTimeString.indexOf(":")+1);
document.getElementById("timeInput").value = minutes;
}
function showWholeTime(){
document.getElementById("timeInput").value = wholeTimeString;
}
Example: http://jsbin.com/rumaveguwe/1/edit?html,js,console,output

Simply have a .focus and blur option and use the one time ("12:30") but in the .blur() option - split it at the ":" and display just the first part.
Try focussing in and out of the field to see this in action.
$('input').on('focus', function(e) {
var time = $(this).attr('data-time');
$(this).val(time);
});
$('input').on('blur', function(e) {
var time = $(this).attr('data-time').split(":")[0];
$(this).val(time);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-time="12:30" autofocus/>

Related

Bootstrap 4: Scroll on Submit to validate element offset [duplicate]

When trying to submit a form with missing required fields, my browser (Chrome), displays a message mentionning there is a field missing, and if it's out of my screen, it scrolls up to it.
My problem is that I have a 50px fixed header in my webpage, and as a result, the input field is hidden, and the message seems to come out of nowhere:
Instead of
Is there a way around this?
I tried both applying the 50px margin to <html> and to <body>
Cheers
EDIT
Here's a fiddle of the problem: http://jsfiddle.net/LL5S6/1/
I had the exact same problem and resolved it using jquery with this bit of code:
var delay = 0;
var offset = 150;
document.addEventListener('invalid', function(e){
$(e.target).addClass("invalid");
$('html, body').animate({scrollTop: $($(".invalid")[0]).offset().top - offset }, delay);
}, true);
document.addEventListener('change', function(e){
$(e.target).removeClass("invalid")
}, true);
Offset should be the height of your header and delay is how long you want it to take to scroll to the element.
The only way I found is adding an 'override' to the invalid handler.
To implement this for every input in your form you can do something like this.
var elements = document.querySelectorAll('input,select,textarea');
var invalidListener = function(){ this.scrollIntoView(false); };
for(var i = elements.length; i--;)
elements[i].addEventListener('invalid', invalidListener);
This requires HTML5 and this is tested on IE11, Chrome and Firefox.
Credits to #HenryW for finding that scrollIntoView works like expected.
Note that the false parameter for scrollIntoView aligns the input with the bottom, so if you have a large form it may be aligned with the bottom of the page.
jsfiddle
In modern browsers there is a new CSS property for that use case:
html {
scroll-padding-top: 50px;
}
Your JSFiddle updated: http://jsfiddle.net/5o10ydbk/
Browser Support for scroll-padding: https://caniuse.com/#search=scroll-padding
When there are several invalid inputs in the form, you only want to scroll to the first of them:
var form = $('#your-form')
var navbar = $('#your-fixed-navbar')
// listen for `invalid` events on all form inputs
form.find(':input').on('invalid', function (event) {
var input = $(this)
// the first invalid element in the form
var first = form.find(':invalid').first()
// only handle if this is the first invalid input
if (input[0] === first[0]) {
// height of the nav bar plus some padding
var navbarHeight = navbar.height() + 50
// the position to scroll to (accounting for the navbar)
var elementOffset = input.offset().top - navbarHeight
// the current scroll position (accounting for the navbar)
var pageOffset = window.pageYOffset - navbarHeight
// don't scroll if the element is already in view
if (elementOffset > pageOffset && elementOffset < pageOffset + window.innerHeight) {
return true
}
// note: avoid using animate, as it prevents the validation message displaying correctly
$('html,body').scrollTop(elementOffset)
}
})
JSFiddle
ok, i did a dirty test with a code snippet i found here on SO
As it is a code from someone else, i just alter it to scroll to the element that had a missing input requirement.
I do not want any credit for it, and it maybe is not even what you have in mind, you or someone else could use it as a reference.
The goal was to get the id of the forgotten/wrong input element:
var myelement = input.id;
var el = document.getElementById(myelement);
el.scrollIntoView(false);
Please keep in mind that this fiddle only works for your posted fiddle above, it not handles multiple forgotten or wrong input fields.I only wanted to show an alternative.
----->jSFiddle
I tried to use the way of T.J. Moats, but it did not work as needed, because I often came back to the field, which was incorrect first.
So, I made it:
var navhei = $('header').height();
var navheix = navhei + 30;
document.addEventListener('invalid', function(e){
$(e.target).addClass("invalid");
$('html, body').animate({scrollTop: $($(".invalid")[0]).offset().top - navheix }, 0);
setTimeout(function() {
$('.invalid').removeClass('invalid');
},0300);
}, true);
body {
margin: 0;
margin-top: 50px;
text-align: center;
}
header {
position: fixed;
width: 100%;
height: 50px;
background-color: #CCCCCC;
text-align:center;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<header>This is the header</header>
<div>
<form action="">
<br>
<input id="text" type="text" required="required" /><br><br>
<input id="text" type="text" required="required" /><br><br><br><br>
<input id="text" type="text" required="required" /><br><br>
<input id="text" type="text" required="required" /><br><br><br><br>
<input id="text" type="text" required="required" /><br><br><br><br><br><br>
<input id="text" type="text" required="required" /><br><br>
<p>Click send (at the bottom of the page), without filling the input field.</p><br><br><br><br><br><br>
<input id="text" type="text" required="required" /><br><br>
<input type="submit" id="btnSubmit" />
</form>
</div>
I hope it will be helpfull for people :)
You can use oninvalid event attribute of HTML5 and in your script's tag write a function for redirecting it.
Here is the example:
<input type="text" required oninvalid="scroll_to_validator(this)">
<script>
function scroll_to_validator(input)
{
input.focus();
}
</script>
And on clicking on your submit button it will scroll to the invalid field.
For radio button please add only on one radio with same nameHere is the example (jsfiddle)
Two solutions:
One: apply padding to the body -->
body {
padding-top:50px;
}
Two : apply margin to the main container -->
#content {
margin-top:50px;
}
Here's an EASY and FAST way.
$('input').on('invalid', function(e) {
setTimeout(function(){
$('html, body').animate({scrollTop: document.documentElement.scrollTop - 150 }, 0);
}, 0);
});

How do i change the backgroundcolor of a form element when clicked?

I've been trying to figure out how I can change the background color of a form element when it is clicked on.
Heres the code:
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
<script>
</script>
I'm trying to make it so the form element where it says "text" turns green when clicked, and the form element where it says "more text" turns red when clicked.
I've tried this, which didn't work:
<script>
let form = document.queryselector('input type="text"');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
</script>
I'm very new to coding, so any help is very much appreciated! Thanks!
you should write ('input[type="text"]');
<script>
let form = document.querySelector('input[type="text"]');
form.addEventListener("click", () => {
form.style.backgroundColor = "green";
});
</script>
If you just want the input background to change color while it's focused. You can achieve this by using CSS selectors. No need for JS
input[type=text]:focus {
background-color: red;
}
Or if you want the form background to change
form:focus-within {
background-color:red;
}
The issue is with this line:
let form = document.queryselector('input type="text"');
First of all - the querySelector() method is camel cased - note the capital S. Secondly, your selector is not quite correct - you're looking for: input[type="text"]:
let form = document.querySelector('input[type="text"]');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
Notice though that this doesn't change the background colour back once you focus out - you might be better off adding event listeners for the focusout, focusin and maybe blur events - but better still, you can use CSS:
form input[type="text"]:focus {
background-color: green;
}
I would recommend add and Id or a css class into your input tag then you can use querySelector --> https://www.w3schools.com/jsref/met_document_queryselector.asp

How do I display a same div for a number times that user input in jquery?

I have POS system with cheque payments. when the cashier input the number of cheque according to the input the cheque detail form should generated.
Eg : if he enter Number 5, the same form should be display five times How can i do this with jquery.
I have attached up to what i have done so far !!
Thanks in Advance
This is the user input
<input type="number" class="form-control" id="numberOfChq" >
<a id="come" class="btn btn-primary">Submit</a>
This is the div to be repeated
<div id="chk_list" hidden></div>
This is the jquery i tried its displaying only once, i want to diplay as many user input
$("#come").click(function(){
var chqNumebr = $("#numberOfChq").val();
var i;
for (i= 1; i <= chqNumebr; i++ ){
var chqSh = $("#chk_list").slideDown("slow");
}
});
Try the below.
First we need something to add the new divs into, so I created <div id="output"></div> for that.
After pressing submit, you'll see the new divs get added according the number the user entered. But we have to make sure that we empty #output every time the function runs otherwise the newly created divs would just keep adding onto the existing ones.
Secondly, if we are going to have multiple instances of #chk_list then it shouldn't have an ID as all ID's should be unique. Instead, we'll use a class.
$("#come").on('click', function() {
var chqNumebr = $("#numberOfChq").val();
//empty divs that are currently inside of #output
$('#output').empty();
for (var i = 0; i < chqNumebr; i++) {
$('#output').append('<div class="chk_list"></div>')
}
});
.chk_list {
width: 50px;
height: 30px;
background: red;
margin-top: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" class="form-control" id="numberOfChq">
<a id="come" class="btn btn-primary">Submit</a>
<div id="output"></div>

Hide an HTML form field when a button is clicked and replace it with a different field

I have an html form that has a field that needs to become hidden and replaced with another when a button is clicked. I can't get rid of this field altogether because its value still must be submitted. Here is some sample code for reference:
<select id="Id.0" onChange="changeTextBox();">
<input type="button" id="addButton" value="Add" onclick="addQual();"/>
Basically what needs to happen is when the addButton is clicked, Id.0 must disappear (but remain a member of the form) and be replaced by an identical field with id="Id.1" then upon clicking again id="Id.2" and so on.
Is there a way, using JavaScript or jQuery, to hide and replace this field upon clicking this button? Thanks!
This with jQuery might help.
elmCount = 0;
function addQual()
{
$("#Id." + elmCount).css('visibility', 'hidden');
$("#Id." + elmCount).css('height', '0px');
elmCount += 1;
}
Thanks to comments.
<div id="divAny">
<select id="Id.0" onChange="changeTextBox();">
</div>
<input type="button" id="addButton" value="Add" onclick="addQual();"/>
var index = 0;
function addQual(){
$("#divAny").hide();
$("#Id."+index).attr("id" , "Id."+ (++index));
}
As an alternative to #MahanGM's answer, I would minimise the use of jQuery here and do only the following in your addQual function:
addQual = function() {
$('select').toggleClass('hidden');
}
You then need a css class hidden to hide the required element. As others have said, you must not use display: none if you don't want to lose the value of the input.
.hidden {
visibility: hidden;
height: 0;
}
And you start out in your markup with both selects present, only the one you initially want hidden has the appropriate class:
<select id="Id.0">
<select id="Id.1" class="hidden">
<input type="button" id="addButton" value="Add" onclick="addQual();"/>
A basic example with spans: http://jsfiddle.net/5Dayf/1/
Cleanest solution in my eyes: see here jsFiddle
HTML, nothing special:
<select class="replaceableSelect" id="Id.0">
<option name="one" value="one">One</option>
</select>
<button id="addButton">Add</button>
Javascript using jQuery:
$(document).ready(function () {
var changeTextBox = function () {
/** Your code goes here */
};
// add the onchange event to all selects (for the current one and future ones)
$(document).on("click", "select.replaceableSelect", changeTextBox);
var currentId = 0,
currentSelect = $("#Id\\.0");
$("#addButton").on("click", function (e) {
// hide the old select
currentSelect.addClass("invisible");
// create the new select with increased id and add onchange event
currentSelect = $('<select class="replaceableSelect" id="Id.' + (++currentId) + '"><option name="two" value="two">Two</option></select>').insertAfter(currentSelect).bind("change", changeTextBox);
});
});
CSS:
.invisible{
visibility: hidden;
height: 0;
width: 0;
margin: 0;
padding: 0;
border: none;
}
Hint: To process the results of your form, please make sure, every select gets a unique name.

How to bind to browser change of input field? (jQuery)

Please take a look at this:
http://jsfiddle.net/sduBQ/1/
Html:
<form action="login.php" method="post" id="login-form">
<div class="field">
<input name="email" id="email" type="text" class="text-input" value="E-mail" />
</div>
<div class="field">
<input name="code" id="code" type="password" class="text-input" />
<div id='codetip'>Access Code</div>
<label class="error" for="code" id="code_error"></label>
</div>
<br />
<div class="container">
<a id="submit" class="link-2">Access</a>
</div>
</form>
CSS:
a {
border: solid 1px #777;
padding:5px;
}
#codetip {
position:absolute;
margin-top:-20px;
margin-left:5px;
}
Javascript:
$('#email').focus(function(){
if($(this).val()=='E-mail'){$(this).val('');}
});
$('#email').blur(function(){
if($(this).val()==''){$(this).val('E-mail');}
});
$('#code').focus(function(){
$('#codetip').hide();
});
$('#code').blur(function(){
if($(this).val()==''){$('#codetip').show();}
});
$('#codetip').click(function(){
$(this).hide();
$('#code').focus();
});
$('#submit').click(function(){
$(this).submit();
});
The problem is that at least in Chrome(haven't tried other browsers yet) when the Chrome Password Manager saves your password and prefills the password for you when you pick the email. I use jquery to hide/show a div over the top of the password input field as a label, hiding that div when the user clicks into the password field (as can be seen in the above jsfiddle code). I need to know how to hide that div when Chrome prefills the password field...
I've haven't run into this myself, but it appears to be a common issue, based on a few quick Google Searches.
FireFox capture autocomplete input change event
http://bugs.jquery.com/ticket/7830
One easy hack you could do is set up some code that runs every second or two via setInterval, and checks to see if the field has a value.
Something like this...
var code = $('#code');
var codeTip = $('#codetip');
var interval = setInterval(function(){
if (code.val()!=''){
codeTip.hide();
clearInterval(interval);
}
}, 1000);
I had the same issue. None of the solutions I found worked nicely enough. I ended up with this:
If it doesn't matter that your input fields have a background, I handled it just in CSS.
jsfiddle
I just gave the .inputPlaceholder { z-index: -1; } so that it aligned behind the input field and then set the input { background: transparent; } so you could see the div behind it.
Google's default -webkit-autofill style has a yellow background, so that just covers up your placeholder behind it all. No need to mess around with custom plugins/events/setIntervals.

Categories

Resources