Enable only backspace on onkeyevent? - javascript

I simply need javascript to automatically add a celsius degree sign after the user starts typing into a text box.
I already have this code which is working as intended. It is adding the degree sign after the text:
$(document).ready(function(){
var temp1 = new Value();
$("#Temperature1").on('keyup',function(e){
var oldstr=$("#Temperature1").val();
var tokens = oldstr.split('℃');
var suffix = tokens.pop() + '℃';
var prefix = tokens.join('');
$("#Temperature1").val(prefix+suffix);
});
});
<input type="textbox" id="Temperature1">
The issue: Once the user starts typing in this field, the "℃" appears correctly, after the text. However, once the user has typed something, it can't be removed. User might change their mind and not want to enter something in the Temperature field. How do I only enable backspace?
Thank you for your time.

try this
$(document).ready(function () {
var temp1 = new Value();
$("#Temperature1").on('keyup', function (e) {
if(e.which == 8) return; // added this line
var oldstr = $("#Temperature1").val();
var tokens = oldstr.split('℃');
var suffix = tokens.pop() + '℃';
var prefix = tokens.join('');
$("#Temperature1").val(prefix + suffix);
});
});
I've added a line which checks if the pressed key was backspace. If YES, it returns from the function (i.e. not executing the rest of the codes of the function).

Related

JavaScript only works in debug mode with a break

I have JavaScript code that is supposed to add input boxes to my html and then save the user input into and array. When I run my code regularly the screen refreshes and nothing happens. If I run it a second time it works how it should. Similarly if I open up debug mode and put a break point in the code works just fine the first time I try to run it. Is there an asynchronous issue I'm not aware of?
Also the event listener is checking for when someone hits the enter key on the web page otherwise the code doesn't execute.
Also, I'm new to stack overflow I've found the help so far great and if I'm not doing something in proper etiquette of asking a question please let me know!
var recipients = document.getElementById("howMany");
recipients.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
validate(e);
}
})
function validate(e) {
var num2 = document.getElementById("howMany");
num2 = document.getElementById("howMany").value;
var values = new Array();
for (i = 1; i < num2; i++){
//loop set to repeat to the amount of guests inputed by user
container.appendChild(document.createTextNode("Recipient " + (i+1)+":"));
//creates a text for the user to read which recipient each input is for
var x = document.createElement("input");
//creates the input element
x.setAttribute("id", "empInput"+i);
x.setAttribute("type", "text");
x.setAttribute("value", "");
//sets the type and attribute
container.appendChild(x);
//places the input element in the container
values[i] = document.getElementById("empInput"+i).value;
}
//console.log(values);
}

How can I check if input.value is the same as a random number

I want to make a little game where the browser selects a random number between 1 and 10 and the user has to guess which number it is. So I made an input, button and the random function, but every time, also when the inputNumber and the randomNumber are the same, it doesn't output the code I want!
<input type="numebr" id="userInput" />
<button id="button">Sure?</button>
<p id="awnser"></p>
let button = document.getElementById('button');
let input = document.getElementById('userInput').value;
let awnser = document.getElementById('awnser');
button.onclick = function randomFunc() {
var randomnr = Math.floor(Math.random() * 10 +1);
if (input == randomnr) {
awnser.innerHTML = randomnr + '<br> You got it!';
} else {
awnser.innerHTML = randomnr + '<br> Nevermind... idiot :P';
}
}
I tried to solve it's with parseInt
let input = parseInt(document.getElementById('userInput').value);
but it doesn't work. I think its a problem with the input value so that this is not a number rather a string...
Some tips for me?
It's because of what you do with this line:
let input = document.getElementById('userInput').value;
This gets the value when the page loads. when you click on a button, its value is the same as it was when the page got loaded. just move this line into button.onclick function and you should be fine.
Put
let input = document.getElementById('userInput').value;
inside the onclick function

transfer data from textbox to textarea with javascript

I have a small problem with my javascript code, im trying make a small application with 2 textboxes and 1 textarea. When textbox 1 is filled in you can press enter and then the focus will go to textbox 2. When textbox 2 is filled then the data from textbox 2 will go automaticly to the textarea as somekind of storage. And i fould like it to work with only plain javascript so it could support all the browsers and older browsers like IE 8
I have a massive javascript and every function works but somehow the big picture doesnt work. Can someone help me figure out why my javascript isnt doing what i want. And what i want is explained above.
https://jsfiddle.net/LLfwhL3L/2/
I cleaned the fiddle up fith the jshint functions from jsfiddle and get no erros, but it still doesnt work
These are the functions where i think it goes wrong:
function AddToList() {
var bonregel = document.getElementById("bonregel");
var val = bonregel.value.toString();
if (val != "") {
var box = document.getElementById("bonregelbox");
if (box.value != "")
box.value += "\n";
box.value = box.value + val;
}
bonregel.value = "";
bonregel.focus();
}
var delayrec = [];
function delay(callback, id, calldelay) {
clearTimeout(delayrec[id]);
delayrec[id] = setTimeout(callback, calldelay);
}
function keyup(event) {
var locatiebox = document.getElementById("locatie");
var bonregelbox = document.getElementById("bonregelbox");
var bonregels = bonregelbox.value.split(/\r\n/).join(",");
var locatie = locatiebox.value;
if (event.keyCode == 125)
SubmitContent(locatie, bonregels);
else
delay(AddToList, "AddToList", 500);
}
The working fiddle
https://jsfiddle.net/LLfwhL3L/5/
This is the working fiddle and how it should work, but on my device with IE 8 it doesnt work. The text from textbox 2 isnt goeing into the textaera. How can i solve this?

Opening webpage in javascript on trigger

I'm using a script called "HIT Scraper WITH EXPORT" to help me with my job. Right now it's set up in a way that any time there is a new posting the page plays a audible sound/ding. Normally when this happens I have to switch tabs and manually click on the new listing to preview it. I'm trying to make it so it automatically opens the listing before/after dinging. Also if possible having it put focus on that tab if I'm in a different one. Is any of this possible, where should I start? I'll post the code and some areas of interest I noticed, I just don't know what to do with these areas.. Thank you in advance.
The function that runs when a new hit is found I think:
function newHits(dingNoise) {
//console.log(dingNoise);
if (dingNoise || newHitDing)
document.getElementById("ding_noise"+audio_index).play();
}
I think "preview_link" is the var I need to automatically open after the ding sound plays.
var preview_link = "/mturk/preview?groupId=" + group_ID;
So my logic was something like:
function newHits(dingNoise) {
//console.log(dingNoise);
if (dingNoise || newHitDing)
document.getElementById("ding_noise"+audio_index).play();
window.open("/mturk/preview?groupId=") + group_ID;
}
Which did not work.. Here's the full script if anyone has any ideas.. Thanks again.
https://greasyfork.org/en/scripts/2002-hit-scraper-with-export/code
EDIT: I don't think the way I originally wanted to do this will work, nothing in the code knows/points to the actual new listings. All that's defined in the code is the preview link function. If there is some way to have it call/open that "var preview_link = "/mturk/preview?groupId=" + group_ID;" after the ding, that would probably be what I need.
for (var j = 0; j < $requester.length; j++)
{
var $hits = $requester.eq(j).parent().parent().parent().parent().parent().parent().find('td[class="capsule_field_text"]');
var requester_name = $requester.eq(j).text().trim();
var requester_link = $requester.eq(j).attr('href');
var group_ID=(listy[j] ? listy[j] : "");
group_ID=group_ID.replace("/mturk/notqualified?hit","");
var masters = false;
var title = $title.eq(j).text().trim();
var preview_link = "/mturk/preview?groupId=" + group_ID;
//console.log(listy[j]);
//console.log(title+" "+group_ID +" "+ listy[j]);
if (!group_ID || group_ID.length == 0){
preview_link = requester_link;
title += " (Requester link substituted)";
}
var reward = $reward.eq(j).text().trim();
var hits = $hits.eq(4).text().trim();
var time = $times.eq(j).parent()[0].nextSibling.nextSibling.innerHTML;
var description = $descriptions.eq(j).parent()[0].nextSibling.nextSibling.innerHTML;
//console.log(description);
var requester_id = requester_link.replace('/mturk/searchbar?selectedSearchType=hitgroups&requesterId=','');
var accept_link;
accept_link = preview_link.replace('preview','previewandaccept');
I'm thinking you want to do:
window.location.replace(window.location.host + '/mturk/preview?groupId='+ group_ID)
I'm actually not sure if you need the window.location.host + part.

Im designing a chess game in HTML,i want to change one charecter from on position to another

i have designed chess board using buttons.Initially all the values on the button will be null,upon loading the page all the pieces appear on them and the piece of code is as follows
<input type="button" id="A8" value="" style="background:#FFE4C4;font-size: 70px;height:90;width:100" onclick="check(this.id)">
and in the onLoad function,the ASCII charecter of the chess pieces are assigned as follows:
document.getElementById('A1').value=String.fromCharCode(9814);
Now what i want is to change the one piece from a button to another on clicking two buttons.i had tried a lot with the following script
function check(clicked_id) {
var Button_2 = "";
if (i < 2) {
i++;
// alert("i:"+i);
if (i == 1) {
Button_1 = clicked_id;
B1_val = document.getElementById(Button_1).value;
alert("B1 Button val:" + B1_val);
}
if (i == 2) {
var Button_2 = clicked_id;
B2_val = document.getElementById(Button_2).value;
alert("b1 val:" + B1_val);
alert("B2 val:" + B2_val);
B2_val = B1_val;
B1_val = "";
alert("B1 val:" + B1_val + "B2 val:" + B2_val);
}
} else {
alert("Only 2 butons should press..i:" + i);
i = 0;
}
// alert("clcked a button:"+clicked_id);
}
But the code is not working
If you just want to move the value from the location of the first click to the location of the second click, then you can do that fairly simply like this:
var lastClick;
function check(id) {
var src, dest;
if (!lastClick) {
// no previous click so just store the location of this first click
lastClick = id;
} else {
// move value from lastClick id to new id
src = document.getElementById(lastClick);
dest = document.getElementById(id);
dest.value = src.value;
src.value = "";
lastClick = null;
}
}
I assume that a real application would need all sorts of error handling that doesn't let you put a piece on top of another piece, ignores first clicks on empty spaces, enforces only legal moves, etc...

Categories

Resources