How can I create a css glow effect with javascript? - javascript

What I'm going after is a code that will gather all my text input fields and detect whether or not they have any input. If so I'd like for there to be a glow effect added, if they're left empty or they delete the data and leave it empty I'd like for the glow effect to turn off.
So far from everything I've found this is what I came up with so far, it doesn't work of course, but it's the best I could try to rationalize.
function glow(){
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
if (text.value ==null){
text.style.boxShadow="#8fd7d2 0px 0px 22px";
}
else
remove.style.boxShadow;
}/**function**/
I used the .getElementsByClassName because the getElementsById didn't support multiple IDs as it seems, but if there's another more efficient way of gathering them all please share.

Simple solution can be adding class having glow with javascript:
var text = document.getElementsByClassName('tex_inp01 tex_inp02');
text[0].className = text[0].className + " glow";
DEMO
Note: If you want to add glow class to each input then you have to iterate through loop and add class to each element. Because text is
HTMLCollection of elements.

You need to get the value of each element, not of the HTMLCollection returned by document.getElementsByClassName; Array.prototype.forEach can help with this. Then, a value can’t be null, but empty.
Edit: Wait a minute… you want the glow effect if the element has an input, right? Then your if-else statement is the wrong way around.
This is the correct function:
function glow() {
"use strict";
Array.prototype.slice.call(document.getElementsByClassName("tex_inp01 tex_inp02")).forEach(function(a) {
if (a.value !== "") {
a.style.boxShadow = "0px 0px 22px #8fd7d2";
}
else {
a.style.boxShadow = "";
}
});
}

You have a couple of mistakes in your existing code (as presented in the question): (1) text.value ==null - do not check against null, because an inputs value will never be a null. Check its length. (2) remove.style.boxShadow; - I think that was a typo. It should have been text.style.boxShadow = 'none'.
..to be a glow effect added, if they're left empty or they delete the
data and leave it empty I'd like for the glow effect to turn off..
You can check if the input has been left empty by simply checking the length of the value. However, to check if the input has been entered and then deleted you will have to keep a flag to keep track of that. You can do that by hooking up the change event on inputs and then setting a flag via data attribute. Later when you are checking each input for applying a style, along with the length also check this attribute to see if the input was edited out.
Here is a simple example putting together all of the above (explanation in code comments):
var inputs = document.getElementsByClassName("a b"), // returns a collection of nodelist
button = document.getElementById("btn"); // just for the demo
button.addEventListener("click", checkInputs); // handle click event on button
[].forEach.call(inputs, function(elem) { // iterate over all selected inputs
elem.addEventListener("change", function() { // handle change event
this.setAttribute("data-dirty", true); // set a data attribute to track..
}); // .. a flag when it is changed
});
function checkInputs() {
[].forEach.call(inputs, function(elem) { // iterate over selected inputs
var isDirty = elem.getAttribute("data-dirty"); // check the dirty flag we set
if ((elem.value.length > 0) || (isDirty)) { // if empty or changed
elem.style.boxShadow = "none"; // reset the style
} else {
elem.style.boxShadow = "#f00 0px 0px 5px"; // else apply shadow
}
});
}
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<input class="a b" /><br /><br /><input class="a b" /><br /><br />
<button id="btn">Check</button>

If you wanted to validate the inputs while the user is typing, you can use keyboard events to check the value of the input(s):
document.querySelector('input[type="text"]').addEventListener('keyup',
function(event){
var element = event.target;
if (element.value.trim() === '') {
element.classList.add('empty');
} else {
element.classList.remove('empty');
}
});
See fiddle for example: http://jsfiddle.net/LrpddL0q/.
Otherwise this could be implemented the same way without the addEventListener to perform as a one-off function.

Jquery can help you as the following
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function () {
$(".MyInput").bind('keypress', function () {
$('.MyInput').css("boxShadow", "#8fd7d2 0px 0px 22px");
});
$(".MyInput").bind('keydown', function () {
if ($(".MyInput").val() == "") {
$('.MyInput').css("boxShadow", "none");
}
});
});
</script>
HTML:
<input type="text" value="" class="MyInput" />
this code working only online If you need to download Jquery library visit this
https://jquery.com/download/

Related

How to remove inner HTML content onchange

I created a form where a user selects options from a checkbox list. So when a user selects an option in the checkbox, I use a function to show the value of the input field using onchange within inner HTML. My question is, how do we remove that same inner HTML content if the user un-selects those options? So when the user toggles back and forth, it either appears or when un-selected, the value gets removed. Thanks
function functionOne() {
var x = document.getElementById("wheels").value;
document.getElementById("demo").innerHTML = x;
}
<input type="checkbox" id="wheels" onchange="functionOne()" value="feature 1">
<div id="demo"></div>
Check the state of the checkbox before you read the value.
function functionOne(cb) {
var x = cb.checked ? cb.value : '';
document.getElementById("demo").innerHTML = x;
}
<input type="checkbox" id="wheels" onchange="functionOne(this)" value="feature 1">
<div id="demo"></div>
Inside the change function on deselect do this:
document.getElementById("demo").innerHTML = '';
The element that is changed has a checked property which can be inspected - it will be either true or false. So write an if/else condition to update the content of the demo element depending on its value.
I've adjusted your code slightly to cache the elements outside of the function, and to add an event listener to the checkbox instead of using inline JS which is a bit old-school these days. Also, since the value is just a string textContent is more suitable in this case than innerHTML.
// Cache the elements
const wheels = document.getElementById('wheels');
const demo = document.getElementById('demo');
// Add a listener to the wheels element which calls the
// handler when it changes
wheels.addEventListener('change', handleChange);
// Here `this` refers to the clicked element. If its
// checked property is `true` set the text content of
// `demo` to its value, otherwise use an empty string instead
function handleChange() {
if (this.checked) {
demo.textContent = this.value;
} else {
demo.textContent = '';
}
}
<input type="checkbox" id="wheels" value="feature 1">
<div id="demo"></div>

Enter Key on Input Automatically Tab to Next Input with Fields in iFrames

I have a form with inputs which also has an iFrame embedded in the form which also has inputs (pseudo HTML):
<input type="text" name="one" value="one" />
<input type="text" name="two" value="two" />
<input type="text" name="three" value="three" />
<iframe
<input type="text" name="bacon" value="bacon">
</iframe>
<input type="text" name="four" value="four" />
<input type="text" name="five" value="five" />
When the user presses tab they are taken from input to input even inside the iframe fields selecting bacon after three. We all love bacon.
I also have some javascript that attempts to focus the next input on enter key:
$(document).ready(function() {
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
var inputs = $(':tabbable');
var next = inputs.index(this) + 1;
var input = inputs.eq(next == inputs.length ? 0 : next);
input.focus();
return false;
}
});
});
The problem is the javascript enter key code never focuses the bacon field, it will skip right over it. jsfiddle:
https://jsfiddle.net/54n8mqkh/4/
Let's all skip answers that include not using the iFrame. I know it is not an ideal implementation. However, I would accept ANY answer that allows the enter key to move through all the fields consistently including the iframe using any type of javascript. It does not have to be jquery specific.
I have tried a few different approaches to solve this but none I have found works. Thanks in advance to anyone who has a solution.
You need to focus inside of the iframe like so :
var frameBody = $("#IFrame_input").contents().find("input");
frameBody.focus();
I am going to answer my own question - after a few more hours I was able to solve my use case by expanding my selector to include the iframe. Then I build the array of inputs manually and while iterating I checked the node type for an iframe. If / when I encountered an iframe, I did the same select inside the iframe and added the inputs within the iframe:
$(document).ready(function() {
// Parent level helper function
window.tabToNext = function(me) {
var selector = ':tabbable, iframe';
var inputElems = [];
$(selector).each(function(index) {
var nodeName = $(this).prop('nodeName').toLowerCase();
if (nodeName == 'iframe') {
$(this).contents().find(selector).each(function(index) {
inputElems.push(this);
});
} else {
inputElems.push(this);
}
});
var inputs = $(inputElems);
var next = inputs.index(me) + 1;
if (next == inputs.length) next = 0;
var input = inputs.eq(next);
input.focus();
return false;
}
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
return window.tabToNext(this);
}
});
// Focus the first input
$('input[name=one]').focus();
});
FWIW: I could not just expand the selector as best I could tell and also I tried to use $.add to build the collection starting with an empty jQuery collection:
var foo = $([]);
foo.add(someElement);
... but it does not honor the order you add. It will re-order to the DOM according to the docs which SEEMS like it should be right, but for some reason my iframe child fields always ended up last and messed up the tab order.
Anyhow, I hope if someone else has this issue some day you find this helpful. Working solution:
https://jsfiddle.net/wbs1zajs/6/

Keeping Submit Button Disabled Until Form Fields Are Full

Would someone be able to take a look at my code and see what I'm missing here?
I have a multi-page form with quite a lot of inputs, and I would like to keep "next page" buttons and the final "submit" buttons disabled until all the fields are full.
I am trying to recreate the process on a smaller scale but in my tests, I cannot seem to re-enable the disabled submit input. I've checked the console and the JS is logging the variable elements so I'm not sure what I'm missing.
function checkForm()
{
var elements = document.forms[0].elements;
var cansubmit= true;
for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 || elements[i].value.length == "" || elements[i].value.length == null)
{
cansubmit = false;
}
document.getElementById("myButton").disabled = !cansubmit;
}
};
<form>
<label for="firstName">First Name:</label> <input type="text" id="firstName" onkeyup="checkForm()" />
<br />
<label for="lastName">Last Name:</label> <input type="text" id="lastName" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
</form>
Your elements array includes your button, which has no value. This will cause your loop to always evaluate to cansubmit = false;.
Try this instead: https://jsfiddle.net/e00sorLu/2/
function checkForm()
{
var elements = document.forms[0].elements;
var cansubmit= true;
for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 && elements[i].type != "button")
{
cansubmit = false;
}
}
document.getElementById("myButton").disabled = !cansubmit;
};
Answer was already accepted, but here are a few other things you might consider:
The way you have it set up now, for absolutely anything other than an empty string "" you're setting button.disabled = false and enabling the button.
You're checking value.length 3 times, but you actually want to
check .value instead. The length property is only a numeric
value for how many code units are in the string - it won't ever be
"" or null, so the only thing you're really checking is the very
first condition for an empty string of length 0.
You're also not accounting for multiple white spaces in a blank string, so " " would be valid) ... or
special characters, so this would be valid: (function goodByeWorld(evil){//do the bad things})();
You're running the checkForm() function on all form elements
(including the <button>) after every single keystroke. This is unnecessary.
Aside from including <button>, which was pointed out in the accepted answer & will always cause this to fail, you should either validate each individual form element with inline error checking
(preferable), or validate all of them once just prior to submission (preferable to server-side validation & kicking it back after submission).
You could bind to onblur() instead and send the current element's value as an argument once that field loses focus. e.g. change to: function checkValue(value) {//validate the value}) and either onblur = checkValue(this) in the HTML or preferably a non-inline event handler that lives in the JS file instead.
You could still do it onkeyup = checkValue(this) to check after every keystroke, but change the function to only check 1 element instead of checking t.h.e. e.n.t.i.r.e. f.o.r.m. dozens of times.
This approach would let you individually keep track of each separate form element's validity (lots of options here depending on what "valid" means - store an array of values, objects with values or "valid/invalid" flags, etc, switch on the field labels to validate this for different types of information). You can run additional validation on the individual elements as well (e.g. min/max name length, eliminating special characters, etc), and display real-time error checking messages next to each form element.
You're defaulting to cansubmit = true which doesn't make much sense, given what you intend for this code to do. Using !cansubmit only serves to confuse yourself & others reading the code. For readability, consider inverting it to disableSubmit so it's in sync with the button.disabled state, which should only be true or false.
Or you can use jQuery.
<script type="text/javascript">
function checkForm() {
var cansubmit = false;
$('form input[type="text"]').each(function (index, element) {
if (element.value == "") {
cansubmit = true;
}
});
document.getElementById("myButton").disabled = cansubmit;
}
</script>

How to select textarea and check if it is readonly?

I am struggling with jQuery. I want to write a script which checks if the text area sharing the same parent (list item) with the button is read-only when that button is clicked. Here is the HTML:
...
<li>
<h1>Title</h1>
<button type="button" onclick="javascript:confirmDelete();">Delete</button>
<button type="button" onclick="javascript:toggle();">Toggle</button>
<textarea class="readOnly" readonly="true">Some text</textarea>
</li>
...
And the script:
<script language="JavaScript">
<!--
...
function toggle()
{
var textArea = $(this).parent("li").children("textarea");
var isReadOnly = textArea.attr("readonly");
if (isReadOnly == "true") {
alert('It\'s read-only.');
} else {
alert('It\'s not read-only.');
}
}
//-->
</script>
It appears that I cannot get passed the var textArea = ...
Update 1:
OK, I broke apart the selection in order to help myself analyze the problem:
...
var btn = $(this);
console.log(btn); //returns value, but not sure what exactly
var li = btn.parent();
console.log(li); //returns value, but not sure what exactly
var textArea = li.children('textarea');
console.log(textArea.prop('tagName')); //returns unidentified
So, there's the error. I can't seem to understand what is actually wrong, as I cannot really learn much if all the output I get from the debug is an object (and I don't even know what it represents; is it an element, or array ...) or unidentified. jQuery is not exactly intuitive.
The property is case sensitive. Try instead
var isReadOnly = textArea.attr("readOnly");
if it is the only you likely need:
...find("textarea")[0];
not
...children("textarea");
or simply $(this).siblings("textarea")[0];
OR select directly
var mylist = $(this).siblings("textarea.readOnly");
if (mylist.length > 0)//true if it is
There are some errors in here.
Firs of all, turns out that when the attribute "readonly" is active, it doesn't have a "true" value, but a "readonly" value.
On the other hand, if you invoque a function by onclick (and I'm not 100% sure), you cannot use $(this). I'd recommend you to do (after giving some ID to the trigger button, or anything to identify it):
$(function() {
$("button#my-button").bind("click", function() {
if ($(this).siblings("textarea").attr("readonly") == "readonly") {
alert("It's readonly");
} else {
alert ("It's not");
}
});
});

Adding constant text to inputted text

I have two input fields, where people can write numbers. And what I need is when a person finished writing in this input field some constant words or symbols are left there near his number.
I think that you didn't get anything from what I wrote above so I will try to explain with this example:
In the upper there are two inputs you see what person printed himself. And two inputs in the bottom are what he gets when he puts his cursor out of the input where he was printing.
(I don't need all four inputs, just two...upper two just show the first step and bottom two show the final step)
I think it can be done by javascript... but I couldn't do it by myself and I couldn't find anything in web...
You'll need to get a reference to the textbox (try onblur event) and then append your static text to the value property.
I've used the following before, the reason I chose using an image over anything else was because text added to an input dynamically can cause confusion, as well as getting in the way when users wish to edit. Using an image meant it could be constantly there and wouldn't get in the way of the user typing:
It's only written in jQuery because it was lying around, this could easily be rewritten in pure js - and it could easily be optimised.
http://jsfiddle.net/pafMg/
css:
input {
border: 1px solid black;
background: #fff;
padding: 2px;
}
markup:
<input class="right-aligned" type="text" />
<input class="left-aligned" type="text" />
code:
In the following code the padding-left and padding-right has to take into account the width of the image you use.
$(function(){
/* For left aligned additions */
$('input.left-aligned')
.css({
'padding-left': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : '2px center',
'background-repeat': 'no-repeat'
});
});
The left aligned version is really simple, the right aligned gets a little bit more complex however:
$(function(){
/* For right aligned additions */
$('input.right-aligned')
.bind('keypress keyup', function(e){
var input = $(this), measure, text = input.val(), x, w, y;
/// You can calculate text width, but it's not easily cross-browser
/// easier method, inject the text to a span and measure that instead
if ( !input.data('measure') ){
/// only build our measuring span the first time
measure = $('<span />')
.hide() // hide it
.appendTo('body')
/// try and match our span to our input font
/// this could be improved
.css({
'font-weight':input.css('font-weight'),
'font-family':input.css('font-family'),
'font-size':input.css('font-size')
});
/// store the measure element for later
input.data('measure', measure );
}
/// handle if the user types white space
text = text
.replace(/\s/g,' ')
.replace(/</g,'>');
measure = input.data('measure');
measure.html(text);
w = measure.width();
y = input.width();
/// calculate the image position (minus padding)
x = w + parseInt(input.css('padding-left')) + 2;
/// take into account the scroll ability of an input
x -= ( w > y ? w - y : 0 );
/// reposition our image background on the input
input
.css({
'padding-right': '20px',
'background-image': 'url(/favicon.png)',
'background-position' : x + 'px center',
'background-repeat': 'no-repeat'
});
}).trigger('keyup');
});
Take a look at the blur event using jQuery: http://docs.jquery.com/Events/blur#fn
Here's a quick sample: http://jsfiddle.net/jDGg9/
<form>
Field 1: <input id="ip1" type="text" value="" />
Field 2: <input id="ip2" type="text" value="" />
</form>
$('#ip1').blur(function() {
$('#ip1').val($('#ip1').val() + ' month');
});
$('#ip2').blur(function() {
$('#ip2').val($('#ip2').val() + ' month');
});
Since you didn't specify using jQuery, here's a simple example with basic Javascript using the blur event (as everyone has already specified) although it might make sense to use the onchange event:
http://jsfiddle.net/A9yVv/1/
<input type="text" id="text1" value="" />
<br />
<input type="text" id="text2" value="" readonly="readonly" />
var text1 = document.getElementById("text1");
text1.onblur = function () {
var text2 = document.getElementById("text2");
text2.value = this.value + " month(s)";
};
If jQuery is available this will be much easier, but the code can be rewritten to work without it if it's not.
When an input loses focus, the blur event is fired, and when it regains focus the focus event is fired. If you store the original value (say, using jQuery's data method), you can accomplish what you're asking fairly easily:
<input type="text" name="months" class="month" />
<input type="text" name="price" class="price" />
<script>
jQuery(function($) {
$('.months')
.blur(function(event) {
// This code runs when the input with class "months" loses focus
var originalValue = $(this).val();
$(this)
.data('original-value', originalValue)
.val(originalValue + ' months');
})
.focus(function(event) {
// This code runs when the input with class "months" gains focus
var originalValue = $(this).data('original-value');
if (typeof originalValue !== 'undefined') {
$(this).val(originalValue);
}
});
$('.price')
.blur(function(event) {
// This code runs when the input with class "price" loses focus
var originalValue = $(this).val();
$(this)
.data('original-value', originalValue)
.val('$ ' + originalValue);
})
.focus(function(event) {
// This code runs when the input with class "price" gains focus
var originalValue = $(this).data('original-value');
if (typeof originalValue !== 'undefined') {
$(this).val(originalValue);
}
});
$('form.myform')
.submit(function(event) {
// This code runs when the form is submitted
// Restore the original values, so they are submitted to the server
$('.months').val($('.months').data('original-value'));
$('.price').val($('.price').data('original-value'));
});
});
</script>
I've done it all without javascript... The problem was that it changed the value of the input field but I didn't need that.
So I've just made images of '$' and 'month' and added them as a background in CSS to the inputs... In the first input field i wrote a property maxlenth='3' so numbers won't be written over the constant text and in the second field I've done padding-left='15px' in CSS.
Thanks everyone.

Categories