Add class to element based on input value length/state with JavaScript - javascript

I'm trying to create the 'floating labels' effect for my fields. However, I'm having difficulties because the HTML code is structured in such a way that prevents it from being achieved using only CSS as there is no way to use CSS combinators (>,+,~) and I do not have the ability to change the HTML code.
My code:
label {display: block; position: absolute; margin: 15px 0 0 12px; color: #606060; font-family: "Arial";}
input {display: block; padding: 15px 12px; border: 1px solid #bbb; border-radius: 5px; width: 300px;}
<p class="container">
<label for="input">
Label
</label>
<span class="input-wrapper">
<input type="input-text" class="input" name="input" id="input" placeholder="">
</span>
</p>
But I believe it would be possible if I was able to give the container a CSS class based on the field's input/state. I would like to give the container the display-floating-label class if the value of the input is greater than 0 ( > 0 ). And maybe when the input is focused as well. Is that possible with JavaScript?
I've tried:
$(document).ready(function() {
var formFields = $('.container');
formFields.each(function() {
var field = $(this);
var input = field.find('input');
var label = field.find('label');
function checkInput() {
var valueLength = input.val().length;
if (valueLength > 0 ) {
label.addClass('display-floating-label')
} else {
label.removeClass('display-floating-label')
}
}
input.change(function() {
checkInput()
})
});
});
But it didn't work. I'm not very familiar with JavaScript so I would really appreciate if someone could help me out.
Here's what I'm trying to achieve:
*I can not change the structure of the HTML code, I can only work with what I have.

Try the below snippet.
$(document).ready(function() {
$('.input').each(function(){
if( $(this).val() !='' ){
$(this).closest('.container').addClass('display-floating-label');
}
});
$('.input').on('input', function() {
var valueLength = $(this).val().length;
if (valueLength > 0 ) {
$(this).closest('.container').addClass('display-floating-label');
} else {
$(this).closest('.container').removeClass('display-floating-label');
}
});
});
label {position: absolute;margin: 15px 0 0 12px;}
.display-floating-label label {position: absolute; margin: 10px 0 0 12px; color: #606060; font-family: "Arial";font-size:10px;}
input {display: block; padding: 18px 12px 12px 12px; border: 1px solid #bbb; border-radius: 5px; width: 300px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="container">
<label for="input">
Label
</label>
<span class="input-wrapper">
<input type="input-text" class="input" name="input" id="input" placeholder="">
</span>
</p>
<p class="container">
<label for="input">
Label
</label>
<span class="input-wrapper">
<input type="input-text" class="input" name="input2" id="input2" placeholder="" value="Prefill">
</span>
</p>

Related

JavaScript Login Form Problem Related to Remember me Button

I have made this login form from my basic HTML CSS and JavaScript knowledge. There is a Remember me button in this login form I have created and now I have to give it a functionality.
I want to click OK button and then it should:
Create a cookie if Remember Me is set and save Student Id and Name.
I am using Visual Studio Code.
Here is my HTML + JavaScript Code:
!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Login Form</title>
<link rel="stylesheet" href="style1.css">
</head>
<body>
<div class = "f1">
<label for = "uname">
<b>Username</b>
</label>
<input type = "text"
placeholder = "Enter Username"
id = "user"
name = "uname" requitred>
<span id = "username" class = "text-danger font-weight-bold"></span>
<label for = "psw">
<b>Password</b>
</label>
<input type = "text"
placeholder = "Enter Password"
id = "pass"
name = "psw" requitred>
<button type="button" onclick="alert('Login is clicked')">OK</button>
<button type="button" onclick="alert('Cancel is clicked')">Cancel</button>
<input type="checkbox" value="lsRememberMe" id="rememberMe">
<label for="rememberMe">Remember me</label>
<input type="submit" value="Login" onclick="lsRememberMe()">
<script>
if (onclick == "alert('Login is clicked')"){
window.location.assign("Home.html");
}
</script>
</form>
</body>
</html>
CSS Code:-
form{
border: 3px solid black;
}
input[type=text],
input[type=password]{
width:27%;
padding:12px 20px;
margin:8px 0;
display: inline-block;
border: 1px solid black;
box-sizing: border-box;
}
button{
background-color: #04aa6d;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 27%;
}
input[type="checkbox"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
display: inline-block;
width: auto;
}
body {
background-image: url('cool.jpg');
color: #FFFFFF;
}
input[type = Clear]{
font-size : 18px;
padding : 5px;
width : 20%;
border-radius: 0 10px;
border : none;
}
I have tried a lot of different techniques but it not work for me. (Code must be in JavaScript and HTML).
Thanks.
It would be better to save under the localStorage instead of a cookie because cookie is being sent to server every request. But both are ok if you are just saving the name (although that's something most browsers do anyway).
So basically you want to setItem when remeberMe is checked. you want to removeItem otherwise. When onload, restore the value using getItem
var user = document.getElementById("user");
var pass = document.getElementById("pass");
var rememberMe = document.getElementById("rememberMe");
window.addEventListener("load", function() {
console.log('run this: user.value = localStorage.removeItem("login-user-name") || "";');
})
function do_submit() {
if (rememberMe.checked) {
console.log('run this: localStorage.setItem("login-user-name", user.value);');
} else {
console.log('run this: localStorage.removeItem("login-user-name");');
}
alert("will cancel because return false explicitly")
return false;
}
form {
border: 3px solid black;
}
input[type=text],
input[type=password] {
width: 27%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid black;
box-sizing: border-box;
}
button {
background-color: #04aa6d;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 27%;
}
input[type="checkbox"] {
-webkit-appearance: checkbox;
-moz-appearance: checkbox;
appearance: checkbox;
display: inline-block;
width: auto;
}
body {
background-image: url('cool.jpg');
color: #FFFFFF;
}
input[type=Clear] {
font-size: 18px;
padding: 5px;
width: 20%;
border-radius: 0 10px;
border: none;
}
<form class="f1" action="home.html" onsubmit="return do_submit()">
<label for="user">
<b>Username</b>
</label>
<input type="text" placeholder="Enter Username" id="user" name="uname" required>
<span id="username" class="text-danger font-weight-bold"></span>
<label for="pass">
<b>Password</b>
</label>
<input type="text" placeholder="Enter Password" id="pass" name="psw" required>
<!--
<button type="button" onclick="alert('Login is clicked')">OK</button>
<button type="button" onclick="alert('Cancel is clicked')">Cancel</button>
-->
<input type="checkbox" value="lsRememberMe" id="rememberMe">
<label for="rememberMe">Remember me</label>
<input type="submit" value="Login">
</form>
Is student ID a part of the response that you get from the server?
To create cookies, save the student name value in a variable:
const username = document.getElementById("user").value;
and save it as cookie if the Remember me checkbox is checked:
const rememberMe = document.querySelector("rememberMe");
if (rememberMe.checked) {
document.cookie = "username=" + username;
}
Next time on page loads, app reads the cookie value from browser and you can show previous username.
You may use js-cookie for easier cookie manipulation.
More info about JavaScript cookie.

Keep input's place holder text while typing

I have this input :
<input type="number" class="textfield numberField font" name="Price" placeholder="Price"><br>
So the text place holder is price.
When user start typing I would like to keep the word price.
So if he types 65 he will see on the input :
Price 65
Do I need to create another div inside for the word price, or can it be done using js or html ?
I think you want to be like that.
.full-input {
display: inline-block;
padding: 3px;
border: 2px solid blue;
}
input {
outline: none;
border: none;
display: inline-block;
line-height: 1.2em;
font-size: 14pt;
}
label {
display: inline-block;
font-size: 12px;
color: blue;
}
<div class='full-input'><label for='price'>Price</label>
<input type='number'class="textfield numberField font" name="Price">
</div>
One way would be to check if the value is equal to an empty string, and if so, manually set the value to Price. Note that this will require removing the type="number" restriction.
document.getElementsByTagName('input')[0].onkeydown = function() {
if (this.value == '') {
this.value = "Price ";
}
}
<input class="textfield numberField font" name="Price" placeholder="Price">
If you only want to allow numbers, then you could add a pattern validation of something like pattern="Price [0-9]":
document.getElementsByTagName('input')[0].onkeydown = function() {
if (this.value == '') {
this.value = "Price ";
}
}
<form>
<input class="textfield numberField font" name="Price" placeholder="Price" pattern="Price [0-9]">
<input type="submit">
</form>
Keep in mind that both approaches would have the word Price in the value (which may be unintended). Creating a <label> may be more appropriate for your situation.
You may try this:
.textfield.labeled>.label {
flex: 0 0 auto;
margin: 0;
font-size: 14px;
}
.textfield.labeled .label:first-child+input {
border-top-left-radius: 0;
border-bottom-left-radius: 0;
border-left-color: transparent;
}
.textfield.labeled>input {
padding-left: 3px;
border: 1px solid rgba(34,36,38,.15);
box-shadow: none;
}
.textfield.labeled {
display: inline-flex;
color: rgba(0,0,0,.87);
}
.label {
display: inline-block;
background-color: #e8e8e8;
padding: 2px 5px;
color: rgba(0,0,0,.6);
font-weight: bold;
}
<div class="textfield labeled">
<div class="label">
Price
</div>
<input type="number" class="textfield numberField font" name="Price" placeholder="Price">
</div>

Display date and time in input

I currently have the code below. I added a script in the HTML to display time and date in the Interview Start time input (Interview End Time not added yet.
For some reason this does not work and only shows the time for a split second before automatically deleting it.
I tried changing the location of the script, but that didn't work. How would I make the start time stay there, and also output on submit?
const idToBold = [ 'start', 'name', 'profile', 'application', 'age', 'dob', 'origin', 'language' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
//here you check every <input type="text">
if(input.attr('type') == 'text'){
var value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[b]' + value + '[/b]';
}
var label = $("label[for='"+input.attr('id')+"']").text();
formInfo[label] = value;
}
//Age Check
if(input.attr('name') == 'ageCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'Yes'){
message = '[b][Color = Blue]Match[/color][/b]';
}else{
message = '[b][Color = yellow]Age and Date of Birth do not match[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
//Passed Interview
if(input.attr('name') == 'passCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
message = '[b][Color = Green]User has passed the interview [/color][/b]';
}else{
message = '[Color = Red]User hase failed the interview.[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ': ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 300px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
h1 {
margin: 0 0 30px 0;
text-align: center;
}
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime"],
input[type="email"],
input[type="number"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
textarea,
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #8a97a0;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
input[type="radio"],
input[type="checkbox"] {
margin: 0 4px 8px 0;
}
select {
padding: 6px;
height: 32px;
border-radius: 2px;
}
.input_submit {
padding: 19px 39px 18px 39px;
color: #FFF;
background-color: #4bc970;
font-size: 18px;
text-align: center;
font-style: normal;
border-radius: 5px;
width: 100%;
border: 1px solid #3ac162;
border-width: 1px 1px 3px;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
margin-bottom: 10px;
}
fieldset {
margin-bottom: 30px;
border: none;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
label {
display: block;
margin-bottom: 8px;
}
label.light {
font-weight: 300;
display: inline;
}
.number {
background-color: #5fcf80;
color: #fff;
height: 30px;
width: 30px;
display: inline-block;
font-size: 0.8em;
margin-right: 4px;
line-height: 30px;
text-align: center;
text-shadow: 0 1px 0 rgba(255,255,255,0.2);
border-radius: 100%;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src ="javascript/supportJS.js"></script>
<title>Arma Life - Interview Logger</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var time = new Date();
function show(id) {
if (id == 1) {
document.getElementById('start').value=time;
}
if(id == 2) {
document.getElementById('end').value=time;
}
}
</script>
</head>
<body>
<form>
<label for="start"><b>Interview Start Time</b></label>
<input type="text" name="message" id="start">
<button id='1' onClick="show(this.id)">Click Amber</button>
<label for="name"><b>Roleplay Name</b></label>
<input type="text" name="message" id="name">
<label for="profile"><b>Profile Link</b></label>
<input type="text" name="message" id="profile">
<label for="application"><b>Application Link</b></label>
<input type="text" name="message" id="application">
<br><br>
<label for="age"><b>Age</b></label>
<input type="text" name="message" id="age">
<label for="dob"><b>Date of Birth</b></label>
<input type="text" name="message" id="dob">
<label for="ageCondition"><b>Date of Birth and Age match?</b></label><br>
<input type="radio" name="ageCondition" value="Yes">Yes<br>
<input type="radio" name="ageCondition" value="No">No<br>
<br><br>
<label for="origin"><b>Country of Origin</b></label>
<input type="text" name="message" id="origin">
<label for="language"><b>Primary Language</b></label>
<input type="text" name="message" id="language">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input class="input_submit" type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
In HTML button elements are by default of type submit.
If you click on this button, you immediately submit the form:
<button id='1' onClick="show(this.id)">Click Amber</button>
To make this button only performs the action defined on click, without submitting the form, just give it a type of button.
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
const idToBold = [ 'start', 'name', 'profile', 'application', 'age', 'dob', 'origin', 'language' ];
var formInfo = {};
function showInput() {
$('input').each(function(){
var input = $(this);
//here you check every <input type="text">
if(input.attr('type') == 'text'){
var value = input.val();
//check if the id is in the constant of ids that need to add the [B] tag
if(idToBold.includes(input.attr('id'))){
value = '[b]' + value + '[/b]';
}
var label = $("label[for='"+input.attr('id')+"']").text();
formInfo[label] = value;
}
//Age Check
if(input.attr('name') == 'ageCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'Yes'){
message = '[b][Color = Blue]Match[/color][/b]';
}else{
message = '[b][Color = yellow]Age and Date of Birth do not match[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
//Passed Interview
if(input.attr('name') == 'passCondition' && input.is(':checked')){
var message = null;
//check the value, theres: 'pass' and 'fail'.
if(input.val() == 'pass'){
message = '[b][Color = Green]User has passed the interview [/color][/b]';
}else{
message = '[Color = Red]User hase failed the interview.[/color][/b]';
};
var label = $("label[for='"+input.attr('name')+"']").text();
formInfo[label] = message;
}
});
//you can remove this, just for output purpose
var formInfoFormated = '';
jQuery.each(formInfo, function(key, value){
formInfoFormated += key + ': ' + value + '<br>';
});
$('#display').html(formInfoFormated);
}
*, *:before, *:after {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font-family: 'Nunito', sans-serif;
color: #384047;
}
form {
max-width: 300px;
margin: 10px auto;
padding: 10px 20px;
background: #f4f7f8;
border-radius: 8px;
}
h1 {
margin: 0 0 30px 0;
text-align: center;
}
input[type="text"],
input[type="password"],
input[type="date"],
input[type="datetime"],
input[type="email"],
input[type="number"],
input[type="search"],
input[type="tel"],
input[type="time"],
input[type="url"],
textarea,
select {
background: rgba(255,255,255,0.1);
border: none;
font-size: 16px;
height: auto;
margin: 0;
outline: 0;
padding: 15px;
width: 100%;
background-color: #e8eeef;
color: #8a97a0;
box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
margin-bottom: 30px;
}
input[type="radio"],
input[type="checkbox"] {
margin: 0 4px 8px 0;
}
select {
padding: 6px;
height: 32px;
border-radius: 2px;
}
.input_submit {
padding: 19px 39px 18px 39px;
color: #FFF;
background-color: #4bc970;
font-size: 18px;
text-align: center;
font-style: normal;
border-radius: 5px;
width: 100%;
border: 1px solid #3ac162;
border-width: 1px 1px 3px;
box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
margin-bottom: 10px;
}
fieldset {
margin-bottom: 30px;
border: none;
}
legend {
font-size: 1.4em;
margin-bottom: 10px;
}
label {
display: block;
margin-bottom: 8px;
}
label.light {
font-weight: 300;
display: inline;
}
.number {
background-color: #5fcf80;
color: #fff;
height: 30px;
width: 30px;
display: inline-block;
font-size: 0.8em;
margin-right: 4px;
line-height: 30px;
text-align: center;
text-shadow: 0 1px 0 rgba(255,255,255,0.2);
border-radius: 100%;
}
#media screen and (min-width: 480px) {
form {
max-width: 480px;
}
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src ="javascript/supportJS.js"></script>
<title>Arma Life - Interview Logger</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script>
var time = new Date();
function show(id) {
if (id == 1) {
document.getElementById('start').value=time;
}
if(id == 2) {
document.getElementById('end').value=time;
}
}
</script>
</head>
<body>
<form>
<label for="start"><b>Interview Start Time</b></label>
<input type="text" name="message" id="start">
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>
<label for="name"><b>Roleplay Name</b></label>
<input type="text" name="message" id="name">
<label for="profile"><b>Profile Link</b></label>
<input type="text" name="message" id="profile">
<label for="application"><b>Application Link</b></label>
<input type="text" name="message" id="application">
<br><br>
<label for="age"><b>Age</b></label>
<input type="text" name="message" id="age">
<label for="dob"><b>Date of Birth</b></label>
<input type="text" name="message" id="dob">
<label for="ageCondition"><b>Date of Birth and Age match?</b></label><br>
<input type="radio" name="ageCondition" value="Yes">Yes<br>
<input type="radio" name="ageCondition" value="No">No<br>
<br><br>
<label for="origin"><b>Country of Origin</b></label>
<input type="text" name="message" id="origin">
<label for="language"><b>Primary Language</b></label>
<input type="text" name="message" id="language">
<br><br>
<label for="passCondition"><b>Passed?</b></label><br>
<input type="radio" name="passCondition" value="pass">Pass<br>
<input type="radio" name="passCondition" value="fail">Fail<br>
<br><br>
</form>
<input class="input_submit" type="submit" onclick="showInput();">
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
Ok so to keep your content from disappearing remove the form tags. From what I see your have to form element present but you're not using it for their intended purpose. The form tag is trying to do a POST (which is why everything looks like it disappearing) when you click your "Click Amber" button. The form thinks that your button is there to do a "Submit".
Here is more information about html form elements:
https://www.w3schools.com/html/html_forms.asp
You can add type="button" to the "Click Amber" button to prevent your form from submitting on that press. As been said, your form is submitting which is clearing out your page.
Your output code already works correctly.
<button id='1' type="button" onClick="show(this.id)">Click Amber</button>

Increase/decrease value of input integer fieldset with buttons/inputs using Jquery/js

I need to have a series of inputs, with a preset value, each a different integer, and have 1 button that when pressed increases(and another button that decreases) these input values by a preset amount. Say I have inputs of values 10, 20, 30, and then I can increase these values by pressing on a button, say of value 10, so that these input values are updated simultaneously to being 20, 30, 40. I researched about 5-6 previous answers that describe something very similar, but too often "Id" is used whereas I need to reference a class of inputs. One of the codes found here that semi-works is in the following, culled from an answer several years back.
HTML:
<input name="qty" id="qty" type="text" value="10" size="3" >
<input name="qty" id="qty1" type="text" value="20" size="3" >
<input type="button" id="qtyplus" value="+" onclick="return false">
<input type="button" id="qtyminus" value="HELLO" onclick="return false">
Jquery:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>jQuery(function(){
jQuery("#qtyplus").click(function(){
jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) + 1 );
});
jQuery("#qtyminus").click(function(){
if(jQuery('#qty').val()>1)
jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) - 1 );
});
});
There's also a previously authored jfiddle from another posting that I can't make to work for my purposes.
JS Fiddle Demo
HTML:
<form method="post" action="">
<div class="controls">
<div>
<label for="name">Item One</label>
<input type="text" name="french-hens" id="french-hens" value="10">
</div>
<div>
<label for="name">Item Two</label>
<input type="text" name="turtle-doves" id="turtle-doves" value="20">
</div>
<div>
<label for="name">Item Three</label>
<input type="text" name="partridge" id="partridge" value="30">
</div>
</div>
<div class="inc button">+</div>
<div class="dec button">-</div>
<input type="submit" value="Submit" id="submit">
</form>
CSS:
#page-wrap {
width: 500px;
margin: 100px auto;
}
h1 {
font: 26px Georgia, Serif;
margin: 0 0 10px 0;
}
form {
margin: 50px 0 0 0;
}
label {
font: bold 20px Helvetica, sans-serif;
display: block;
float: left;
text-align: right;
padding: 5px 10px 0 0;
width: 140px;
}
input[type=text] {
float: left;
width: 40px;
font: bold 20px Helvetica, sans-serif;
padding: 3px 0 0 0;
text-align: center;
}
form div {
overflow: hidden;
margin: 0 0 5px 0;
}
.dec {
background-position: 0 -29px;
}
.buttons {
padding: 20px 0 0 140px;
}
.button{
cursor: pointer;
}
JS:
$(function() {
$(".button").on("click", function() {
var $button = $(this);
$(".controls input").each(function() {
console.log($(this));
var oldValue = $(this).val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 10; //custom-preset value enter here
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 10; //custom-preset value enter here
} else {
newVal = 0;
}
}
$(this).val(newVal);
});
});
});

Clear icon inside input text

Is there a quick way to create an input text element with an icon on the right to clear the input element itself (like the google search box)?
I looked around but I only found how to put an icon as background of the input element. Is there a jQuery plugin or something else?
I want the icon inside the input text element, something like:
--------------------------------------------------
| X|
--------------------------------------------------
Add a type="search" to your input
The support is pretty decent but will not work in IE<10
<input type="search">
Older browsers
If you need IE9 support here are some workarounds
Using a standard <input type="text"> and some HTML elements:
/**
* Clearable text inputs
*/
$(".clearable").each(function() {
const $inp = $(this).find("input:text"),
$cle = $(this).find(".clearable__clear");
$inp.on("input", function(){
$cle.toggle(!!this.value);
});
$cle.on("touchstart click", function(e) {
e.preventDefault();
$inp.val("").trigger("input");
});
});
/* Clearable text inputs */
.clearable{
position: relative;
display: inline-block;
}
.clearable input[type=text]{
padding-right: 24px;
width: 100%;
box-sizing: border-box;
}
.clearable__clear{
display: none;
position: absolute;
right:0; top:0;
padding: 0 8px;
font-style: normal;
font-size: 1.2em;
user-select: none;
cursor: pointer;
}
.clearable input::-ms-clear { /* Remove IE default X */
display: none;
}
<span class="clearable">
<input type="text" name="" value="" placeholder="">
<i class="clearable__clear">×</i>
</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Using only a <input class="clearable" type="text"> (No additional elements)
set a class="clearable" and play with it's background image:
/**
* Clearable text inputs
*/
function tog(v){return v ? "addClass" : "removeClass";}
$(document).on("input", ".clearable", function(){
$(this)[tog(this.value)]("x");
}).on("mousemove", ".x", function( e ){
$(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]("onX");
}).on("touchstart click", ".onX", function( ev ){
ev.preventDefault();
$(this).removeClass("x onX").val("").change();
});
// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
/*
Clearable text inputs
*/
.clearable{
background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
border: 1px solid #999;
padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
border-radius: 3px;
transition: background 0.4s;
}
.clearable.x { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
<input class="clearable" type="text" name="" value="" placeholder="" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
The trick is to set some right padding (I used 18px) to the input and push the background-image right, out of sight (I used right -10px center).
That 18px padding will prevent the text hide underneath the icon (while visible).
jQuery will add the class "x" (if input has value) showing the clear icon.
Now all we need is to target with jQ the inputs with class x and detect on mousemove if the mouse is inside that 18px "x" area; if inside, add the class onX.
Clicking the onX class removes all classes, resets the input value and hides the icon.
7x7px gif:
Base64 string:
data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=
Could I suggest, if you're okay with this being limited to html 5 compliant browsers, simply using:
<input type="search" />
JS Fiddle demo
Admittedly, in Chromium (Ubuntu 11.04), this does require there to be text inside the input element before the clear-text image/functionality will appear.
Reference:
Dive Into HTML 5: A form of Madness.
input type=search - search field (NEW) HTML5.
According to MDN, <input type="search" /> is currently supported in all modern browsers:
<input type="search" value="Clear this." />
However, if you want different behavior that is consistent across browsers here are some light-weight alternatives that only require JavaScript:
Option 1 - Always display the 'x': (example here)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
el.addEventListener('click', function(e) {
e.target.previousElementSibling.value = '';
});
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Always display the 'x':</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
Option 2 - Only display the 'x' when hovering over the field: (example here)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
el.addEventListener('click', function(e) {
e.target.previousElementSibling.value = '';
});
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
display: block;
}
.clearable-input > [data-clear-input] {
display: none;
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Only display the 'x' when hovering over the field:</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
Option 3 - Only display the 'x' if the input element has a value: (example here)
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
var input = el.querySelector('input');
conditionallyHideClearIcon();
input.addEventListener('input', conditionallyHideClearIcon);
el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
input.value = '';
conditionallyHideClearIcon();
});
function conditionallyHideClearIcon(e) {
var target = (e && e.target) || input;
target.nextElementSibling.style.display = target.value ? 'block' : 'none';
}
});
.clearable-input {
position: relative;
display: inline-block;
}
.clearable-input > input {
padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
display: none;
position: absolute;
top: 0;
right: 0;
font-weight: bold;
font-size: 1.4em;
padding: 0 0.2em;
line-height: 1em;
cursor: pointer;
}
.clearable-input > input::-ms-clear {
display: none;
}
<p>Only display the 'x' if the `input` element has a value:</p>
<div class="clearable-input">
<input type="text" />
<span data-clear-input>×</span>
</div>
<div class="clearable-input">
<input type="text" value="Clear this." />
<span data-clear-input>×</span>
</div>
You could use a reset button styled with an image...
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>
See it in action here: http://jsbin.com/uloli3/63
I've created a clearable textbox in just CSS. It requires no javascript code to make it work
below is the demo link
http://codepen.io/shidhincr/pen/ICLBD
Since none of the solutions flying around really met our requirements, we came up with a simple jQuery plugin called jQuery-ClearSearch -
using it is as easy as:
<input class="clearable" type="text" placeholder="search">
<script type="text/javascript">
$('.clearable').clearSearch();
</script>
​
Example: http://jsfiddle.net/wldaunfr/FERw3/
If you want it like Google, then you should know that the "X" isn't actually inside the <input> -- they're next to each other with the outer container styled to appear like the text box.
HTML:
<form>
<span class="x-input">
<input type="text" class="x-input-text" />
<input type="reset" />
</span>
</form>
CSS:
.x-input {
border: 1px solid #ccc;
}
.x-input input.x-input-text {
border: 0;
outline: 0;
}
Example: http://jsfiddle.net/VTvNX/
Change the text box type as 'search' in the design mode or
<input type="search">
EDIT: I found this link. Hope it helps. http://viralpatel.net/blogs/2011/02/clearable-textbox-jquery.html
You have mentioned you want it on the right of the input text. So, the best way would be to create an image next to the input box. If you are looking something inside the box, you can use background image but you may not be able to write a script to clear the box.
So, insert and image and write a JavaScript code to clear the textbox.
Use simple absolute positioning - it's not that hard.
jQuery:
$('span').click(function(){
$('input', $(this).parent()).val('');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
Vanilla JS:
var spans = document.getElementsByTagName("span");
function clickListener(e) {
e.target.parentElement.getElementsByTagName("input")[0].value = "";
}
for (let i = 0; i < spans.length; i++) {
spans[i].addEventListener("click", clickListener);
}
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
<div style="position:relative; width:min-content;">
<input>
<span style="position:absolute;right:10px">x</span>
</div>
jQuery Mobile now has this built in:
<input type="text" name="clear" id="clear-demo" value="" data-clear-btn="true">
Jquery Mobile API TextInput docs
Something like this??
Jsfiddle Demo
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
.searchinput{
display:inline-block;vertical-align: bottom;
width:30%;padding: 5px;padding-right:27px;border:1px solid #ccc;
outline: none;
}
.clearspace{width: 20px;display: inline-block;margin-left:-25px;
}
.clear {
width: 20px;
transition: max-width 0.3s;overflow: hidden;float: right;
display: block;max-width: 0px;
}
.show {
cursor: pointer;width: 20px;max-width:20px;
}
form{white-space: nowrap;}
</style>
</head>
<body>
<form>
<input type="text" class="searchinput">
</form>
<script src="jquery-1.11.3.min.js" type="text/javascript"></script> <script>
$(document).ready(function() {
$("input.searchinput").after('<span class="clearspace"><i class="clear" title="clear">&cross;</i></span>');
$("input.searchinput").on('keyup input',function(){
if ($(this).val()) {$(".clear").addClass("show");} else {$(".clear").removeClass("show");}
});
$('.clear').click(function(){
$('input.searchinput').val('').focus();
$(".clear").removeClass("show");
});
});
</script>
</body>
</html>
<form action="" method="get">
<input type="text" name="search" required="required" placeholder="type here" />
<input type="reset" value="" alt="clear" />
</form>
<style>
input[type="text"]
{
height: 38px;
font-size: 15pt;
}
input[type="text"]:invalid + input[type="reset"]{
display: none;
}
input[type="reset"]
{
background-image: url( http://png-5.findicons.com/files/icons/1150/tango/32/edit_clear.png );
background-position: center center;
background-repeat: no-repeat;
height: 38px;
width: 38px;
border: none;
background-color: transparent;
cursor: pointer;
position: relative;
top: -9px;
left: -44px;
}
</style>
You can do with this commands (without Bootstrap).
Array.from(document.querySelectorAll('.search-field')).forEach(field => {
field.querySelector('span').addEventListener('click', e => {
field.querySelector('input').value = '';
});
});
:root {
--theme-color: teal;
}
.wrapper {
width: 80%;
margin: 0 auto;
}
div {
position: relative;
}
input {
background:none;
outline:none;
display: inline-block;
width: 100%;
margin: 8px 0;
padding: 13px 15px;
padding-right: 42.5px;
border: 1px solid var(--theme-color);
border-radius: 5px;
box-sizing: border-box;
}
span {
position: absolute;
top: 0;
right: 0;
margin: 8px 0;
padding: 13px 15px;
color: var(--theme-color);
font-weight: bold;
cursor: pointer;
}
span:after {
content: '\2716';
}
<div class="wrapper">
<div class="search-field">
<input placeholder="Search..." />
<span></span>
</div>
</div>
Here's a jQuery plugin (and a demo at the end).
http://jsfiddle.net/e4qhW/3/
I did it mostly to illustrate an example (and a personal challenge). Although upvotes are welcome, the other answers are well handed out on time and deserve their due recognition.
Still, in my opinion, it is over-engineered bloat (unless it makes part of a UI library).
I have written a simple component using jQuery and bootstrap.
Give it a try: https://github.com/mahpour/bootstrap-input-clear-button
Using a jquery plugin I have adapted it to my needs adding customized options and creating a new plugin. You can find it here:
https://github.com/david-dlc-cerezo/jquery-clearField
An example of a simple usage:
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">
<table>
<tr>
<td><input name="test1" id="test1" clas="test" type='text'></td>
<td>Empty</td>
</tr>
<tr>
<td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
<td>Not empty</td>
</tr>
</table>
<script>
$('.test').clearField();
</script>
Obtaining something like this:
No need to include CSS or image files. No need to include that whole heavy-artillery jQuery UI library. I wrote a lightweight jQuery plugin that does the magic for you. All you need is jQuery and the plugin. =)
Fiddle here: jQuery InputSearch demo.

Categories

Resources