Highlight words from multiple input fields simultaneously - javascript

I have a problem i'm working on, my program will highlight words if typed in an input field. It wont highlight words from both.(Example Input1 type "Test1", Input2 type "Test2") is there a way to keep the highlighted words active from one field when the user switches to another?
JSBIN: http://jsbin.com/xovisayaso/edit?html,css,js,output
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
<title>JS Bin</title>
</head>
<body>
<div id="listArray">
<span>Test1</span>
<span>Test2</span>
<span>Test3</span>
</div>
<input type="text" class="form-control" id="userArray">
<input type="text" class="form-control" id="userArray2">
</body>
</html>
<script
$("#userArray, #userArray2").on('change keyup paste', function() {
var input = $(this).val().toLowerCase().split(" ");
$('#listArray span').each(function(){
$(this).removeClass('active');
if( $.inArray( $(this).text().toLowerCase(), input ) != -1 ) {
$(this).addClass('active');}});});
</script>
<style>#list_input > div { border:4px solid; padding: 1em; margin: 1em auto; }
#listArray { overflow: auto; }
#listArray span { display: block; float: left; clear: left; padding:4px; margin:1px; }
#listArray span.active { background: green; }
}
</style>

You can achieve the desired effect by removing the active class whenever the text changes and then checking against both inputs:
$("#userArray, #userArray2").on('change keyup paste', function() {
$('#listArray span').removeClass('active');
$('input').each(function() {
var input = $(this).val().toLowerCase().split(" ");
$('#listArray span').each(function() {
if ($.inArray($(this).text().toLowerCase(), input) != -1) {
$(this).addClass('active');
}
});
});
});
#list_input > div {
border: 4px solid;
padding: 1em;
margin: 1em auto;
}
#listArray {
overflow: auto;
}
#listArray span {
display: block;
float: left;
clear: left;
padding: 4px;
margin: 1px;
}
#listArray span.active {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="listArray">
<span>Test1</span>
<span>Test2</span>
<span>Test3</span>
</div>
<input type="text" class="form-control" id="userArray">
<input type="text" class="form-control" id="userArray2">

Try this code :
$("#userArray, #userArray2").on('change keyup paste', function() {
var input = $("input").map(function(){return $(this).val().toLowerCase();}).get();
$('#listArray span').each(function(){
if( $.inArray( $(this).text().toLowerCase(), input ) != -1 ) {
$(this).addClass('active');
}
else
$(this).removeClass('active');
});
});
Reason : In your code you are only getting single value at a time to compare, rather the both textbox's values !!!

Related

Is there a way to remove the "chose a file" from an input file type?

I want to remove the "No file Chosen" from an input file and then rename the "choose" to another text.
"" $(document).ready(function() {
var readURL = function(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.avatar').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".file-upload").on('change', function(){
readURL(this);
});
});""
One way to do this, as I have on a couple of occasions, would be to hide the input element and use a label element which is bound to the hidden file field to receive the click events. You can style the label however you see fit within reason so that ought to give sufficient flexibility to accomplish what you want?!
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
body, body *{ font-family:cursive }
input[type='file']{
width: 0px;
height: 0px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
input[type='file'] + label{
font-weight: 700;
color: black;
background-color: #E5E4E2;
display: inline-block;
border:1px solid black;
padding:0.25rem;
width:50%;
cursor:pointer;
}
.input[type='file']:focus + label,
.input[type='file'] + label:hover {
background-color: red;
}
span{
color:red
}
</style>
</head>
<body>
<form>
<input type='file' name='photo' id='photo' />
<label for='photo'>
<span>Put your Text here</span>
</label>
</form>
<script>
/* you can still assign the listeners... */
document.getElementById('photo').onchange=function(e){
console.log(this.value)
}
</script>
</body>
</html>
a less verbose version of the above to show a minimal example
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style>
input[type='file']{
width: 0px;
height: 0px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
</style>
</head>
<body>
<form>
<input type='file' name='photo' id='photo' />
<label for='photo'>
<span>Put your Text here</span>
</label>
</form>
</body>
</html>

How to prevent removing "section" from <div contenteditable> when editing?

How to prevent a user from removing <section> inside <div contenteditable> editor during editing (at least by pressing "Delete"/"Backspace" keys)?
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
#editor {
width: 100%;
height: 300px;
border: 1px black solid;
}
#dont-remove-me-please{
width: 100%;
height: 100px;
border: 1px red dashed;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div contenteditable="true" id="editor">
<div>hey guys!</div>
<div><strong>more text...</strong></div>
<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
<div><br></div>
</div>
<script>
document.getElementById('editor').focus()
</script>
</body>
</html>
Thank You.
You can set contenteditable=false to children to prevent them from being editable.
However if you still want the children to be editable but the child dom elements shouldn't be removable I think you need to listen to backspace/delete events and see how these effect the dom and undo the changes if they remove dom nodes. Trying to figure this out myself
Edit: this is what I did
function onpaste(e: ClipboardEvent) {
e.preventDefault();
const selection = window.getSelection();
// Don't allow deleting nodes
if (selection.anchorNode.isSameNode(selection.focusNode)) {
// get text representation of clipboard
const text = e.clipboardData.getData("text/plain");
// insert text manually, but without new line characters as can't support <br/>s yet
document.execCommand("insertHTML", false, text.replace(/\n/g, ""));
}
}
function onkeydownInEditable(e: KeyboardEvent) {
if (e.key === "Enter") {
e.preventDefault();
}
if (e.key === "Backspace" || e.key === "Delete" || e.key === "Paste") {
const selection = window.getSelection();
// Don't allow deleting nodes
if (!selection.anchorNode.isSameNode(selection.focusNode))
e.preventDefault();
}
}
elementEditing.addEventListener("keydown", onkeydownInEditable);
elementEditing.addEventListener("paste", onpaste);
To achieve expected result, use below click event listener and add contenteditable attribute based on id
<script>
document.getElementById('editor').addEventListener('click', function(e) {
if(e.target.id !=="dont-remove-me-please"){
e.target.setAttribute("contentEditable", true);
}
}, false);
</script>
code sample - https://codesandbox.io/s/rypy7wkn5m
<html>
<head>
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
<style>
#editor {
width: 100%;
height: 300px;
border: 1px black solid;
}
#dont-remove-me-please{
width: 100%;
height: 100px;
border: 1px red dashed;
font-weight: bold;
user-select: none;
}
</style>
</head>
<body>
<div id="app"></div>
<div id="editor">
<div>hey guys!</div>
<div><strong>more text...</strong></div>
<section id="dont-remove-me-please" contenteditable="false">DONT' REMOVE ME!!!</section>
<div><br></div>
</div>
<script>
document.getElementById('editor').focus()
</script>
<script>
document.getElementById('editor').addEventListener('click', function(e) {
if(e.target.id !=="dont-remove-me-please"){
e.target.setAttribute("contentEditable", true);
}
}, false);
</script>
</body>
</html>

showing div after activating a function

I need help on how to show a div that I'm suppose to hide. The idea is that when the object is dragged to the droppable, it will trigger the quiz which is stored on the div "wrapper". I can hide the div but how do I show it when the dragItem_ts(); is done. Please help.
dragItem_ts();
dragItem2();
function dragItem_ts() {
$(function() {
$("#draggable_ts, #draggable-nonvalid").draggable();
$("#droppable").droppable({
accept: "#draggable_ts",
drop: function(event, ui) {
$(this)
.addClass("ui-state-highlight")
.find("p")
.html("Correct!")
.alert("I am an alert box!");
}
});
});
}
function dragItem2() {
$(function() {
$("#draggable2, #draggable-nonvalid").draggable();
$("#droppable2").droppable({
accept: "#draggable2",
drop: function(event, ui) {
$(this)
.addClass("ui-state-highlight")
.find("p")
.html("Correct!");
}
});
});
}
function tabulateAnswers() {
// initialize variables for each choice's score
// If you add more choices and outcomes, you must add another variable here.
var c1score = 0;
var c2score = 0;
var c3score = 0;
var c4score = 0;
// get a list of the radio inputs on the page
var choices = document.getElementsByTagName('input');
// loop through all the radio inputs
for (i = 0; i < choices.length; i++) {
// if the radio is checked..
if (choices[i].checked) {
// add 1 to that choice's score
if (choices[i].value == 'c1') {
c1score = c1score + 1;
}
if (choices[i].value == 'c2') {
c2score = c2score + 1;
}
if (choices[i].value == 'c3') {
c3score = c3score + 1;
}
if (choices[i].value == 'c4') {
c4score = c4score + 1;
}
// If you add more choices and outcomes, you must add another if statement below.
}
}
// Find out which choice got the highest score.
// If you add more choices and outcomes, you must add the variable here.
var maxscore = Math.max(c1score, c2score, c3score, c4score);
// Display answer corresponding to that choice
var answerbox = document.getElementById('answer');
if (c1score == maxscore) { // If user chooses the first choice the most, this outcome will be displayed.
answerbox.innerHTML = "You are correct"
}
if (c2score == maxscore) { // If user chooses the second choice the most, this outcome will be displayed.
answerbox.innerHTML = "The correct answer is stvsp#am.sony.com"
}
if (c3score == maxscore) { // If user chooses the third choice the most, this outcome will be displayed.
answerbox.innerHTML = "The correct answer is stvsp#am.sony.com"
}
if (c4score == maxscore) { // If user chooses the fourth choice the most, this outcome will be displayed.
answerbox.innerHTML = "The correct answer is stvsp#am.sony.com"
}
// If you add more choices, you must add another response below.
}
// program the reset button
function resetAnswer() {
var answerbox = document.getElementById('answer');
answerbox.innerHTML = "Your result will show up here!";
}
#droppable,
#droppable2 {
width: 150px;
height: 150px;
padding: 0.5em;
float: left;
margin: 10px;
}
#draggable_ts,
#draggable2,
#draggable-nonvalid {
width: 100px;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px 10px 10px 0;
}
body {
font-family: sans-serif;
background: green;
}
h2 {
margin: 5px 0;
}
#wrapper {
width: 600px;
margin: 0 auto;
background: white;
padding: 10px 15px;
border-radius: 10px;
}
input {
margin: 5px 10px;
}
button {
font-size: 18px;
padding: 10px;
margin: 20px 0;
color: white;
border: 0;
border-radius: 10px;
border-bottom: 3px solid #333;
}
#submit {
background: green;
}
#reset {
background: red;
}
#answer {
border: 1px dashed #ccc;
background: #eee;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Droppable - Accept</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src=javascript/functions.js>
</script>
</head>
<body>
<div id="draggable-nonvalid" class="ui-widget-content">
<p>I'm draggable but can't be dropped</p>
</div>
<div id="draggable_ts" class="ui-widget-content">
<img src="images/ts_image02.jpg">
</div>
<div id="draggable2" class="ui-widget-content">
<p>Drag me to my target</p>
</div>
<div id="droppable" class="ui-widget-header">
<p>accept: '#draggable'</p>
</div>
<div id="droppable2" class="ui-widget-header">
<p>accept: '#draggable2'</p>
</div>
<div id="droppable3" class="ui-widget-header">
<p>accept: '#draggable2'</p>
</div>
<div id="wrapper">
<h1>What is the email address that the customer should send them to?</h1>
<form id="quiz">
<!-- Question 1 -->
<!-- Here are the choices for the first question. Each input tag must have the same name. For this question, the name is q1. -->
<!-- The value is which answer the choice corresponds to. -->
<label><input type="radio" name="q1" value="c1">
stvsp#am
</label><br />
<label><input type="radio" name="q1" value="c2">
svtsp#am
</label><br />
<label><input type="radio" name="q1" value="c3">
mydocs#am
</label><br />
<label><input type="radio" name="q1" value="c4">
docs#am
</label><br />
<button type="submit" id="submit" onclick="tabulateAnswers()">Submit Your Answers</button>
<button type="reset" id="reset" onclick="resetAnswer()">Reset</button>
</form>
<div id="answer">Your result will show up here!</div>
</div>
</body>
</html>
in the css class of your div you need to set :
display : none;
when dragItem_ts(); is done. just call this function below :
var e = document.getElementsByClassName("your_div")[0];
e.style.display="block";

Javascript - post button not disabled - character count not working

This code is not giving me a disabled post button when I haven't inserted at least 1 character, and the character count is not functioning. I have checked index.html, to see that the js file is linked properly. I am using safari, have tried on chrome as well.
app.js file:
var main = function() {
$('.btn').click(function() {
var post = $('.status-box').val();
$('<li>').text(post).prependTo('.posts');
$('.status-box').val('');
$('.counter').text(140);
$('.btn').addClass('disabled');
});
$('.status-box').keyup(function() {
var postLength = $(this).val().length;
var charactersLeft = 140 - postLength;
$('.counter').text(charactersLeft);
if(charactersLeft < 0) {
$('.btn').addClass('disabled');
}
else if(charactersLeft === 140) {
$('.btn').addClass('disabled');
}
else {
$('.btn').removeClass('disabled');
}
});
$('.btn').addClass('disabled');
};
$(document).ready(main);
html.index file:
<!doctype html>
<html>
<head>
<link href="http://s3.amazonaws.com/codecademy- content/courses/ltp2/css/bootstrap.min.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form>
<div class="form-group">
<textarea class="form-control status-box" rows="2" placeholder="What's on your mind?"></textarea>
</div>
</form>
<div class="button-group pull-right">
<p class="counter">140</p>
Post
</div>
<ul class="posts">
</ul>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Css file:
html,
body {
font-family: 'Roboto', sans-serif;
color: #404040;
background-color: #eee;
}
.container {
width: 520px;
margin-top: 20px;
}
.button-group {
margin-bottom: 20px;
}
.counter {
display: inline;
margin-top: 0;
margin-bottom: 0;
margin-right: 10px;
}
.posts {
clear: both;
list-style: none;
padding-left: 0;
width: 100%;
}
.posts li {
background-color: #fff;
border: 1px solid #d8d8d8;
padding-top: 10px;
padding-left: 20px;
padding-right: 20px;
padding-bottom: 10px;
margin-bottom: 10px;
word-wrap: break-word;
min-height: 42px;
}
keyup is not a good event to use for this sort of thing. On modern browsers, input is best; on older browsers, you need a combination of things, primarily change, keypress and keyup (with a setTimeout delay, since the field isn't updated yet when they happen), and the non-standard paste..
For example (see comments):
var main = function() {
function enableDisableButtons(field) {
var postLength = field.val().length;
var charactersLeft = 140 - postLength;
$('.counter').text(charactersLeft);
// Note we can readily combine the two conditions and use toggleClass
var disabled = charactersLeft < 0 || charactersLeft === 140;
$('.btn').toggleClass('disabled', disabled);
return disabled;
}
$('.btn').click(function() {
// Proactively check when the button is clicked, in case all else failed
if (enableDisableButtons($('.status-box'))) {
return;
}
var post = $('.status-box').val();
$('<li>').text(post).prependTo('.posts');
$('.status-box').val('');
$('.counter').text(140);
$('.btn').addClass('disabled');
});
$('.status-box')
.on("input change paste", function() {
// Field is already updated when these happen
enableDisableButtons($(this));
})
.on("keypress keyup", function() {
// Field not be updated until just *after* these happen, so wait a tick
setTimeout(enableDisableButtons.bind(null, $(this)), 0);
});
$('.btn').addClass('disabled');
};
$(document).ready(main);
.disabled {
color: grey;
}
<textarea class="status-box"></textarea>
<input class="btn" type="button" value="Send">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Side note: Why use a disabled class rather than the button's intrinsic disabled feature?

Trouble Removing One Child DIV At A Time

I am building a simple Grocery List App and I am having issues trying to remove a place holder div element.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Grocery List App</title>
<link type="text/css" href="style/form.css" rel="stylesheet"/>
</head>
<body>
<div id="container">
<div id="left_side">
<div id="to_buy">To Buy:</div>
</div>
<div id="right_side">
<div id="in_cart">In Cart:</div>
</div>
</div>
<input type="text" id="item_body" placeholder="Type Item to Add">
<script src="scripts/jquery-1.11.2.min.js"></script>
<script src="scripts/grocery.js"></script>
<script src="scripts/jquery-ui/jquery-ui.js"></script>
</body>
</html>
JS
$(function () {
var rmv = false;
$('#item_body').keydown(function(e) {
if (e.keyCode == 13) {
var add = $('#item_body').val();
$("#to_buy").append('<div class="draggable_item">' + add + '</div>');
$("#in_cart").append('<div class="holder"></div>');
}
$(".draggable_item").draggable( {
axis: "x"
});
$(".draggable_item").dblclick(function() {
this.remove();
$('#in_cart > div:first').remove();
});
});
});
CSS
#to_buy {
float:left;
width: 50%;
height: 100%;
color: #00E5EE;
}
#in_cart {
float: left;
width: 49%;
height: 100%;
color: #00E5EE;
}
#container {
width:100%;
height: 100%;
}
#left_side {
height: 100%;
width: 50%;
float:left;
background: #5D5851;
}
#right_side {
height: 100%;
width: 50%;
float: left;
background: #6D5D4D;
}
#item_body {
float:left;
clear:both;
color: #326B62;
}
body {
background: #B1ADA5;
}
.draggable_item {
color: #FFF;
}
.holder {
height: 20px;
}
So the screen is split vertically between "to_buy" and "in_cart." When I add an item to "to_buy" I also add a "dummy" div to "in_cart" so that the two sides remain even. However, when I double click to remove an item, when
$('#in_cart > div:first').remove();
gets called, first one div is removed, then on the next double click two, then four etc etc. Apparently, it is getting called multiple times or something else wonky is going wrong.
This is because you bind event handlers for double click event on every Enter key press so they multiply on every item addition. Just move dblclick registration outside:
var rmv = false;
$('#item_body').keydown(function (e) {
if (e.keyCode == 13) {
var add = $('#item_body').val();
$("#to_buy").append('<div class="draggable_item">' + add + '</div>');
$("#in_cart").append('<div class="holder"></div>');
}
$(".draggable_item").draggable({
axis: "x"
});
});
$("#left_side").on("dblclick", ".draggable_item", function () {
this.remove();
$('#in_cart > div:first').remove();
});
Also note, that it makes sense to delegate double click event to the parent container #left_side so you don't have to worry about presence of elements at the time of event registration.
Here is a demo: http://jsfiddle.net/hx11gkcj/

Categories

Resources