Using jQuery $(this).addClass() breaks working code - javascript

I'm creating a form where an error message appears when the input loses focus if the input is empty. I also want to add a class to the input to give it a red border.
The problem arises when I add $(this).addClass("error"); - the error message no longer shows. Does using addClass() change the reference of this within the function? Can anybody explain to me what is happening? I'm usually pretty good with jQuery but I'm a bit lost here.
Here's my code:
$(function() {
$.fn.showError = function(error) {
$(this).addClass("error");
$errorElement = this.closest(".input-field").find(".error");
if (!$errorElement.length) {
$errorElement = $('<span class="error"></span>').appendTo(this.closest(".input-field"));
}
$errorElement.text(this.data("errormsg"));
};
$("input").on("focusout", function(e) {
$(this).showError();
});
});
.error {
border-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div class="input-field">
<input type="text" data-errormsg="Please enter your first name" />
</div>

$errorElement = this.closest(".input-field").find(".error");
Since you just added error to the input, this line finds the input and adds the text to it, however since an input element has no children, the text isn't shown. Use
$errorElement = this.closest(".input-field").find("span.error");

Related

How to do validation of the form fields in for various inputs?

I got a filed in a form for text area and all other are input elements.
I am not able to use the same for text area as its not supported for the above method that is being used.
I want to get a function , if the input is invalid then return false which adds the class invalid and show the errror message.
Can anyone guide , what the alternative method I can use here instead of checkValidity to perform the validation on text area?
I tried using the below function but the event is not getting picked up
function validateTxt(textArea) {
const reg = new RegExp("^[a-zA-Z0-9]+$")
if (!reg.test(textArea.value)) {
return false
}
return true
}
The pattern attribute is not supported on the textarea element. You need to implement it yourself. This can be done by setting its value in a data attribute, which you use to create a RegExp in the input event handler to validate the value against. You can then toggle the class on the element as required.
Try this:
$('textarea').on('input', e => {
const $textarea = $(e.target);
const valid = new RegExp($textarea.data('pattern')).test($textarea.val());
$textarea.toggleClass('invalid', !valid);
});
.invalid {
border: 2px solid #C00;
color: #C00;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<textarea type="text" class="form txt" id="message" data-pattern="^[a-zA-Z0-9]+$"></textarea>

jQuery click events not working as expected

I want the user after clicking the input field, have the anchor options. Thus, I capture the click of these anchors and add the contents of that anchor into the input which was empty, white. But, the script does not work. So, where is the error? Is the logic wrong? At where? I followed the examples from the Jquery library documentation, I do not understand the error. Can you tell me where the error is?
Translation
pt-br 'Colegios' to en-us 'schools'
pt-br 'Unidades' to en-us 'locations'
pt-br 'Inscrição' to en-us 'subscription'
Actions of my script
1. If the user clicks the input type="text", anchor will be added.
2. If it clicks on that anchor, add the value of the content inside the input.
HTML
<input id="incricao" type="text" class="inscricao"/>
<input id="colegios" type="text" class="colegios"/>
<input id="unidades" type="text" class="unidades" />
Javascript/Jquery
$().ready(function(e) {
$('#input').click(function(){
$('.inscricao').append('PresencialOnline');
})
$('#colegios').click(function(){
$('.colegios').prepend('CDF MasterMenino JesusEthos');
})
$('#unidades').click(function(){
$('.unidades').prepend('RecifeJabatão');
})
$("#presencial").click(function() {
var valorDoInput0 = $(".inscricao").text();
$("#inscricao").val(valorDoInput0);
});
$("#online").click(function() {
var valorDoInput1 = $(".inscricao").text();
$("#inscricao").val(valorDoInput1);
});
$("#cdfmaster").click(function() {
var valorDoInput2 = $(".colegios").text();
$("#colegios").val(valorDoInput2);
});
$("#meninojesus").click(function() {
var valorDoInput3 = $(".colegios").text();
$("#colegios").val(valorDoInput3);
});
$("#ethos").click(function() {
var valorDoInput4 = $(".colegios").text();
$("#colegios").val(valorDoInput4);
});
$("#recife").click(function() {
var valorDoInput5 = $(".unidades").text();
$("#unidades").val(valorDoInput5);
});
$("#jabatao").click(function() {
var valorDoInput6 = $(".unidades").text();
$("#unidades").val(valorDoInput6);
});
});
First of all, you can't append anything inside an input tag, try using after instead of append.
Also $('#input') is wrong and you don't have any input id! try changing it to $('#incricao').
And finally, why you use both class and id to select your inputs? remove those classes and just use ids and select your inputs like $('#ID')

How can I edit a hidden input field with jquery and a textarea?

I am not sure if what I am trying to do is possible at all. Ok, so I have successfully created a "drop your images" feature for a site I am working on. This is how it looks (looks will improve).
Now, I have this textbox where I can edit the caption but I am trying to make it so that when I type the text I am able to edit parts of the hidden input box. For, example, the enter caption would edit the Caption part inside the hidden input box.
This is how it looks:
<input value="meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"","DateStamp":"","Privacy":""}">
This is the code I have used
<div class="addtextTopic">
<div class="leimage">
<img src="funnylookingcar.png">
<input class="tosend" value="meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"","DateStamp":"","Privacy":""}">
</div>
<textarea class="lecaptine" placeholder="Enter A Caption"></textarea>
</div>
$(document).ready(function() {
$(".addtextTopic .lecaptine").onchange(function() {
var $cap = $(this)
$(".tosend").val($cap);
});
});
Now, the code above doesn't work, and for some reason, I am beginning to think that if it works, it will replace the entire value, instead of the caption part.
Also, am I on the right direction? is this even possible?
Here's a possible solution.
http://jsfiddle.net/o2gxgz9r/3167/
$(document).ready(function() {
$(".addtextTopic .lecaptine").keyup(function() {
var metaDefault = '"meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"{{CAPTION}}","DateStamp":"","Privacy":""}';
var $cap = $(this).val();
$(".tosend").val(metaDefault.replace('{{CAPTION}}', $cap));
});
});
A few things wrong with your original code.
The change event will only fire when the textarea is blurred, not on keystroke. I changed this to keyup
I created a default string of metaDefault with a magic string of {{CAPTION}} so .replace() would know what to replace.
$cap needs to be the .val() of $(this).
First change your Onchange method to change method and copy value of .lecaptline to .tosend use $cap.val() please find below fiddle for more info
$(document).ready(function() {
$(".addtextTopic .lecaptine").change(function() {
debugger;
var $cap = $(this);
$(".tosend").val($cap.val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="addtextTopic">
<div class="leimage">
<img src="funnylookingcar.png">
<input class="tosend" value="meta":{"userId":"le_user","FolderName":"Name Of the Folder","Caption":"","DateStamp":"","Privacy":""}">
</div>
<textarea class="lecaptine" placeholder="Enter A Caption"></textarea>
</div>
how about change like this?
$('.addtextTopic .lecaptine').bind('input propertychange', function({
});

How can I create a css glow effect with 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/

Unable to get value of input field, even through text() and val() methods

I want to get the value of an input field that a user will type into, then do things with it. I've tried the two ways to get value , text() and val(), on the input fields, but neither work.
Kindly advise on what it could be that I'm missing here.
What happens exactly in the code below is that after hovering a button, the value of an input field would be shown through an alert() function. But the alert is constantly blank.
HTML
<div id="collection_name">
collection name
</div>
<input type="text" id="collection_title" placeholder="Midnight in New York">
<div id="collection_button"></div>
jQuery
var collection_title = $('#collection_title').text();
var collection_button = $('#collection_button');
collection_button.on({
mouseover: function() {
alert(collection_title); // the alert comes out blank
}
});
You need to call the text()/val() methods within the handler itself
var collection_title = $('#collection_title');
var collection_button = $('#collection_button');
collection_button.on({
mouseover: function() {
alert(collection_title.val()); //or .text() depending on the element type
}
});
The reason it was blank before is at the time of initializing
var collection_title = $('#collection_title').text();
it had no text value
Demo Fiddle
var collection_title = $('#collection_name').text();
var collection_button = $('#collection_button');
collection_button.on({
mouseover: function () {
alert(collection_title); // the alert comes out blank
}
});

Categories