Change text input border color - javascript

I want to make a form where data is verified using JavaScript before being sent.
When a field is empty, I want to set its border to red.
HTML code:
<label>Question: </label><input type = "text" maxlength = "100" name = "question"> <br />
JavaScript code 1:
fields[i].style.borderColor = "red";
JavaScript code 2:
fields[i].style.border = "1px solid red";
If I use JS code 1, the border changes its color but it has the width bigger than before (even though I do not say anything about border width).
If I use JS code 2, the text input shrinks with 2px and the change is noticeable.
What should I do to change only the border color?

Actually this is preferred by adding and removing classes:
$("input").change(function()
{
var value = $(this).val();
if(value=="")
{
$(this).addClass("red-border");
$(this).focus();
}else
{
$(this).removeClass("red-border");
}
});
And your CSS:
.red-border{
border: 1px solid red;
}

The default user agent stylesheet uses this for the input field:
border: 2px inset;
Now you may ask why is this not defined by default?
by default(In IE the appreance is hard-coded):
appearance: textfield;
But whenever you change something:
appearance: none;
And when the appearance is none, you will see the 2px inset border.
So actually the width is the problem here:
So you want to change 2 propeties: Border-width and border-color
You would need 2 lines now:
document.getElementsByTagName('input')[0].style.border = "red";
document.getElementsByTagName('input')[0].style.borderWidth = "1px";
jsFiddle
However your own solution might be elegant, as it is defined with one line of code:
fields[i].style.border = "1px solid red";
Note that the inset style sets the top and right border lighter where the bottom and left border is the given color. Setting the style to solid will solve this.
It won't harm your code to use the whole shorthand property of border. You always have to be very specific when you want to win the battle with the user agent stylesheet.

I have something like this in production, only it uses alerts instead of color change. Use CSS Styles & classes:
CSS
.error {
border:2px solid red;
}
JavaScript
<script>
function checkField(){
var f = document.getElementById('<name of field>').value;
if (f === "") {
document.getElementById('<name of field>').className = document.getElementById('<name of field>').className + " error";
return false;
}
}
</script>
Then add this to your button/control's click event:
return checkField()
This SO post seems to be similar:changing textbox border colour using javascript

Use outline instead of border.
fields[i].style.outline = "1px solid red";

Try this out. Jquery
$("input").change(function ()
{
var value = this.value;
if(value=="")
{
$(this).css("border", "1px solid red");
}else
{
$(this).css("border",'');
}
}).trigger("change");
Html
<input type="text" class="col">

Related

Can i put css on a condition required in javascript?

I want to know if there is a way to add css on a required element in JavaScript I have many condition and i want it just in this case i want something like that (I know i can't do this)
Thanks for your help !
if (!allAreFilled) { // While required element are empty
alert('Fill all the fields');
objForm.style:required.border = "solid 1px red"; // objForm = document.getElementById('compoundFormId')
}
With css:
input:required {
border: 1px dashed red;
}
You cannot directly change CSS style settings for pseudo elements or classes in Javascript.
But you can set CSS variables from JS.
This snippet sets a CSS variable --border when the submit button is clicked with the value depending on a condition.
const button = document.querySelector('button');
let conditionIsSet = true;
button.addEventListener('click', function() {
document.body.style.setProperty('--border', (conditionIsSet) ? 'red' : 'black');
});
body {
--border: black;
}
input:required {
border: var(--border) 1px solid;
}
<input type="checkbox" onchange="conditionIsSet = !conditionIsSet;">Select condition is true</input>
<br> Input without required: <input> Input with required: <input required>
<button>Submit</button>
Obviously you need to supply whatever condition is needed.

JS: how to switch CSS subclass of an object?

I want to change the view of an object from a JS function depending on any events.
For example, I have a set of forms, including an input form of type text. While it is not completely filled, the color of the frame and font is green, when it is completely filled - red.
At the same time, I want to keep the freedom of the HTML designer and give him the opportunity to set class names arbitrarily. I want to operate at the subclass level.
I set this:
.info.available {
color: green;
border: 1px solid lime;
}
.info.full {
color: red;
border: 1px solid red;
}
And
<input class="info available" type="text" id="info">
I have a function myfunc(obj) that takes a pointer "this" and works with different components of a formset.
How for obj.form.info ... to switch the subclass from "available" to "full" and vice versa? How can I get its current value?
first, specify an input maxlength to know if its is completely filled or not.
<input class="info available" max-length="10" type="text" id="input">
then remove the outline color from your input field when it is clicked or being typed
input.available {
border: 1px solid green;
}
input.full {
border: 1px solid red;
}
input:focus {
outline: none;
}
this is to make .available and .full classes visible. then add an action event to your input field that will listen for every string that is typed. you can do it by:
next in your script tag, create the function that will be fired from your input field
<script>
function myfunc(e) {
let x = document.getElementById('input')
if (x.value.length == 10)
{
x.classList.remove('available')
x.classList.add('full')
}
else {
x.classList.add('available')
x.classList.remove('full')
}
}
</script>
x refers to your input field
x.value.length refers to the length of characters that is in your input field
if x.value.length is equal to your input's maxlength(which we specified as 10), it will replace the class .available by .full and vice versa
you can read the documentation or tutorials here:
https://www.w3schools.com/js/js_events.asp
https://www.w3schools.com/tags/ref_eventattributes.asp
Use maxlength="{maxlen}" for your input.
function myfunc(obj) {
if (obj.value.length >= maxlen) {
obj.classList.remove('available');
obj.classList.add('full');
} else {
obj.classList.add('available');
obj.classList.remove('full');
}
}

Applying css to a javascript variable

I want to add color and border to a javascript variable using css. Below is my code;
var msg = "OK"; //i want this to colored and bordered with green.
msg = "Conflict"; // i want this to be colored and bordered with red.
I tried another answer from other questions but it doesn't seem to work with me.
If you're just trying to add styles to a JavaScript variable you can't do that, and I don't understand what you would hope to achieve by doing that.
I am therefore going to assume you want to add styles to an html element that you have extracted as a JavaScript variable like so
let msgElement = document.getElementById('msg')
let msg = "OK"
msgElement.innerHTML = msg
In this case, you can add styles to the element like so
msgElement.style.color = "red"
msgElement.style.border = "2px solid red"
In your example, when you change the value of msg to "Conflict", you are doing just that - changing it. You can't have two separate values held by the same variable.
As one of the comments says, this is basic web development, so I would advise some further reading, or an online course such as those provided by Codeacademy
As the other answers state, you can't apply a CSS rule to a variable. You can, however, do something like this:
<html>
<head>
<style>
.redgreen {border-style: solid; border-color: green; color: red;}
</style>
<script>
function foo() {
let msg = "<div class='redgreen'>Hello, world!</div>";
document.getElementById("themsg").innerHTML = msg;
}
</script>
</head>
<body onload='foo();'>
<p id='themsg'>Your message here</p>
</body>
</html>
That is, define "msg" as an HTML element instead of a text string.
You can't add CSS to a javascript variable.
if you are create element using javascript
html:
<div class="parent-div">
</div>
js:
var msg = "OK";
element = document.createElement('p');
// Give the new element some content and css
element.innerHTML = msg;
element.style.color = 'green';
element.style.border = "1px solid red";
// append element to parent div
document.querySelector('.parent-div').appendChild(element);
Just do without javascript
html:
<div class="parent-div">
<p class="child-one">OK</p>
<p class="child-two">Conflict</p>
</div>
css:
.parent-div .child-one {
color: red;
border: 1px solid green;
}
.parent-div .child-two {
color: green;
border: 1px solid red;
}

this.style.cursor='hand', not working for the first time when I hover mouse on to the element

I am new to programming. All I was trying is to change the style of cursor to hand onmouseover event. when I run the page for first time it is changing the border style but the cursor style is not being changed, but when I move the cursor onto the image element for the second time everything is working as expected.
can anyone please explain what's the exact reason for this improper behavior and how can I make it work.
NOTE:
I was trying to implement this in asp.net content pages :P so I feel this is easier way instead of maintaining a separate css file
<img alt="Sedan" width="300px" height="200px" id="img" src="Images/WelcomePage/Compact/abc.jpg" />
<script>
img.onmouseover = function () {
this.style.cursor = 'hand';
this.style.border = "2px solid black"
}
img.onmouseout = function () {
this.style.cursor = 'pointer';
this.style.border = "2px solid white"
}
</script>
Try using CSS instead of JavaScript. If you want to do it in the same file, use a style element:
<style>
#img {
border: 2px solid white;
}
#img:hover{
cursor: pointer ;
border: 2px solid black;
}
</style>
That gives the image a white border normally (with the default cursor), then changes it to black with the pointer cursor when the mouse is over the element.
I know how to implement this in css, I was trying to dig out if there is any possibility to implement this in javascript.
Well, that was important information to include in the question.
Two things:
You need to use the correct CSS cursor property values, hand is not a valid value.
You need to ensure that your code runs after the image exists. The easiest way to do that is to put your script tag at the end of your HTML, just before the closing </body> tag.
If you do those things, it works. Of course, the image moves because it doesn't initially have a border:
img.onmouseover = function() {
this.style.cursor = 'pointer';
this.style.border = "2px solid black";
}
img.onmouseout = function() {
this.style.cursor = 'default';
this.style.border = "2px solid white";
}
<img alt="Sedan" width="300px" height="200px" id="img" src="Images/WelcomePage/Compact/abc.jpg" />
I don't recommend relying on the automatic global (the one created because you have id="img"), but it does work.
As kaiido points out, we could just set the cursor property once rather than in the event handlers, since it only applies when the cursor is hovering the element anyway:
img.style.cursor = 'pointer';
img.onmouseover = function() {
this.style.border = "2px solid black";
}
img.onmouseout = function() {
this.style.border = "2px solid white";
}
<img alt="Sedan" width="300px" height="200px" id="img" src="Images/WelcomePage/Compact/abc.jpg" />

Changin a div border with javascript

I have created a div programaticaly using.
var Element;
Element = document.createElement('div');
Now I want to change the right and bottom border to "#CCCCCC 1px solid".
I don't want to use a library for this and using CSS classes is not possible.
element.style.borderRight = element.style.borderBottom = "#CCCCCC 1px solid";
Element.setAttribute("style", "bottom-right: #CCCCCC 1px solid"); ?

Categories

Resources