Run Function when Css class changes - javascript

I want to change the bordercolor of the next HTML-Element when my input is "dirty" and "valid".
HTML:
<input type="text" class="form-control" id="exampleId" formControlName="exampleId"
[ngClass]="{ 'is-valid': Form.get('exampleId')?.valid && vvtForm.get('exampleId')?.dirty) }"
(onKeyUp)="changeBorderColorOnValidation('exampleId')">
JavaScript:
changeBorderColorOnValidation(id) {
if (this.Form.get(id).valid) {
(document.querySelector('#' + id).nextSibling as HTMLElement).style.borderColor = '#28a745';
}
}
So far, this works, when you type something in the textarea the (onKeyUp) validates if the textarea is empty or not and changes the bordercolor.
I want to have something cleaner like [ngRun]="functionToRun() | functionThatMustBeTrue".
Here:
[ngRun]="changeBorderColorOnValidation('exampleId') | Form.get('exampleId')?.valid && vvtForm.get('exampleId')?.dirty)
Does something like this exist?

Use the Adjacent sibling combinator and Angular's status classes:
.ng-invalid.ng-dirty + * {
border-color: #28a745
}

If I understand your question well, then what you want to do is already handled by angular. You just need to ad the .ng-dirty class to your css. See example below and check the link to angular doc below for details.
[https://angular.io/guide/form-validation#control-status-css-classes][1]
Html:
<input type="text" class="form-control" id="exampleId" formControlName="exampleId"(onKeyUp)="changeBorderColorOnValidation('exampleId')">
Css:
.form-control .ng-invalid .ng-dirty {
border-color: red;
}

Related

How do i change the backgroundcolor of a form element when clicked?

I've been trying to figure out how I can change the background color of a form element when it is clicked on.
Heres the code:
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
<script>
</script>
I'm trying to make it so the form element where it says "text" turns green when clicked, and the form element where it says "more text" turns red when clicked.
I've tried this, which didn't work:
<script>
let form = document.queryselector('input type="text"');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
</script>
I'm very new to coding, so any help is very much appreciated! Thanks!
you should write ('input[type="text"]');
<script>
let form = document.querySelector('input[type="text"]');
form.addEventListener("click", () => {
form.style.backgroundColor = "green";
});
</script>
If you just want the input background to change color while it's focused. You can achieve this by using CSS selectors. No need for JS
input[type=text]:focus {
background-color: red;
}
Or if you want the form background to change
form:focus-within {
background-color:red;
}
The issue is with this line:
let form = document.queryselector('input type="text"');
First of all - the querySelector() method is camel cased - note the capital S. Secondly, your selector is not quite correct - you're looking for: input[type="text"]:
let form = document.querySelector('input[type="text"]');
form.addEventListener('click', () => {
form.style.backgroundColor = 'green'
});
<form id="form">
<input type="text" placeholder="text"/>
<input type="password" placeholder="more text" />
</form>
Notice though that this doesn't change the background colour back once you focus out - you might be better off adding event listeners for the focusout, focusin and maybe blur events - but better still, you can use CSS:
form input[type="text"]:focus {
background-color: green;
}
I would recommend add and Id or a css class into your input tag then you can use querySelector --> https://www.w3schools.com/jsref/met_document_queryselector.asp

Show div if label = empty

I have a label which displays an IP address:
<label id="internet_ipaddr" class="label_s1"></label>
What I want to do is display a div, #youareoffline if the label is empty. This was suggested as an implementation but after playing around I can't get it to work:
if (string.IsNullOrWhiteSpace(#internet_ipaddr)) {
$(#youareoffline).show();
}
The code you've attempted to use looks like a mix of C# (string.isNullOrWhiteSpace()) and pseudo code, not valid JS.
To make this work you can check if the element has any children (text nodes or otherwise) using the is(':empty') method, then show the relevant element. Try this:
if ($('#internet_ipaddr').is(':empty')) {
$('#youareoffline').show();
}
#youareoffline { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="internet_ipaddr" class="label_s1"></label>
<div id="youareoffline">You are offline</div>
Also note that you can make the JS more succinct, although arguably harder to read, by using toggle():
$('#youareoffline').toggle($('#internet_ipaddr').is(':empty'));
you can easily do this using jQuery.
HTML
<label id="label1"></label>
<div id="div1" style="display: none; color: red;">You are off line.</div>
jQuery
var labelText = $("#label1").text();
if (!labelText) {
$("#div1").show();
}

Input box and css altering colors

I have a input box which looks like below,
<input id="basic-search" type="text" value="Enter keyword or phrase" title="basic-search" class="form-text" size="38" onclick = "this.className = 'focused'; javascript:Reset();" onblur = "javascript:Reset();" />
and css for .focused and form-text is,
.focused {
color:black;
}
.form-text
{
background-color: #FFF;
color: #CCC;
}
The input box on load has the content 'Enter keyword or phrase' which is grey initially. Onclick on this box and on typo the font color changes to black(works good). When the delete the contents, tab to next field or on mouse press the content 'Enter keyword or phrase' changes to black. It should still be grey. What change should i make in the css? any inputs would help. Thanks.
Note: I noticed the 'title' field in stackoverflow works as I would want. I want my boc to work the same way.
Use onfocus instead of onclick. Also, for your onblur, append the css class:
jsFiddle: http://jsfiddle.net/QybRX/14/
<input id="basic-search" type="text" value="Enter keyword or phrase" title="basic-search" class="form-text" size="38" onfocus="this.value=''; this.className = 'focused'; javascript:Reset();" onblur = "basicSearch()" />
<input type="text"/>
<script>
function basicSearch()
{
var element = document.getElementById("basic-search");
if ( element.value.length == 0 )
{
element.value = 'Enter keyword or phrase';
element.className = 'form-text';
}
else
{
element.className = 'focused';
}
javascript:Reset();
}
</script>
What's happening is you are adding the "focused" class to the input field when a user clicks it, but that class is never being removed. You either need to remove the class onblur, or switch to using the :focus selector in CSS, like so:
.form-text
{
background-color: #FFF;
color: #CCC;
}
#basic-search:focus
{
color: black;
}
Are you trying to mimic the HTML5 Placeholder attribute ?
If so you might want to have a look at this article

jQuery taking control over label's border color

My jQuery function looks like that
$('input[type="text"]').focus(function() {
$("label").css("border-bottom-color", "red");
});
$('input[type="text"]').blur(function() {
$("label").css("border-bottom-color", "#e6e6e6");
});
1) I have a bunch of text inputs in my form. What I want to do is to change bottom border color of focused text boxes label (there is one label for every text box. And I want to change only focused text boxes label's border color). But my functions changes all labels' border colors at once. How to fix that problem?
2) I have 2 forms. with id's form1 and form2. I want to do same things to second form but color will be another. How to modify this func?
My forms are looking like that
<form id="form1">
...
<label for="fname">First Name</label>
<input name="fname" placeholder="please enter your first name" type="text" />
...
</form>
<form id="form2">
...
<label for="job">Your Job</label>
...
<input name="job" placeholder="please enter your job" type="text" />
</form>
How about this fiddle?
http://jsfiddle.net/RvYca/3/
label tag's for attribute references to an input's id attribute, not its name.
I moved the styles to css too.
Use both CSS and JavaScript:
$('input:text, input:password, textarea').focus(
function(){
$(this).prev('label').addClass('focused');
}).blur(
function(){
$(this).prev('label').removeClass('focused');
});
And, in the CSS:
#form1 label.focused {
border-bottom: 1px solid red;
}
#form2 label.focused {
border-bottom: 1px solid green;
}
JS Fiddle demo.
For question 1, use $(this) as your selector:
$('input[type="text"]').focus(function() {
$(this).css("border-bottom-color", "red");
});
$('input[type="text"]').blur(function() {
$(this).css("border-bottom-color", "#e6e6e6");
});
For question 2, do you mean, after the user has selected both items, in either order? They can't both be in focus at the same time.
your selector is not specific enough for manipulating the css. You must be specific about which label you want to update. Something like this:
$('input[type="text"],textarea,input[type="password"]').focus(function() {
$("label[for='" + $(this).attr('id') + "']").css("border-bottom-color", "red");
});

jquery.parents() is selecting the grandparent and siblings of the grandparent

What I'm trying to accomplish is when a user has focus on a text box, the field set that's in will add a class "active_fieldset" so it gives a nice visual cue of where the user is in the form. Using the following javascript, it does affect the parent fieldset but it also affects all sibling fieldsets as well. Am I doing something wrong? Is there something fundamentally wrong with my HTML or javascript?
Example HTML:
<div id="content">
<form action="next_page" method="post">
<fieldset>
<legend>Foo</legend>
<p><label for="one">One</label> <input type="text" class="input_text" name="one" value="" id="one"></p>
</fieldset>
<fieldset>
<legend>Bar</legend>
<p><label for="two">Two:</label><input type="text" class="input_text" name="two" value="" id="two"></p>
</fieldset>
<p><input type="submit" value="Continue →"></p>
</form>
</div>
form.js:
$(document).ready(function(){
$('.input_text').focus(function(){
$(this).parents('fieldset').addClass("active_fieldset");
});
});
EDIT:
I've included my CSS:
fieldset
{
border-width: 10px 0 0 0;
border-style: solid;
border-color: #0D6EB8;
}
fieldset.active_fieldset
{
border-width: 10px 0 0 0;
border-style: solid;
border-color: #0D6EB8;
}
Try using the closest method. You'll probably need to pair this with some more code to make sure that the class has been removed from all the other field sets.
$('.input_text').focus( function() {
$('fieldset').removeClass('active_fieldset');
$(this).closest('fieldset').addClass('active_fieldset');
});
Quoting from the docs:
Closest works by first looking at the
current element to see if it matches
the specified expression, if so it
just returns the element itself. If it
doesn't match then it will continue to
traverse up the document, parent by
parent, until an element is found that
matches the specified expression. If
no matching element is found then none
will be returned.
I'd suggest:
$("input.input_text").focus(function() {
$("fieldset.active_fieldset").removeClass("active_fieldset");
$(this).parents("fieldset").addClass("active_fieldset");
}).blur(function() {
$("fieldset.active_fieldset").removeClass("active_fieldset");
});
Use parents() with parameter.
$("#test").parents('.something'); // will give you the parent that has a something class.
Perhaps it's the CSS code that has a bug. I think the suggestion to use JQuery.closest was correct.

Categories

Resources