Display the last 3 characters of an input field when it is in focus

I want the minutes in my input to only show up when the input is focused. Can this be achieved?

Currently, I am using jQuery to display the full time, but I prefer to always have the full time as the value and only show what is necessary.

Another issue is that the cursor doesn't go where you click in the input field, it ends up at the end. This happens at least in Firefox.

Are there any smarter ideas to tackle this? Can it be done just with CSS, like setting the color of the last 3 characters to transparent 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" />

Answer №1

If you need to position the cursor correctly, one trick is to utilize a dummy form field. This solution involves primarily CSS with a sprinkle of JavaScript to ensure the fields stay in sync. (Based on your query, it seems like you specifically desire only hours to be displayed, not just 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>

Answer №2

Here's an example of using HTML and JavaScript together:

<input id="timeInput" value="12:30" onfocus="showMinutesOnly()" onblur="showWholeTime()"/>

In the accompanying JavaScript code:

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;
}

Take a look at the live demo: http://jsbin.com/rumaveguwe/1/edit?html,js,console,output

Answer №3

To achieve this effect, incorporate a focus and blur option where the time is displayed once ("12:30") but when blurred, only the first part is shown.

Experiment by focusing in and out of the input field to observe the desired behavior.

$('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/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery and Ajax to submit a form in Rails applications

Solved the previous issue, now moving on to another related question. Below is the JavaScript code I am working with: jQuery.ajaxSetup({ 'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript") } }) jQuer ...

What is the best way to ensure elements are rendered in Vue only when they are fully prepared?

Is there a way to delay the rendering of images in my list until all content is ready? I want everything, including text and classes, to finish loading before displaying anything. Even with v-cloak, it's not working! I'm having difficulty with t ...

Steps for turning off the output in hook.io

I am currently utilizing hook.io programmatically for small application servers. Whenever there is a connection or event, it generates output, but I am specifically looking to only receive error messages. Are there any methods to mute the hook objects? ...

Is there a way to keep left-aligned text centered even when it wraps around?

I would like to center a block of left-aligned text within a div, ensuring that the visual width of the text block is centered rather than the block itself. In situations where the div is narrow and the text is too long to fit on one line, causing it to o ...

Event signaling the completion of an Ajax call

Is there a way to identify when an element has finished rendering? For example, I have a div element with id "A" that is being created and rendered dynamically with Ajax. I need to access elements inside this div once it has finished rendering. I attempt ...

AngularJS app enhanced with personalized directive for drag and drop functionality

As part of my AngularJS application, I am implementing a feature where users can drag elements from the left container and drop them into the right container. While most elements can be dragged back to the left container, I am facing an issue with the "Man ...

Failed to update the innerHTML attribute for the anchor tag

I'm attempting to apply styles through DOM manipulation using Angular's renderer2. I have successfully updated styles for all HTML elements except for anchors. In the example below, I am trying to replace the text www.url.com with World within ...

Prioritize loading images over loading any HTML elements

My goal is to ensure that my background images are loaded before the HTML content is displayed. However, I've noticed that certain elements such as input fields are being rendered before the background images finish loading. I've researched vari ...

Tips for Sending Emails from an Ionic Application without Utilizing the Email Composer Plugin

I am attempting to send an email from my Ionic app by making an Ajax call to my PHP code that is hosted on my server. Below is the code for the Ajax call: $scope.forget = function(){ $http({ method: 'POST', url: 's ...

Insert a new row in a table using jQuery

Could you help me figure out how to move an element within a table row into another table using jQuery? I've been considering using 'append', but it requires session handling. What is the best method in this case: should I use ajax, JSON, PH ...

Animating jQuery Accordion in Horizontal Direction Extending to the Far Right

After implementing a horizontal accordion in jQuery based on the tutorial found at the following link: A minor issue arose during animation where a slight space was added on the far right side, causing the tabs to shift slightly. This problem is particula ...

Library for Typescript in Microsoft MakeCode Minecraft

Just started my journey in the world of Minecraft and I am currently trying to navigate through using javascript within the game. Specifically, I have some questions pertaining to javascript objects as I delve into the Windows 10 version of Minecraft. I am ...

`Inconsistency in image width behavior observed in Opera browser`

I am very new to HTML and CSS3. I am teaching myself as I work on creating a new website. For some reason, my image gallery is not displaying properly in Opera browser. The width of portrait images appears distorted only in Opera, whereas landscape images ...

Submit the form with an input value that is located outside of the form

I am facing an issue with a dropdown menu that displays a list of users. When I select a user from the list, a radio button appears with options to Modify user details, Change user Permissions, or Warn User. After choosing an option from the radio buttons ...

methods for obtaining specific rows from a master table and a child table within a JTable

Here I am attempting to write like this.. However, this code is not functioning as expected for me. I am receiving the alert message: [{rcid:1}] Nevertheless, I desire an alert message like this: [{rcid:1, rdsid:10}] Note: rcid represents the selected ...

Integrate the elements from the <template> section into the designated <slot> area

I am trying to retrieve template content, insert it into a custom element with shadow DOM, and style the span elements inside the template using the ::slotted selector. However, it seems like this functionality is not working as I expected. <!doctype h ...

I encountered an issue while attempting to establish a connection to an API using WebSocket. Specifically, I received an error message stating: "Uncaught ReferenceError

Guide on Installing the API from GitHub; const WebSocket = require("ws"); const DerivAPI = require("@deriv/deriv-api/dist/DerivAPI"); // Use your own app_id instead of 1089 for testing // Register your own app at api.deriv.com to get a ...

Creating a visually stunning image grid akin to the meticulously designed layouts found

Forgive my lack of knowledge, but I'm curious about how to create an image or text grid similar to Tumblr using HTML and CSS. I'm looking to achieve a layout like this: ...

Filtering out section boxes does not eliminate empty spaces

Link to Fiddle I've run into a bit of a roadblock while trying to filter my section box for a project I'm currently working on. The issue I'm facing is that instead of collapsing the first section box to display only the filtered options, i ...

Struggling to get troika-three-text installed via npm?

I'm having trouble integrating Troika with my three-js scene. While others seem to have no issue, I am struggling to call the module and encountering problems with references. It's frustrating because I can't seem to find any resources to he ...