I am building a section on my website for language learning. The user will see the word でんき (Japanese word). When someone enters in the correct text that matches each symbol, one of them will light up. How could I achieve this?
Here is a preview image of my site: http://imageshack.us/photo/my-images/827/hiraganaquiz2.jpg/
Here's an example with a normal input field:
<script type="text/javascript">
var answer = 'foo';
function checkMatch(val) {
if (val == answer) {
alert('CORRECT!');
}
}
</script>
<input type="text" id="word_box" value="" onkeyup="checkMatch(this.value)" />
This is incredibly simplified, but you get the idea. onkeyup will be called whenever a key is pressed in a box or other editable field.
Here's another one to add to the mix. Short answer is use Javascript, HTML, and CSS to accomplish this.
http://jsfiddle.net/BUxvx/1/
HTML
<span data-answer="cat" data-for="1">Symbol 1</span>
<span data-answer="dog" data-for="2">Symbol 2</span>
<span data-answer="chicken" data-for="3">Symbol 3</span>
<br />
<input type="text" data-for="1" />
<input type="text" data-for="2" />
<input type="text" data-for="3" />
< - Type answers here
<br />
<span>cat</span>
<span>dog</span>
<span>chicken</span>
JavaScript
$('input').keyup(function(){
$txt = $(this);
$span = $('span[data-for="' + $txt.attr('data-for') + '"]');
if($(this).val() === $span.attr('data-answer')){
$span.addClass('highlight');
}else{
$span.removeClass('highlight');
}
});
CSS
span{
display:inline-block;
height:75px;
width:75px;
line-height:75px;
text-align:center;
border:1px solid black;
}
input{
width:75px;
border:1px solid black;
}
.highlight{
background-color:yellow;
}
HTML
<div class="question">
<span data-answer="correctAnswerOne">で</span>
<span data-answer="correctAnswerTwo">ん</span>
<span data-answer="correctAnswerThree">き</span>
<div>
<label for="answer">Enter your Answer</label>
<input id="answer" />
Javascript
//Build an array of correct answers
var answerArray = "";
var i = 0;
$('.question span').each( function() {
answerArray[i] = this.attr('data-answer');
i++;
} );
//On key up, get user input
$('input').keyup(function(){
$('.question span').removeClass('highlight');
var userInput = $('#inputElementID');
var userInputArray = string.split(' ');//Split the string into an array based on spaces (I assume you are looking for three separate words
var answerCount = array.length;
for (i=0;answerCount >= i;i=i+1) {
if (userInputArray[i] == answerArray[i]) {
$('span[data-answer=' + answerArray[i] + ']').addClass('highlight');
}
}
});
CSS
.highlight{
background-color:yellow;
}
Here's a simple way:
<span data-value="Car">{character that means Car}</span>
<span data-value="Boat">{character that means Boat}</span>
<span data-value="Plane">{character that means Plane}</span>
<input>
$('input').keyup(function(){
var val = $(this).val();
$('[data-value]').removeClass('highlight');
$('[data-value="'+val+'"]').addClass('highlight');
});
Explanation:
The data-value will hold the English text of your character. When the user types a value that matches it, it will add the highlight class to all elements that have a data-value matching the text. Just apply your "lighting up" styles to the class.
Demo: http://jsfiddle.net/MTVtM/
To work with multiple words just split the value by a space and check each piece:
$('input').keyup(function(){
var val = $(this).val();
$('[data-value]').removeClass('highlight');
val.split(' ').forEach(function(v) {
$('[data-value="'+v+'"]').addClass('highlight');
});
});
Demo: http://jsfiddle.net/MTVtM/1/ (Try entering "Car Boat")
Related
I'm practicing JavaScript with the jQuery library.
What I want is to create something like a POS Application, but there are things I just can't figure out.
I'd like to, if you enter lays, and then you enter lays again, the output should change to the already appended output to lays * 2.
I'm kind of lost on how to achieve the desired.
What I have so far:
var billoutput = document.getElementById('inputterminal');
var counter = 1;
$('#bill').click(function() {
$("#holder").append(" <span style='padding:10px; margin:5px; color:white; background-color:black; border-radius: 10px;'> " + billoutput.value + " </span> ");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>POS Terminal</h1>
<input id="inputterminal" value="" name="" type="text">
<button id="bill">bill</button> <br>
<div style="margin-top: 20px;" id="holder"></div>
You can store the inputs in an array and check whether the array includes the value of the input every time the user clicks the button. If it does not, append the element and push the input's value to the array.
var billoutput = document.getElementById('inputterminal');
var counter = 1;
var words = []
$('#bill').click(function() {
if (!words.includes(billoutput.value)) {
words.push(billoutput.value)
$("#holder").append(" <span style='padding:10px; margin:5px; color:white; background-color:black; border-radius: 10px;'> " + billoutput.value + " </span> ");
}else{
alert("you already entered that!")
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>POS Terminal</h1>
<input id="inputterminal" value="" name="" type="text">
<button id="bill">bill</button> <br>
<div style="margin-top: 20px;" id="holder"></div>
I have the following problem:
I would like to change the value of an input field, which is next to an another element, which will be clicked.
HTML:
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
JS:
$(document).on('click', ".plus", function (event) {
let currentTarget = event.currentTarget;
let idOfClickedElement = $(currentTarget).attr('id');
let currentQuantity = Number($('.quantity' + idOfClickedElement).val());
$(this).parent().find(".quantity" + idOfClickedElement).val(currentQuantity + 1)
});
There are other input fields which are the same like in the example. Those value changes also, but I want only one.
As each input with +/- is inside a div wrapper, you can use
$(this).closest("div").find(".quantityNum--input")
to get the related input.
There's no need for the numeric IDs when using relative DOM traversal.
Combining the + and - into a single event gives:
$(document).on('click', ".minus,.plus", function() {
var delta = $(this).is(".plus") ? 1 : -1;
$(this).closest("div").find(".quantityNum--input").val((i, val) => {
console.log(val);
return (val * 1) + delta;
});
});
.minus,
.plus {
cursor: pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="100">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
<div>
<a class="minus">[-]<i class="icon-minus-wide"></i></a>
<input class="quantityNum--input" name="sQuantity" type="text" value="500">
<a class="plus">[+]<i class="icon-plus-wide"></i></a>
</div>
I thik you are looking for .next and .prev.
note: I like sharing information usingdata-attributes so I've used that. you can use anything else id/class to differentiate. that's upto you
Just created a demo script for you
$('.number-action-button').on('click', function(){
const direction = $(this).data('direction');
if(direction === 'decrement'){
const $input = $(this).next('input[type="number"]');
$input.val($input.val() - 1);
}
if(direction === 'increment'){
const $input = $(this).prev('input[type="number"]');
$input.val(parseInt($input.val()) + 1);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="number-action-button" data-direction="decrement">-</button>
<input type="number" value="0" />
<button class="number-action-button" data-direction="increment" >+</button>
simple solution: bundle the 3 elemts into 1 container, so your parent selector can easily catch the input, the way you already do it.
<div>
<a id="{$sArticle.articleID}" class="minus"><i class="icon-minus-wide"></i></a>
<input class="quantityNum--input quantity{$sArticle.articleID}" name="sQuantity"
type="text" value="{$sArticle.minpurchase}">
<a id="{$sArticle.articleID}" class="plus"><i class="icon-plus-wide"></i></a>
</div>
if you cant(or dont want) change the html use $(this).next() (or $(this).prev() for the plus button) in order to fint the input.
btw: maybe you'll try that funktion (havn't tested it, but at least it should give you an idea how to)
$(document).on('click', ".plus,.minus", function (event) {
let input_quantity=false;
if($(this).hasClass('plus'){
input_quantity=$(this).prev();
input_quantity.val(parseInt(input_quantity.val())+1);
}else{
input_quantity=$(this).next();
input_quantity.val(parseInt(input_quantity.val())-1);
}
});
I have created a QR code generator. The user can create multiple QR codes.
I would like the user to be able to name each QR code (referred to as a checkpoint) by writing the desired checkpoint name in the text input field, clicking the Assign Name button and having the text input field disappear, being replaced by the name the user typed into the field.
The user can input checkpoint names, however, it only works for the first QR code printed, and the label only appears below the QR code. Below is the code that I have so far. Any help or suggestions to help me get the ball rolling on this would be very much appreciated. Thank you!
Note: If you try to run this to see the QR codes, you will have to enter something in the text field and press generate. They won't appear automatically.
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: arial, sans-serif;
}
section {
margin: 50px auto;
max-width: 350px;
text-align: center;
}
textarea {
width: 50%;
height: 50px;
margin-bottom: 10px;
}
#size {
max-width: 64px;
}
label {
display: inline-block;
width: 140px;
text-align: left;
}
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<section>
<h1>QR Code Generator</h1>
<p>Enter a URL or some text bellow and hit the Generate button (<kbd>Ctrl</kbd>+<kbd>Enter</kbd>)!</p>
<textarea id="textarea" autofocus></textarea>
<div class="block">
<label for="size">Size (px):</label>
<input align="left" id="size" type="number" value="150" min="50" max="500" step="50">
<label for="amount">Amount of Labels:</label>
<input align="left" id="amount" type="number" value="1" min="1" max="500" step="1">
<button id="genQRcode">Generate</button>
</div>
<div id="content" style="display: none;"></div>
</section>
<p id="demo" align="center"></p>
<script>
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
</script>
<script id="template-qr-code" type="text/html">
<p> <img id="qrcode" src="{{src}}" /></p>
<label for="checkpoint"> Checkpoint Name:</label>
<input id="cpname" type="text" value="">
<button onclick="myFunction()">Assign Name</button>
</script>
<script type="text/javascript">
window.addEventListener('load', function() {
var textarea = document.getElementById("textarea"),
content = document.getElementById("content"),
amount = document.getElementById("amount"),
qrTemplate = document.getElementById('template-qr-code');
function genQRcode() {
var data = encodeURIComponent(textarea.value),
size = document.getElementById("size").value,
chart = "http://chart.googleapis.com/chart?cht=qr&chs=" + size + "x" + size + "&choe=UTF-8&chld=L|0&chl=" + data;
if (data === "") {
alert("Please enter valid data!");
textarea.focus();
content.style.display = "none";
} else {
for (var i = 0; i < amount.value; i++) {
var qrSrc = qrTemplate.innerHTML;
qrSrc = qrSrc.replace(new RegExp('{{src}}', 'g'), chart);
qrSrc = qrSrc.replace(new RegExp('{{i}}', 'g'), i);
content.insertAdjacentHTML('beforeEnd', qrSrc);
}
content.style.display = "";
}
}
document.getElementById("genQRcode").addEventListener("click", genQRcode);
document.addEventListener("keydown", function(e) {
if (e.ctrlKey && e.keyCode == 13) {
genQRcode();
}
});
});
</script>
</body>
</html>
Your click function
function myFunction() {
var x = document.getElementById("cpname").value;
document.getElementById("demo").innerHTML = x;
}
is getting and setting an element by ID. That will only ever affect a single element on the page (usually the first one that the browser runs into with that specific id). You need to use a different selector / way of getting the label you want to change because you can't reuse ids.
Basically you need to make your label fields distinct so you can actually select them
Ok, so I have a filterable search form that returns certain images in a grid, which works great, it resets when I delete the text in the search input, but when I click the "Clear" button, which should do the same thing as deleting the text, it doesn't work. Here is the HTML and JQuery used:
<form id="live-search" action="" class="styled" method="post" style="margin: 2em 0;">
<div class="form-group">
<input type="text" class="form-control" id="filter" value="" style="width: 80%; float: left;" placeholder="Type to search"/>
<span id="filter-count"></span>
<input type="button" class="clear-btn" value="Clear" style="background: transparent; border: 2px solid #af2332; color: #af2332; padding: 5px 15px; border-radius: 3px; font-size: 18px; height: 34px;">
</div>
</form>
This is the JQuery for the clearing text:
jQuery(document).ready(function(){
jQuery("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = jQuery(this).val(), count = 0;
// Loop through the comment list
jQuery(".watcheroo").each(function(){
jQuery(this).removeClass('active');
// If the list item does not contain the text phrase fade it out
if (jQuery(this).text().search(new RegExp(filter, "i")) < 0) {
jQuery(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
jQuery(this).show();
count++;
}
});
// Update the count
var numberItems = count;
});
//clear button remove text
jQuery(".clear-btn").click( function() {
jQuery("#filter").value = "";
});
});
Any help would greatly be appreciated.
value is a property on a DOMElement, not a jQuery object. Use val('') instead:
jQuery(document).ready(function($) {
$("#filter").keyup(function() {
var filter = $(this).val(),
count = 0;
$(".watcheroo").each(function(){
var $watcheroo = $(this);
$watcheroo.removeClass('active');
if ($watcheroo.text().search(new RegExp(filter, "i")) < 0) {
$watcheroo.fadeOut();
} else {
$watcheroo.show();
count++;
}
});
var numberItems = count;
});
$(".clear-btn").click(function() {
$("#filter").val(''); // <-- note val() here
});
});
Note that I amended your code to alias the instance of jQuery passed in to the document.ready handler. This way you can still use the $ variable safely within the scope of that function.
As the accepted answer doesn't solve the problem.
Try input event instead of keyup
$("#filter").on("input", function() {.....
& then clear the filter input field on which event you want.
$(".clear-btn").on("click", function() {
$("#filter").val("").trigger("input");
});
Add this to your CSS:
input[type="search"]::-webkit-search-cancel-button {
-webkit-appearance: searchfield-cancel-button;
}
<form>
<input type="search" name="search" placeholder="Search...">
</form>
I can make my label inside an input element (my "disappearing text"):
HTML
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
onfocus="if(this.value==this.defaultValue)this.value=''"
onblur="if(this.value=='')this.value=this.defaultValue" />
Then style it so my disappearing text is faded (#333). And style it so when I start to input a value into the field the text is black (#000).
CSS
input[type=text] {
color: #333;
}
input[type=text]:focus {
color: #000;
}
It all works fine until you move onto the next input field. Then the field you just entered a value in changes back to the #333 color. I can see why that happens, but can't quite get to how to keep the value black #000 color if the input field has had a value put into it.
Thanks in advance for the assist and education!
HTML5
HTML5 brings a handy attribute for the <input> tag called placeholder which enables native support of this functionality.
jsFiddle
<input type="text" placeholder="Search..." />
Support
All latest browsers support this, IE9 and below don't however.
<label>
Note that the placeholder attribute is not a replacemenr for the <label> tag which every input should have, make sure you include a label for the <input> even if it's not visible to the user.
<label for="search">Search</label>
<input id="search" placeholder="Search..." />
The above <label> can be hidden so it's still available to assistive technologies like so:
label[for=search] {
position:absolute;
left:-9999px;
top:-9999px;
}
Cross-browser solution
Here is a potential cross-browser solution, I've moved the code out of the tag and into script tags and then used the class placeholder to indicate when to fade the text.
jsFiddle
HTML
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
class="placeholder" id="my-input" />
CSS
input[type=text].placeholder {
color: #999;
}
JS
<script type="text/javascript">
var input = document.getElementById('my-input');
input.onfocus = function () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
};
input.onblur = function() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
};
</script>
Apply to all input[type=text]
We can extend the above solution to apply to all input[type=text] by using document.getElementsByTagName(), looping through them and checking the type attribute with element.getAttribute().
jsFiddle
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') === 'text') {
input[i].onfocus = inputOnfocus;
input[i].onblur = inputOnblur;
}
}
function inputOnfocus () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
}
function inputOnblur() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
}
This appears to work xbrowser using a combination of jQuery and the Modernizer library.
Requires the jQuery and Modernizer Libraries be on the site and properly referenced.
HTML
<head>
<script src="jquery-1.9.1.min.js"></script>
<script src="modernizr.js"></script>
<script>
$(document).ready(function(){
if(!Modernizr.input.placeholder){
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
$('[placeholder]').parents('form').submit(function() {
$(this).find('[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
}
</script>
</head>
<body>
<form>
<input name="firstName" type="text" maxlength="40" placeholder="Enter your first name">
</form>
CSS
input[type=text] {
color: #000;
}
input[type=text].placeholder {
color: #666;
}
SOURCE: http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text