How to show/hide a div with javascript - javascript

I'm currently making a registration page for a site and need to show a typical password confirmation message. How would I make a script to hide and show a div?
This is as far as I've got:
<html><head>
<script language="javascript">
function correctpassword()
var password="password"
var confirmpassword="confirmpassword"
if (password1 != password2)
{
showcss="unconfirmed"
}
else
{
showcss="confirmed"
}
</script>
</head>
<body>
<form>
<u>Personal Details</u>
First Name: <input type="text" id="firstname">
Last Name: <input type="text" id="lastname">
Date of Birth:
Gender: Male Female
<u>Login Details</u>
Email Adress:<input type="text" id="email">
Username:<input type="text" id="username">
<!--check avalibility-->
Password:<input type="text" id="password">
Confirm Password:<input type="text" id="confirmpassword">
<!--Javascript if "password" doesnt equal "confirm password" showcss passwords don't match-->
<button type="button" onclick="correctpassword()">Display Date</button>
</form>
</body>
</html>
PS:The variables may be wrong.

Assuming you are talking about hiding / showing a div, spanor other similar element in HTML, you can use the jQuery JavaScript framework. For example:
$('#element_to_show').show();
$('#element_to_hide').hide();
You can trigger the hide / show via events, e.g. key press or user leaving the input element, in jQuery as well.

Control your styles and appearance with className property that applied to class markup attribute.
Try to avoid .style property of the elements and add/remove some classes instead. It will give you more control and simplify maintenance in the future.
in css:
.show{
display:block;
}
.box{
display:none;
}
in html:
<div id="passConfirm"></div>
<div id="box"></div>
in your script:
var confirmEl,
confirmBox;
confirmEl = document.getElementById('passConfirm');
confirmBox = document.getElementById('box');
confirmEl.addEventListener('click', showBox, false);
function showBox () {
confirmBox.className += ' show';
}
As mentioned, you can use some libraries that helps to work with DOM or write your own functions helping to add and remove some classes, check for hasClass method etc.

I'm on my phone, hence the short answer.
Easiest way is to get the id of the element like document.getElementById and place that into a variable.
Then use the style property like
Obj.style.display = "none";
To hide it.

Related

Why doesn't empty() work on input in search bar?

When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.
Am I targeting the element incorrectly?
$("#inviteButton").click(function(){
var userName = $("#searchUser").val();
if (userName.trim() != "") {
if (userName == myUserName) {
$("#connectToBox").append("You can't invite yourself");
$("#searchUser").empty(); // Doesn't work
} else {
socket.emit("checkUserConnect", userName, function(data){
if (data.result === undefined) {
console.log("No name");
$("#connectToBox").append("User does not exist");
$("#searchUser").empty(); // Doesn't work
} else {
console.log("name exists");
$("#searchUser").empty(); // Doesn't work
$("#connectToBox").append("Invite send");
UserID = data.result.id;
socket.emit("connectToUser", myUserName, UserID, currentConversation);
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="connectToBox">
<label for="search-2">Type in username</label>
<input type="search" name="search-2" id="searchUser" value="">
Connect
</div>
To empty an input field you would normally use:
$('#searchUser').val('')
Empty is used to clear away child nodes from elements like divs or p tags, but not for inputs.
Reason for that is that the text within an input is not represented as a child node of the element and instead stored on an html attribute of the input tag. Hence .empty() does not work for clearing the value.
You can clear the input field by using
$('#searchUser').val('');
$('#searchUser').val('');
This will work fine according to your application.
The empty() method removes all child nodes and content from the selected elements. Src: W3Schools
According to your requirement you need to reset the value of an input field, for that we have val() function. You can assign an empty string and it will work fine.
Using empty() won't work here.
Check these examples -
empty() working correctly -
function emptyOperation(){
$("div").empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
empty() as per your code [won't work] -
function emptyOperation(){
$("#input-field").empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
Solution to your problem -
function emptyOperation(){
$("#input-field").val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>

jquery placeholder text for input form

I'm using jquery placeholder text for a search placeholder. This search field doesn't have any placeholder so i added this text.
$(document).ready(function(){
$('.mfilter-search').find("input[type=text]").each(function(ev)
{
if(!$(this).val()) {
$(this).attr("placeholder", "Refine Your Search");
}
});
});
i don't know it's the best way to add a placeholder using jquery. If anyone know more simple way please add your code it will be very helpful.
You can directly set the placeholder no need to check value and use .each()
$('.mfilter-search input[type=text]').attr("placeholder", "Refine Your Search")
If you want to place on first then use
$('.mfilter-search input[type=text]:first').attr("placeholder", "Refine Your Search")
You can simply use find method using value attribute
$('.mfilter-search').find("input[type=text][!value]").attr("placeholder", "Refine Your Search");
you can add placeholder attribute directly in your html element like this
<input type="text" name="fname" placeholder="search">
or you can add a class to all your element that you need to put placeholder eg:- .placeholder and add placeholder attribute in javascript like this.
$(".placeholder").attr("placeholder", "Type here to search");
or you can use plugins like these.
http://andrewrjones.github.io/jquery-placeholder-plugin/ or
https://github.com/mathiasbynens/jquery-placeholder or refer this site for different placeholder plugins.
https://www.sitepoint.com/top-5-jquery-html5-placeholder-plugins/
and your code is also good. We can do that way too.
hope this will work.
Try this code
$(document).ready(function(){
$('.mfilter-search').find("input[type=text]").each(function(ev)
{
var txt = $(this).data('placeholder');
$(this).attr('placeholder', txt);
});
});
For place holder no need complex method function in jquery simply use like this
<input type="text" placeholder = "Zipcode" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Zipcode'" name="zipcode" class="form-control" maxlength='10'>
try this. this is how you can add place holder if you have two input fields with same class name.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
first name :<input type="text" name="firstname" class="tfield" id="field0">
last name :<input type="text" name="lastname" class="tfield" id="field1">
</body>
<script type="text/javascript">
$(document).ready(function(){
var thelength = $(".tfield").length;
for(var i=0;i<thelength;i++)
{
var theid = $("#field"+i);
var thename = theid.attr("name");
alert(thename);
if(thename == "firstname")
{
theid.attr("placeholder","name");
}
}
});
</script>
</html>

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

How to only show a div if a certain entry field is filled in (but not submitted)?

Relatively new to html coding, and very new with javascript. On this page, I don't want the option to email an editor to become visible until a tripID is filled in (but form not submitted yet). Here is the form so far without that option added yet:
TripID:
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' /><br><br>
Port:
<input type='text' id='aport' name='aport' size='6' maxlength='6' /><br><br>
<div id=acheckbox><br> E-mail editor? </b>
<input type='checkbox' name='acheck' onchange='copyTextValue(this);'/><br>
<div id='div' style='display:none'>
<br> <b>Subject:</b> <input type='text' id='asubject' name='asubject' size='70' maxlength='75'/><br><br>
<textarea name='aemailbody' cols='85' rows = '10'>Explain any packaging or labeling mistakes here...</textarea>
</div>
</div>
<script>
function copyTextValue(bf) {
if(bf.checked){
document.getElementById('div').style.display = 'block';
var atext = 'Frozen Sample Error Notice: '+ document.getElementById('atripid').value;
}else{
document.getElementById('div').style.display = 'none';
var atext = '';
}
document.getElementById('asubject').value = atext
}
</script>
</div>
Now to hide the email editor option until tripid is filled in, I got something like this to work on jfiddle:
<form action="">
tripid:<input type="atripid" id="atripid" value="">
port:<input type="aport" id="aport" value="">
</form>
<div id="acheckbox" style="display:none">
<br><br><br>
This is where the email options (subject and textbox) would appear.
</div>
<script>
$("#atripid").keyup(function(){
if($(this).val()) {
$("#acheckbox").show();
} else {
$("#acheckbox").hide();
}
});
</script>
But for some weird reason, it won't work anywhere else, so I can't figure out how to incorporate it into what I already have. Does anyone have any ideas that could help me? Thanks!
You can do something like this with pure javascript:
<input type="atripid" id="atripid" value="" onkeyup="keyupFunction()">
And define your keyupFunction().
See jsfiddle
The code you attempted on jsfiddle requires that you import jquery.js files. An alternate way of doung what you intend to do is
<input type='text' id='atripid' name='atripid' size='6' maxlength='6' onkeyup="toggleCheckBox(this)" />
<input type='checkbox' name='acheck' id="acheckbox" style="display:none;" onchange='copyTextValue(this);'/>
with js
function toggleCheckBox(element) {
if(element.value=='') {
document.getElementById('acheckbox').style.display = 'none';
}
else {
document.getElementById('acheckbox').style.display = 'block';
}
}
The issue is the .keyup() method, which is not consistent across browsers and does not account for other means of user input. You would rather, use an Immediately Invoked Function Expression (IIFE) that will detect the propertychange of the input field in question and then to fire the desired event if the condition is met. But for the purposes of simplicity, and the fact that I'm not as well versed enough in IIFE syntax, simply bind some events to the input field, like so:
$("#atripid").on("keyup change propertychange input paste", (function(e) {
if ($(this).val() === "") {
$("#acheckbox").hide();
} else {
$("#acheckbox").show();
}
}));
#acheckbox {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form action="">
tripid:
<input type="atripid" id="atripid" value="">port:
<input type="aport" id="aport" value="">
</form>
<div id="acheckbox">
<br>
<br>
<br>This is where the email options (subject and textbox) would appear.
</div>

How to get span element with no id which is inside a div with no id

I have 2 span elements inside 2 div elements. Both span elements have no id and both div elements also have no id.
The 1st div has the 1st input element with an id (id_name) and then have the 1st span element after it.
The 2nd div has the 2nd input element with an id (id_password) and then have the 2nd span element after it.
I have a javascript function which I call on submit of form. Inside that function I can get the 1st input element in a variable element_id_name and the 2nd input element in a variable element_id_password. Now how can I get the 1st span element which comes after 1st input element? And how can I get the 2nd span element which comes after 2nd input element? Since I dont have id for span elements, I cannot use document.getElementById(). Is there a way to get 1st span element by reference to 1st input element?
This is my code:
<html>
<head>
<meta charset="ISO-8859-1">
<title>test</title>
<style type="text/css">
.error_noshow{
display: none;
}
.error_show{
color: red;
}
</style>
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
return false;
}
</script>
</head>
<body>
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
Thank you for reading my question.
var spans = document.getElementsByTagName('span');
span[0] is the first span, span[1] is the second span. However it's not the preferred way to do this. Use jQuery to make it easier or add an id or classname
To access next span element you can use nextElementSibling property.
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
var firstSpan=element_id_name.nextElementSibling;
return false;
}
</script>
But keep in mind that nextElementSibling not working in all version of browsers so you can simulate this using nextSibling http://www.w3schools.com/dom/prop_node_nextsibling.asp;
You can use querySelector to find the elements by their attributes.
function validate() {
var element_id_name = document.querySelector("[name=txt_user_name]");
var element_id_password = document.querySelector("[name=txt_password]");
console.log(element_id_name, element_id_password);
return false;
}
.error_noshow{
display: none;
}
.error_show{
color: red;
}
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
I'm not answering the question because someone already did, but it seems like you want to check if the user typed something in both field, you could skip the javascript and use the HTML5 tag "required" like so
<input type="text" require />.
The user will have an error message if he tries to submit. But keep in mind that old version of IE will skip this check.

Categories