I would like that when the user inserts information in a specific input text, another element becomes visible. My question looks study, but I'm new on JavaScript world, and I have tried searching on Google and here but I wasn't able to find anything.
Check out my code:
.hide {
display: none;
}
<div>
<label>Password:</label>
<input type="password" id="pwInput">
Show password
</div>
What I want is that the "Show password" anchor only shows when the password input has content inside.
Super simple option... use the input event handler on the <input> to toggle a class on it. You can then use an adjacent-sibling selector in your CSS to show or hide the <a>.
.hide {
display: none;
}
.has-input + .hide {
display: inline;
}
<div>
<label>Password:</label>
<input type="password" id="pwInput"
oninput="this.classList.toggle('has-input', this.value.trim())">
Show password
</div>
If you're not a fan of inline event handlers, this is the unobtrusive equivalent
document.getElementById('pwInput').addEventListener('input', function(e) {
this.classList.toggle('has-input', this.value.trim())
}, false)
Note, the force option on classList.toggle() doesn't work in IE. If you need to support it, try something like
this.classList[this.value.trim() ? 'add' : 'remove']('has-input')
Just do this in JavaScript:
document.addEventListener("keydown", function() {
if (document.getElementById("pwInput").value != "") {
document.querySelector(".hide").style.display = "inline";
}
else {
document.querySelector(".hide").style.display = "none";
}
});
.hide {
display: none;
}
<div>
<label>Password:</label>
<input type="password" id="pwInput">
Show password
</div>
This will check every keydown if the input has any content, plus it'll work both ways e.g. if the user deletes the password then the anchor will go away.
Related
I've been trying to find a way to fully prevent text input text selection (Chrome, v. 104)
#testInput {
user-select: none;
pointer-events: none;
width: 100%;
}
<!DOCTYPE HTML>
<html>
<label for="testInput">Input label</label>
<input id="testInput" type="text" value="Test value">
</html>
It is still possible to select text inside the input. Either through selecting the end of the label text and dragging mouse through the input, control + a and other ways. user-select also seems to have no effect on input element, the only reason copying directly is impossible is due to the pointer-events: none css setting.
https://jsfiddle.net/a69bswmq/
Although it's possible for someone to look at the source code and copy the text, here are some JS hacks that will make the copying a little bit harder and prevent non-developers to copy the text:
document.getElementById('testInput')
.addEventListener('selectionchange ', function (e) {
window.getSelection().empty();
window.getSelection().removeAllRanges();
});
// Detect Ctrl/Cmd+C and temporarily switch the value
document.addEventListener("keydown", e =>{
const input = document.getElementById('testInput');
const oldVal = input.value;
if ( (e.ctrlKey || e.metaKey ) && ( e.key === "c" || e.code === "KeyC") ){
input.value = "DON'T COPY";
setTimeout(()=>{
input.value = oldVal;
}, 1000)
}
})
// Disable Right-Click and Copy
document.addEventListener("contextmenu", e =>{
const selection = window.getSelection();
if ( selection && ( selection.type === 'Range' ) ){
e.preventDefault();
}
})
#testInput {
user-select: none;
pointer-events: none;
width: 100%;
}
<label for="testInput">Input label</label>
<input id="testInput" type="text" value="Test value">
This is just a simple example to get you started. We can track other events also (drag, selection, mousedown, etc.) and make this even harder for someone to copy the text ...unless they open the DevTools and take a peek at the input value. ¯_(ツ)_/¯
Another approach would be to super-impose another element on top of the input element so that when the user tried to copy the text, they would be interacting with another element instead of the input element containing the value.
Just use the "disabled" attribute.
<input id="testInput" type="text" value="Test value" disabled>
I have a textarea for the user to type something and it has a cancel and a submit button as part of it.
How can I make it so that the cancel and submit button only appears when the user clicks inside the textarea? (using javascript, no jquery please)
I have attempted using this javascript function:
function setButtons(writingtext) {
if (writingtext) {
document.getElementById('cfm').style.display = 'block';
document.getElementById('cancel').style.display = 'block';
}
else {
document.getElementById('cfm').style.display = 'none';
document.getElementById('cancel').style.display = 'none';
}
}
When the user clicks the text area, it would be onClick="setButtons(True)" -> displays the buttons.
I'm not sure if this is the right approach here. Sorry, really new to this.
Any help would be appreciated!
You have control over your html you can do it with just css sniping the next sibling at :focus like this:
div {display:none;}
textarea:focus + div {display:block;}
<textarea name="" id="" cols="30" rows="10"></textarea>
<div>
<input type="submit">
<input type="submit">
</div>
This is only a simple example to show the buttons on focus. If you want to hide them, I think you will be able to manage that solution.
If all you want to do is show the buttons when the text area is focused, use the CSS-only solution. However, I'm guessing you'll want to keep them for a bit or do some extra pre-processing before the submit, in which case you should use the javascript option.
document.querySelector("#textarea").addEventListener("focus", function() {
document.querySelector("#submit").style.display = "block";
document.querySelector("#cancel").style.display = "block";
});
button {
display: none;
}
<textarea id="textarea"></textarea>
<button id="submit">Submit</button>
<button id="cancel">Cancel</button>
You can just assign an id to the textarea for example text and then use
document.getElementById('text').addEventListener('focus', function(){
document.getElementById('cfm').style.display = 'block'
document.getElementById('cancel').style.display = 'block'
})
// Hide when blur (when not focused)
document.getElementById('text').addEventListener('blur', function(){
document.getElementById('cfm').style.display = 'none'
document.getElementById('cancel').style.display = 'none'
})
You should use
onfocus="setButtons(this)" instead of onClick
function setButtons(writingtext) {
document.getElementById('cfm').style.display = 'block';
document.getElementById('cancel').style.display = 'block';
}
I am using Jquery validation and a Tag-it plugin that generates UL LIs on the fly for each new tag to be added. If there are no tags, the plugin has only one LI and it is empty. If you create at least one tag, then the plugin creates a second LI. I am using submitHandler and invalidHandler to validate only if there is more than 1 LI, which means there is at least one tag. This works. Here is my fiddle: http://jsfiddle.net/Z3HDh/95/
I need help with two additional things:
When the form fails to validate because no tags have been entered, it writes to the console - "you don't have any tags". It also displays a message, "Add some tags, puhleeeease!" I want it to add the error styling to the background and border of the ul class="tagit ui-widget ui-widget-content ui-corner-all". I have unsuccessfully tried using jquery validation's highlight and addrules functions.
If the field fails to validate (there is no tag, the "Add some tags, puhleeeease!" message appears), and then I put in a tag (which means the field now validates), it will only register the validation and remove the error message if I click submit again. On other fields, the plugin itself validates on the fly and adjusts the styling. So, in this case, as soon as I add the tag, I would like the field to validate successfully and remove the error styling and message, rather than waiting until I re-submit it. I have seen a number of examples of this but also have failed to implement it.
HTML:
<div class="form-group">
<label for="id_title">Add your title here (required)</label>
<input type="text" id="id_title" name="title" maxlength="75" value=""
required data-msg="Please add a title.">
</div><!-- end form-group -->
<div class="form-group">
<label for="id_material">Your tags go here... (required)</label>
<input type="text" id="id_material" name="material" value=""
required data-msg="Add some tags, puhleeeease!">
</div>
<div class="form-group-buttons">
<p class="form_buttons">
Cancel
<button type="submit">Submit</button>
</p>
</div><!-- end form-group-buttons -->
</form>
JS:
$("#id_material").tagit();
$("#add_idea_form").validate({
ignore: "input[name='tags']:hidden",
submitHandler: function (form) {
},
invalidHandler: function(event, validator) {
if($('#id_material + ul').length < 2){
console.log("You don't have any tags");
// return false;
}
}
});
$("li.email > input").rules("add", {
required: true,
email: true
});
CSS:
input.error, td.field input.error, td.field select.error, tr.errorRow td.field, input, tr.errorRow td.field select {
/*background-color: #ffffd5;*/
border:2px solid #d17877;
background: #F2DEDE;
box-shadow: none;
}
#add_idea_form label.error{
color: red;
}
You need to add a delete rule when a tag is entered. The example below will remove the "Add tags please" when a tag is added (after the error was run).
$("#id_material").tagit({
afterTagAdded: function(event, ui) {
$("#id_material-error").remove();
$(".ui-corner-all").removeClass('error');
console.log(ui.tag);
}
});
To add CSS around the tag area, add the following code to your invalid Handler
invalidHandler: function(event, validator) {
if($('#id_material + ul').length < 2){
console.log("You don't have any tags");
$('.ui-corner-all').addClass('error');
}
}
});
It will add a red outline inside the tag input box. If you have multiple tag input boxes, the code may need to be updated to target a specific input.
You'll also need to add the following to your css file
.error{
border:2px solid #d17877;
background: #F2DEDE;
box-shadow: none;
}
.ui-corner-all.error{
background:red;
}
Working example at http://jsfiddle.net/v0jdpkz8/8/
I'd like to enter the word,PASSWORD and for the content inside HIDDENDIV to display.
Can someone show me where I'm going wrong?
#HIDDENDIV {
display: none;
}
<input type="text" id="password" onkeydown="if (event.keyCode == 13) document.getElementById('button').click()" />
<br/>
<input id="button" type="button" value="Login" onclick="if (document.getElementById('password').value == 'PASSWORD') {
document.getElementById('table').classList.toggle('show'); document.getElementById('passw').style.display='none'; }
else { alert('Invalid Password!'); password.setSelectionRange(0, password.value.length); } " />
<div id="HIDDENDIV">bla</div>
Because you hid the content via an id based CSS selector, adding a "show" CSS class to it later won't override the id rule that you already set. (Read this on how different CSS selectors are more specific than others and thus, more difficult to override.)
Here's a quick example:
#d1 { display:none; } /* Will override most other selectors */
div { display:block; } /* Won't work */
.show { display:block; } /* Won't work */
<p>You aren't going to see the div below this paragraph even though it matches two selectors that indicate that it should be shown and even though those two selectors come after the one that hides it. This is because the way it's being hidden is with an id based selector and tag type and class selectors alone are less specific than an id selector and won't override it.</p>
<div id="d1" class="show">Hello?!</div>
So, first, set the content to be hidden with a CSS class instead of an id based selector, then later, you can just remove that class - no extra "show" class is needed.
Next, in your code you have a div with an id of HIDDENDIV, but your code attempts to get and show an element with an id of table. I'm assuming that this was just a typo when posting this question and that, in reality, you really to have a table to show, but you need to correct that.
Also, you should not be using HTML inline event attributes. This was the way we did event handling 20+ years ago before we had standards and unfortunately, is a technique that is so pervasive that it just won't die the death it deserves. There are a variety of reasons not to use them. Instead, use modern standards and best-practices and do all of your event handling in separated JavaScript.
You also need to add an additional line just before you attempt to select all the text in the password field to give that element the focus, otherwise the select code won't work (see code below for this).
// Get references to the elements you'll be working with
var input = document.getElementById("password");
var div = document.getElementById("HIDDENDIV");
var btn = document.getElementById("button");
// Set up event handlers in JavaScript
button.addEventListener("click", validate);
function validate(){
if (input.value == 'PASSWORD') {
// No need to add a "show" class. Just remove the "hidden" class.
div.classList.remove('hidden');
// Or, add it:
input.classList.add("hidden");
} else {
password.focus(); // <-- If you don't do this first, your select code won't work
password.setSelectionRange(0, password.value.length);
alert('Invalid Password!');
}
}
input.addEventListener("keydown", function(event){
if (event.keyCode === 13){
// No reason to simulate a button click. Just call the code that needs to be run.
validate();
}
});
/* You only need to apply this to elements that should be hidden and
then simply remove this class from hidden elements to show them. */
.hidden { display: none; }
<input type="text" id="password">
<br>
<input id="button" type="button" value="Login">
<div id="HIDDENDIV" class="hidden">bla</div>
NOTES:
Keep in mind that although this code can "work", anyone can defeat
this code quite easily simply by looking at your source code. To
truly protect content from being consumed without the correct
credentials being provided, you need to implement a server-side
solution.
Just like inline scripting should no longer be done, the same can be
said for using XHTML self-terminating tag syntax (i.e. <br />,
<input />). That is also an old syntax that just won't go away.
Here's why you don't need and shouldn't use this syntax.
I modified and cleaned your code to get to this working snippet:
(See my comments in the code)
// Scripts belongs in tag scripts or in separate files, inline scripts shouldn't be that long.
function verify() { // I created the function, which is called onclick on the button
if (document.getElementById('password').value === 'PASSWORD') {
document.getElementById('HIDDENDIV').classList.remove("hidden"); // Using class instead of inline CSS
document.getElementById('credentials').classList.add("hidden"); // Hide the div containing the credentials
} else {
alert('Invalid Password!');
password.setSelectionRange(0, password.value.length);
}
return false;
}
.hidden { /* Changed id selector to a class */
display: none;
}
<div id="credentials">
<!-- Added the parent div to be able to hide both the password, the button and even the <br> tag easily -->
<input type="text" id="password" onkeydown="if (event.keyCode == 13) verify()" />
<br/>
<input id="button" type="button" value="Login" onclick="verify()" />
</div>
<div id="HIDDENDIV" class="hidden">bla</div><!-- Added class -->
Note that this is NOT a way to secure anything.
Just open the code viewer on any browser and you will see the “hidden” div.
changed
document.getElementById('table').classList.toggle('show')
to
document.getElementById('HIDDENDIV').style.display = 'block';
Seems like you have a lot of uneccesary code though
<input type="text" id="password" onkeydown="if (event.keyCode == 13) document.getElementById('button').click()" />
<br/>
<input id="button" type="button" value="Login" onclick="if (document.getElementById('password').value == 'PASSWORD') {
document.getElementById('HIDDENDIV').style.display = 'block'; document.getElementById('passw').style.display='none'; }
else { alert('Invalid Password!'); password.setSelectionRange(0, password.value.length); } " />
<div id="HIDDENDIV">bla</div>
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