jQuery - Select non-sibling element on click - javascript

Basically what I am trying to do is hide the spans initially and show the respective span when I click on an input field and when you leave that input field, that span goes away.
So I have a form that looks something like this (simplified):
<form id="form">
<div id="contact-div-1">
<input type="text" placeholder="First Name" name="FNAME" class="field validation" id="mce-FNAME">
</div>
<span>
Please Enter Your First Name
</span>
<div id="contact-div-2">
<input type="text" placeholder="Last Name" name="LNAME" class="field validation" id="mce-LNAME">
</div>
<span>
Please Enter Your Last Name
</span>
<div id="contact-div-3">
<input type="text" placeholder="E-mail Address" name="EMAIL" class="field validation" id="mce-EMAIL">
</div>
<span>
Please Enter A Valid E-mail Address
</span>
</form>
This is currently the JavaScript code that I have but it is not working properly.
$("#form span").hide();
$("input").focus(function(){
$(this).next('span').fadeIn("slow");
}).blur(function(){
$(this).next('span').fadeOut("slow");
}); //end blur

The <span> elements are siblings with the parent <div> elements of each <input>, so you need to use $(this).parent():
$("input").focus(function(){
$(this).parent().next('span').fadeIn("slow");
}).blur(function(){
$(this).parent().next('span').fadeOut("slow");
});
Example on JSFiddle
Also, to reduce repetition in your code, your "focus" and "blur" handlers can be combined, using .bind() with .fadeToggle():
$("input").bind("focus blur", function() {
$(this).parent().next("span").fadeToggle("slow");
});
Updated JSFiddle

There's nothing next to the input, try
$(this).parent().next('span').fadeIn("slow");

Working Code:
HTML
<form id="form">
<div id="contact-div-1">
<input type="text" placeholder="First Name" name="FNAME" class="field validation" id="mce-FNAME">
<span> Please Enter Your First Name </span>
</div>
<div id="contact-div-2">
<input type="text" placeholder="Last Name" name="LNAME" class="field validation" id="mce-LNAME">
<span> Please Enter Your Last Name </span>
</div>
<div id="contact-div-3">
<input type="text" placeholder="E-mail Address" name="EMAIL" class="field validation" id="mce-EMAIL">
<span> Please Enter A Valid E-mail Address </span>
</div>
</form>
js
$("#form span").hide();
$("input").on('focus', function(){
var s = $(this).siblings('span');
s.fadeIn("slow");
}).blur(function(){
$(this).next('span').fadeOut("slow");
});
Fiddle: Working fiddle

Since your span is sibling of the parent div, instead of the input, you must navigate to the div
$("#form span").hide();
$("input").focus(function(){
$(this).parent().next('span').fadeIn("slow");
}).blur(function(){
$(this).parent().next('span').fadeOut("slow");
}); //end blur
If you have control over the HTML, and both the span and input hold related information, it may also make sense to put them close together (i.e., child of the same div). Your original js code would work, then.

HTML
<form id="form">
<div id="contact-div-1">
<input type="text" placeholder="First Name" name="FNAME" class="field validation" id="mce-FNAME">
<span>
Please Enter Your First Name
</span>
</div>
<div id="contact-div-2">
<input type="text" placeholder="Last Name" name="LNAME" class="field validation" id="mce-LNAME">
<span>
Please Enter Your Last Name
</span>
</div>
<div id="contact-div-3">
<input type="text" placeholder="E-mail Address" name="EMAIL" class="field validation" id="mce-EMAIL">
<span>
Please Enter A Valid E-mail Address
</span>
</div>
</form>
JQuery
$("#form span").hide();
$("input").focus(function(){
$(this).next('span').fadeIn("slow");
}).blur(function(){
$(this).next('span').fadeOut("slow");
});
DEMO

You can give id's to your spans that are a function of say the name attribute of the corresponding input and then refer to them directly that way... this way you are also not as captive to whether or not you change the design where the hierarchy isn't the same etc.
For example:
<span id="span_FNAME">...</span>
Then jquery
$("input").focus(function() {
var s = '#span_'+$(this).attr("name");
$(s).fadeIn("slow")
...

Related

How to append and remove different appended divĀ“s using jquery/javascript?

I have built a form where you can add a person by clicking a button. Now, I want to add a new button to delete the latest added person. My current code only deletes one person, and after that, I can't add another person again. Do someone know what's wrong?
$(document).ready(function(){
$("#button1").click(function(){
$(".flex-container-name-adult").append($(".test1").html());
});
});
$(document).ready(function(){
$("#button3").click(function(){
$(".test1").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flex-container-name-adult">
<button id="button1">Add person</button>
<button id="button3">Delete person</button>
<div class="test1">
<div class="flex-wrapper-name-adult">
<span class="adult">Person</span><br>
<input type="text" class="input" placeholder="Name" name="name" required>
<input type="text" class="input" placeholder="Nachname" name="nachname" required>
<input type="date" class="input" placeholder="Geburtsdatum" name="geburtstag" required onfocus="(this.type='date')" onblur="(this.type='Geburtsdatum')">
</div>
</div>
</div>
When you click the add person button you are appending the html of test1 to the element with class flex-container-name-adult. That html don't include the div with test1 class itself. Now, when you click the delete person button you are deleting all the elements with the class test1. So, after that action, there will be no more elements with class test1 on the document that you can later use on the add person button.
I suggest to use .clone() for what you want to do, and to always delete the last added person. Something like this:
$(document).ready(function()
{
$("#button1").click(function()
{
// Clone the first ".test1" element and append it to the wrapper.
$(".flex-container-name-adult").append($(".test1").first().clone());
});
$("#button3").click(function()
{
// Delete last ".test1" element, if exists more than one.
let tests = $(".test1");
if (tests.length > 1)
tests.last().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="flex-container-name-adult">
<button id="button1">Add person</button>
<button id="button3">Delete person</button>
<div class="test1">
<div class="flex-wrapper-name-adult">
<span class="adult">Person</span><br>
<input type="text" class="input" placeholder="Name" name="name" required>
<input type="text" class="input" placeholder="Nachname" name="nachname" required>
<input type="date" class="input" placeholder="Geburtsdatum" name="geburtstag" required onfocus="(this.type='date')" onblur="(this.type='Geburtsdatum')">
</div>
</div>
</div>

Choose between ids that only meet some conditions

I'm facing a problem with my project. My user can create a new div by clicking a button, but he can remove whatever div he wants, expect the first one. So if he create 2 new divs here is what the code will look like:
<div id="container1">
<input type="text" id="title1"><br />
<input type="text" id="description1">
</div>
<div id="container2">
<input type="text" id="title2"><br />
<input type="text" id="description2">
</div>
<div id="container3">
<input type="text" id="title3"><br />
<input type="text" id="description3">
</div>
If the user remove the second div my code will look like this.
<div id="container1">
<input type="text" id="title1"><br />
<input type="text" id="description1">
</div>
<div id="container3">
<input type="text" id="title3"><br />
<input type="text" id="description3">
</div>
Pretty simple. Now I want to use the information entered by the user in the text inputs, but I don't know how to select the active divs. Is there a way to select the container1 and container3 in the example above?
Keep in mind that the user can use up to 99 new div.
Your help is appreciated. Thank you,
Just apply a CSS selector:
<div id="parent">
<div id="container1">
<input type="text" id="title"><br />
<input type="text" id="description">
</div>
<div id="container3">
<input type="text" id="title1"><br />
<input type="text" id="description1">
</div>
</div>
$('#parent > div')
See here for more information: https://api.jquery.com/category/selectors/
You can add a class to each item. You would need to amend your code that is called when the button is clicked to handle this.
Let's say you gave all titles a class of "myTitle" and you gave all descriptions a class of "myDescription". Your div created would look something like this:
<div id="container1">
<input type="text" id="title" class="myTitle">
<br />
<input type="text" id="description" class="myDescription">
</div>
Now, in order to get all titles and descriptions you'd use jQuery and say:
$('.myTitle').each(function () {
console.log($(this).val());
});
$('.myDescription').each(function () {
console.log($(this).val());
});
First of all, you have multiple divs with the id "title" and "description", so change those to class. You can select the nth div with jquery: $("#container" + n)
you can select the title of the nth div: `$("#container" + n).children(".title");
you can select all of the divs by adding a class to them, such as .container

Using JQuery on changing sibling input of the same div group only

So I've been working on a code that would try to pre-fill some disabled inputs with a keyup() function from another enabled input that are all enclosed in one div element. What happens is that upon key release, it tries to change the value of the disabled inputs from that specific row of divs. Here's what I currently have on my code
<div class="container-fluid" id="clonegrp">
<div class="row grpit">
<div class="col-md-7">
<input type="text" name="it[]" class="form-control" id="item" placeholder="Chemical/Equipment*" required="true">
</div>
<div class="col-md-2">
<input type="text" name="amount[]" class="form-control" placeholder="Amount*" required="true">
</div>
/<div class="col-md-1">
<input type="text" class="form-control" id="max" placeholder="Max" readonly="readonly">
</div>
<div class="col-md-1">
<input type="text" class="form-control" id="unit" placeholder="Unit" readonly="readonly">
</div>
</div>
so this group of inputs can be cloned by some button and through this JQuery code
var $button2=$('#add-item'),
$row2=$('.grpit').clone(),
$try2=$('#clonegrp');
$button2.click(function() {
$row2.clone().appendTo($try2);
});
the problem lies at the part where I try to do the live keyup function
$(document).ready(function() {
$('#clonegrp').on('keyup','#item', function() {
$('#max').val('some text');
});
});
I know that this is wrong since the id part would mess up which of the cloned inputs with the #max id gets to change the input. I can't seem to figure out how to get the #max sibling of the currently focused #item input. How do I do that?

Change the link of a button based on a set of conditions

So basically I have this sign up button which when clicked on expands a hidden form.
What I want to be able to do is when the button is clicked the the first time, then the form should expand as it does at the moment, however I want it so that once the form is expanded, the same button's link should change so the form could be submitted.
As I have it at the moment when I click the button once the form has been expanded, it simply collapses the form back to how it was to start with.
Here is my code:
// jQuery Script that does the toggling for expanding and collapsing the hidden form
<script>
$(document).ready(function(){
$("#button-1").click(function(){
$("#special1").toggle()
})
})
</script>
//CSS rule for hiding the form (collapse)
<style>
#special1{ display: none }
</style>
// HTML form
<center>
<form action="form_process.php" id="special1">
<div>
<input type="text" class="input" name="forename" size="20" maxlength="40" placeholder="First Name"/> <br />
<input type="text" class="input" name="surname" size="20" maxlength="40" placeholder="Surname"/> <br />
<input type="email" class="input" name="email" size="20" maxlength="40" placeholder="Email"/> <br />
<input type="password" class="input" name="password" size="20" maxlength="40" placeholder="Password"/> <br />
<br/>
</form>
// This is the button that expands and collapses the above form
<input type="submit" value="Sign Up" id="button-1" class="submit"/>
</center>
In the click event, check the visibility of the form and accordingly, display or submit it.
This should work -
$(document).ready(function(){
$("#button-1").click(function(){
if($("#special1").is(":visible")){
$("#special1").submit();
}else{
$("#special1").show();
}
})
})
You should unbind the click event after the first click.
$("#button-1").click(function(){
$("body").off("click","#button-1");
$("#special1").toggle();
})
$(document).ready(function(){
$("#button-1").click(function(e){
e.preventDefault();
$("#special1").toggle()
})
});
or
$(document).ready(function(){
$("#button-1").click(function(e){
$("#special1").toggle();
return false;
})
});

Javascript: validate single input?

I'd like to validate a form step by step via Javascript. For example, I've like that as soon as a user fills an input box and goes to another one, a Javascript function is called. In other words, I've like to create a real-time validation.
HTML:
<form id="form_register" method="post" action="">
<fieldset>
<legend>Register</legend>
<ul>
<li>
<label for="username">Username:</label>
<input type="text" name="username" id="username" maxlength="25" />
</li>
<li>
<label for="password">Email address:</label>
<input type="text" name="email" id="email" maxlength="50"/>
</li>
<li>
<label for="password">Password:</label>
<input type="password" name="password" id="password" maxlength="32"/>
</li>
<li>
<label for="password">Confirm Password:</label>
<input type="password" name="cpassword" id="cpassword" maxlength="32"/>
</li>
</ul>
<input type="submit" value="Create Account">
</legend>
</fieldset>
</form>
I've already created the .js file and it looks like the following one.
Javascript:
function checkUsername(){
//etc..
}
function checkEmail(){
//etc..
}
function checkPassword(){
//etc..
}
function checkConfirmPassword(){
//etc..
}
How do I link the HTML page with the script?
Thank you.
Use the onblur event, as described here
<input type="text" name="username" id="username" maxlength="25" onblur="checkUsername()" />
It sounds like you're looking to execute these functions on the blur event for each input element. Something like this:
var usernameInput = document.getElementById('username');
usernameInput.onblur = checkUsername;
//How do I link the HTML page with the script? Thank you.
using the script tag:
also, i am not sure why everyone is suggesting onblur, isn't onchange is better for validation purpose? why would we want to validate when the value is not changed? onblur may be required only when the validation of a field is dependant on the value of other fields.
You could do this:
$('input').onblur(function() {
if ($(this).is('[name=username]')) checkUsername()
// etc
})

Categories