Can i put css on a condition required in javascript? - 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.

Related

Why does the 'input' event not get fired when changing the value of an input field?

Consider a minimal form such as the following:
let button = document.querySelector("button");
let firstNameInput = document.querySelector("#firstName");
firstNameInput.style.borderColor = "red";
button.addEventListener('click', () => {
firstNameInput.value = "Goofy";
});
firstNameInput.addEventListener('input', () => {
firstNameInput.style.borderColor = "black";
})
.form__input {
border: none;
outline: none;
border-bottom: 1px solid black;
}
<form>
<label for="firstName">Firstname:</label>
<input type="text" class="form__input" id="firstName">
<button type="button">Button</button>
</form>
When loading this page, you should see an input field with a red bottom-border and next to it a button. If you click on the button, the name "Goofy" is written inside the input field. However, the bottom-border stays red. I would like it to change its color whenever something is written inside the input field. Now, when I go on and change the name manually, the border-color changes its color to black, just as I want. But can anyone explain to me why the border-color did not change when clicking on the button?
The input event is an UI-Event, it's meant to fire when the user does action the page, not when scripts do.
For your case your script can simply call the same callback when it does set the .value.
let button = document.querySelector("button");
let firstNameInput = document.querySelector("#firstName");
const setBorderColor = () => {
firstNameInput.style.borderColor = "black";
};
firstNameInput.style.borderColor = "red";
button.addEventListener('click', () => {
firstNameInput.value = "Goofy";
setBorderColor();
});
firstNameInput.addEventListener('input', setBorderColor)
.form__input {
border: none;
outline: none;
border-bottom: 1px solid black;
}
<form>
<label for="firstName">Firstname:</label>
<input type="text" class="form__input" id="firstName">
<button type="button">Button</button>
</form>

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

how to validate the input while entering the data using Jquery event?

how to validate the input while entering the data using Jquery event?
$("#lname").blur(function() {
if ($("#lname").val().trim().match(/^[a-zA-Z ]+$/)) {
$("#lname").css({"border":"1px solid #cecece"});
$("#error_lname").css("display","none");
}
else{
$("#error_lname").css("display","block");
}
});
If you want to validate as the user types, use the input event instead of blur:
$("#lname").on('input', function() {
if ($("#lname").val().trim().match(/^[a-zA-Z ]+$/)) {
$("#lname").css({"border":"1px solid #cecece"});
$("#error_lname").css("display","none");
}
else{
$("#error_lname").css("display","block");
}
});
You should however note that to follow best practices you should avoid using css() and instead add/remove a class that's defined in an external stylesheet, something like this:
$("#lname").on('input', function() {
var $el = $(this);
var valid = $el.val().trim().match(/^[a-zA-Z ]+$/);
$el.toggleClass('invalid', !valid);
$el.next('.error-msg').toggle(!valid);
});
.invalid { border: 1px solid #CECECE; }
Note that the above is assuming the input you're validating has a following sibling which is the error message which has the class of .error-msg. Organising the logic in this way means that the validation logic can easily be genericised - instead of being tied to each control due to the #error_lname selector.
The answer of Rory is perfect I just want to add that you can also use onkeyup event also to get the same effect.
$("#lname").on('keyup', function() {
var $el = $(this);
var valid = $el.val().trim().match(/^[a-zA-Z ]+$/);
$el.toggleClass('invalid', !valid);
$el.next('.error-msg').toggle(!valid);
});
.error-msg{
display:none;
color:red;
}
.invalid{
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="lname">Last Name:</label>
<input type="text" id="lname">
<span class="error-msg">Error message here ...</span>

Changing part of textbox input's color

I'm wondering if it's possible to change just a section of the a text input box's color. I am creating a comment widget want everything between the # and the : to change to a different color:
<input type="text" placeholder="Want To Say Something?"
value="#user556: This is a test comment" ng-model="Comment" ng-click="getCurrentPosition()"
class="form-control ng-valid valid ng-dirty">
Is this possible to do with jQuery or javascript? Or do I have to convert the text input to a div?
Possible, within a contenteditable element,
and with some JS and a bit of RegExp to replace the desired match:
function colorify() {
this.innerHTML = this.textContent.replace(/#([^:]+):/g, "#<span class='user'>$1</span>:");
}
function uncolorify() {
this.innerHTML = this.textContent;
}
[].forEach.call(document.querySelectorAll(".comment"), function(el){
el.addEventListener("blur", colorify);
el.addEventListener("focus", uncolorify);
});
[contenteditable] {
background:#fafafa;
padding:8px;
border-radius:3px;
border:1px solid #ddd;
}
[contentEditable]:empty:not(:focus):before {
/*http://stackoverflow.com/a/18368720/383904*/
content: attr(data-placeholder);
color: #777;
}
.user{
color: #f0f;
}
(Copy the following text into the contenteditable)<br>
#user547794: Use contenteditable. #johnDoe: nice suggestion btw.
<div class="comment" contenteditable data-placeholder="Want To Say Something?"></div>
Than click outside of the contenteditable.

Change text input border color

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">

Categories

Resources