Changing input field color if filled - javascript

I have a form with input elements:
<form method="POST" action="User.do">
<div id="buddy-form-group">
<input type="text"
class="form-control form-input-field form-interests-input-field"
name="interests"
onchange="checkFilled()">
</div>
<br/><br/><button class="btn btn-success" type="submit">Send</button>
</form>
I have a scrip that takes all elements of class form-interests-input-field and checks if they are empty. If empty, it sets the color to red, else to green:
function checkFilled() {
var interests = document.getElementsByClassName("form-interests-input-field");
for (var i = 0; i<interests.length; i++) {
if (interests[i].value = "") {
interests[i].style.backgroundColor = "red";
}
else {
interests[i].style.backgroundColor = "green";
}
}
}
The problem is, the color of all fields gets changed to green if at least one field gets field. Once they are green, it never changes to red, even if I erase all the input. I suspect the script puts the green color property on class, rather than individual element. What is the best way to fix it?

Wanted to do this by using css. This worked for me.
input:not([value = ""]){
background-color: black;
color: white;
}

Something like the following should work:
<script>
function checkFilled() {
var interests = document.getElementsByClassName("form-interests-input-field");
for (var i = 0; i<interests.length; i++) {
if (interests[i].value == '') {
interests[i].style.backgroundColor = 'red';
} else {
interests[i].style.backgroundColor = 'green';
}
}
}
</script>
<form>
<div id="buddy-form-group">
<input type="text"
class="form-control form-input-field form-interests-input-field"
name="interests"
onkeyup="checkFilled()">
</div>
<br/><br/>
<button class="btn btn-success" onclick="checkFilled()" type="button">Send</button>
</form>
Changed the = to == in the if statement.
With the addition of the onkeyup and onclick fields, it does what you want. When you click the button, it checks the value of the input field and sets the background color accordingly. It also sets the input field's background color as you type.

Related

Edit specific input button based on user input, and save it with a separate button in vanilla JS

I'm trying to make an input, it has its value from the beginning.
Then, when the user double click on a span, the cursor needs to be in input field and the user should be able to edit it.
Once edit is ready, he needs to press save button in order to save it, not just click outside of the input field(which is by default)
The second button will just delete, reset the name string, and then once again when you press save, it will save the empty string.
All that, will depend on which span the user is dblckicking, so the respective input of a respective span has to be accessed for edit.
I've done something like this for now..
But it's far to be ready. Would appreciate you're ideas.
I need to do it using vanilla JavaScript
var numberOfbuttons = document.querySelectorAll(".name").length;
for (i = 0; i < numberOfbuttons; ++i) {
document.querySelectorAll('.name')[i].ondblclick = function() {
document.getElementById('in1').disabled = false;
document.getElementById('in1').value = 'hahmmm';
};
}
<span id="spn1" class="name">
<input id="in1" type="text" disabled="true" value="Homer Simpson">
<div class="namefunc">
<button class="check">save</button>
<button class="close">delete</button>
</div>
</span>
<span id="spn2" class="name">
<input id="in2" type="text" disabled="true" value="Marge Simpson">
<div class="namefunc">
<button class="check">save</button>
<button class="close">delete</button>
</div>
</span>
<span id="spn3" class="name">
<input id="in3" type="text" disabled="true" value="Bart Simpson">
<div class="namefunc">
<button class="check">save</button>
<button class="close">delete</button>
</div>
</span>
In order to make the correct input field editable, you must not work with the ID of the first input field in the loop. Here is a way to select the correct input field via the double-clicked span element:
document.querySelectorAll(".name").forEach(span => {
span.ondblclick = function() {
let input = span.querySelector("input");
input.disabled = false;
input.value = "hahmmm";
input.focus();
span.querySelector("button.check").onclick = function() {
input.disabled = true;
}
span.querySelector("button.close").onclick = function() {
if (input.disabled == false) {
input.value = "";
input.focus();
}
}
}
});
window.onclick = function() {
let active_input = document.querySelector("input:not([disabled])");
if (active_input) {
active_input.focus();
}
}
I'm not quite sure what the save button is supposed to do. Right now it just disables the input field again, keeping the new value.

Button Function one time

So I am trying to create a page where one can change the background with colorPicker. And it does work, only if I change it, I cannot change it again without refreshing the page. For instance, I changed the BGCR to red, but to change it to Yellow I have to refresh the page. SO what can I do to make it work? here is the code:
const color = document.getElementById('colorPick').value
document.getElementById('changeColor').onclick = changeCol
function changeCol() {
document.body.style.backgroundColor = color
}
<input id="changeColor" type="button" value="Change the Color">
<input type="color" id="colorPick">
When you write:
const color = document.getElementById('colorPick').value;
you're immediately picking up the color value rather than caching the element which means you can't use it again.
Instead do:
const color = document.getElementById('colorPick');
and in your function just assign color.value to the background.
const color = document.getElementById('colorPick');
document.getElementById('changeColor').onclick = changeCol;
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input id="changeColor" type="button" value="Change the Color">
<input type="color" id="colorPick">
As a second solution, if you want you could remove the button which is not required to change the color.
const color = document.getElementById('colorPick');
function changeCol() {
document.body.style.backgroundColor = color.value;
}
<input type="color" id="colorPick" onchange="changeCol()">

Show element in JavaScript by onkeypress function

I'm trying to show save button only if input gets value,
The issue is if i use append for each input i get 1 button printed, what I'm looking for is regardless of input length get the button only once.
The important is input not be empty that's all.
Code
<input class="text_dec form-control" type="text" onkeypress="myFunction()" name="text_dec[]" id="'+ textFieldsCount.toString() +'">
function myFunction() {
$('#moreless').append("button here");
}
any idea?
Instead of keypress, use keyup, this will call the listener just when the key is released, so you will have the correct length of the input value. With that, you can check if the button must be displayed or not.
Also, I would have another check to make sure that input have some value on it to save when clicked.
Like below, take a look:
$(function(){
$('.myInput').on('keyup', function(){
var btnElem = $('.myButton');
var charLength = this.value.length;
if (charLength > 0){
btnElem.show();
}else {
btnElem.hide();
}
});
$(".myButton").on("click", function(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
});
});
.myButton {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="">
<input class="myButton" type="button" value="Save Button" />
</body>
EDIT
Now, if you really need to make as you were doing before (I don't consider it a best practice and also recommend you to rethink if you really wanna go through this) here goes a code that will help you. Click to show.
Here I added the functions and created the button element (if necessary) then append it to DOM just when the input have some value length.
function myFunction(input){
var btnElem = $(".mySaveButton")[0];
if (!btnElem){
btnElem = document.createElement("button");
btnElem.textContent = "Save Button";
btnElem.onclick = btnClicked;
btnElem.className = "mySaveButton";
}
var charLength = input.value.length;
if (charLength > 0){
document.body.append(btnElem);
}else {
btnElem.remove();
}
};
function btnClicked(){
if ($('.myInput').val().trim().length < 1){
alert("Input is empty")
return;
}
//Do your code
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input class="myInput" type="text" value="" onkeyup="myFunction(this)">
</body>
So I think you just want a button to show to the user once they type something in the text box. If that's the case, then you don't really want to append a button every time they press a key in the box.
Instead I'd make a button and set its css to display none and then when they keydown in the text box change the button's css to display block.
Something like this: http://jsfiddle.net/wug1bmse/10/
<body>
<input type="text">
<input class="myButton" type="button" value="button text" />
</body>
.myButton {
display: none;
}
$(function(){
$('input').on('keypress',function(){
var htmlElement= $('.myButton');
htmlElement.css('display', 'block');
});
});
Hiding the element with a class might be easier:
.btn-hidden {
display: none;
}
<input id="save-button" class="btn-hidden" type="button" value="save" />
function showSave() {
$('#save-button').removeClass('btn-hidden');
}
function hideSave() {
$('#save-button').addClass('btn-hidden');
}

jquery, js. custom text color

How can i change the color of the text inside input box to different color. eg. text to green, red, purple etc.. I planned to use select box to store the different color and based on the selected color change the "text" color: but I am having hard time implementing into code. I am new to js, jquery any help will be greatly appreciated. Also what needs to be done to get the text with selected color to a table(do i save the color in databse?). I will be very thankful to get any help on this .
I made a small demo based on your requirements. You can read the comments in the code.
Something like this:
(function() {
function get(id) {
return document.getElementById(id); // Return the element given an id.
}
var selColors = get("selColors"); // Store the context of the selColors element.
var txtMyText = get("txtMyText"); // Store the context of the txtMyText element.
var myForm = get("myForm"); // Store the context of the myForm element.
var selectedColor = get("selectedColor");
// This is an object that has 2 properties: (color and value). These properties can hold in it string values.
var obj = {
color: "",
value: ""
};
// When you select an option.
selColors.onchange = function() {
if (this.value.length > 0) {
obj.color = this.value; // this.value contains the color that you have selected.
selectedColor.setAttribute("style", "background-color: " + obj.color);
txtMyText.setAttribute("style", "color: " + this.value); // With this you can set a style to the txtMyText textbox.
}
};
// When you submit the form.
myForm.onsubmit = function(e) {
obj.value = txtMyText.value;
console.log(obj); // Shows in the console the object with the current color and value of your textbox.
e.preventDefault();
};
})();
#myForm {
border: solid 1px #335a82;
}
#myForm fieldset {
border: solid 1px #a3c9d4;
}
#myForm fieldset div {
margin: 5px;
}
#myForm fieldset div label {
display: inline-block;
width: 120px;
}
#selectedColor {
display: inline-block;
padding: 10px;
width: 120px;
}
<form id="myForm">
<fieldset>
<legend>Configuration</legend>
<div>
<label>Colors:</label>
<select id="selColors">
<option value="">[Select a color]</option>
<option value="#5069b1">#5069b1</option>
<option value="#ff0000">#ff0000</option>
<option value="#841b72">#841b72</option>
</select>
</div>
<label>Selected color:</label>
<div id="selectedColor">
</div>
</fieldset>
<fieldset>
<legend>Preview</legend>
<div>
<label>Text:</label>
<input id="txtMyText" type="text" />
</div>
<div>
<button type="submit">Send</button>
</div>
</fieldset>
</form>
You could use js to select the class or id of the <input class=".." id="..">
Then you would be able to change the CSS attributes with js.
See the following example
<form method="post">
<input type="text" class="input1">
</form>
So your <input> class is input1. Using the following CSS code you could select a class by its name. See the example below
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
}
</script>
Now by adding a CSS atribute like color to the function you could change the existing or add a new CSS rule to your <input> field.
I think you could get pretty far with this example.
Let me know if it helps!
$('#myinput').css("color","#fdd");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="test" id="myinput">
You could try this also:
$('#myinput').css('color',$('#myinput').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="#04edee" id="myinput" onkeyup="$('#myinput').css('color',$('#myinput').val());">
jQuery option to show some fun stuff:
$(function() {
$('#myColors').on('change', function() {
var picked = $(this).val();
$('#currentcolor').css("background-color", picked);
$('#results').append("<div>" + $(this).find("option:selected").text() + "|" + picked + "</div>");
});
// verbose add on click of button
$('#addHot').on('click', function() {
var valHot = '#69b4ff';
var newName = "Hot Pink Triadic Blue";
//$('#myColors').append("<option value='"+valHot+" style='color:"+nameHot+"'>"+nameHot+"</option>");
var newOpt = $("<option></option>");
newOpt.css("color:" + valHot);
newOpt.prop("value", valHot);
newOpt.text(newName);
newOpt.appendTo('#myColors');
console.log(newOpt);
});
});
<div>
<select id="myColors">
<option value="red" style="color:red">Red</option>
<option value="green" style="color:green">Green</option>
<option value="cyan" style="color:cyan">Cyan</option>
<option value="#0080ff" style="color:#0080ff">Analogous Cyan</option>
</select>
<button id="addHot" type="button">
Add Hot Pink Triadic Blue
</button>
</div>
<div>
<div id="currentcolor">
current color is background
</div>
<div id="results">
Show stuff:
</div>
</div>
What you can do create class for every color like .green .purple and just remove and add classes
$(".input1").addClass("red").removeClass("green");
and you can also add remore these classes with selected box color change

Different class (textcolor) in javascript form

I have the problem that I can't set two different text colors (via css classes) in the following javascript form. The standard class is grey (grey text color), but once someone clicks on "Type your mail here" the email color text to type in, should be black. (class black). Someone can help me?
<form name="mainform" method="post">
Your email: <input type="text" size="40" class="grey" name="email" value="{{ fields.email.input }}" onclick="ClearIfAppropriate();">{{ fields.email.error }} <input type="submit" name="submit" value="Go">
</form>
<script type="text/javascript" language="JavaScript"><!--
var LabelText = "Type your email here";
if(document.mainform.email.value.length == 0) {
document.mainform.email.value = LabelText;
}
function ClearIfAppropriate() {
if(document.mainform.email.value == LabelText) {
document.mainform.email.value = "";
document.mainform.email.class = "black";
}
}
//--></script>
CSS Classes
.grey {
color: grey;
}
.black {
color: black;
}
This is easily doable in pure CSS No javascript is necessary:
input.grey:focus
{
color: #000;
}
Although I think ie<8 doesn't support the pseudo-class :focus.
The attribute you want to change is
className
See here http://www.jsfiddle.net/dduncan/hdtvr/
Give an id to your input (id="idElement") and
instead of: document.mainform.email.class = "black";
try:
document.getElementById("idElement").setAttribute("class", "className");
Should do it.

Categories

Resources