How to make an input not case sensitive - javascript

I want to know how make it when the user types in something to an input it doesn't have to be the same capitalization as the value for the document.getElementById("spanId").innerHTML = "146.5 meters"; to appear.
HTML
<input id="ask" type="text"
placeholder = "Ex: how tall is the Gateway Arch"
onfocus="this.placeholder = ''"
onblur="this.placeholder = 'Ex: how tall is the gateway arch'"
text-align: center/>
JS
document.getElementById("button").onclick = function() {
if (document.getElementById("ask").innerHTML == "how tall are the pyramids") {
document.getElementById("spanId").innerHTML = "146.5 meters";
} else if (document.getElementById("ask").value == "how tall is the gateway arch") {
document.getElementById("spanId").innerHTML = "630 feet";
} else if (document.getElementById("ask").value == "how tall is the empire state building") {
document.getElementById("spanId").innerHTML = "1,454 feet";
}
}

First, use value instead of innerHTML for input fields
Second, convert both side lowercase or uppercase during comparing
Try like this
var ask=document.getElementById("ask").value.toLowerCase();
if (ask =="how tall are the pyramids")
Or like this
var ask=document.getElementById("ask").value.toUpperCase();
if (ask =="how tall are the pyramids".toUpperCase())

Related

get characters left of cursor until the first space after a symbol is typed

What I am trying to do is build the ability to add tagging with a text editor #user and populate a list of users they can select from and it will insert that into the editor. I want to grab all the text before the # when it is typed up to the first space so that I can distinguish if the user is trying to type an email or wanting to add a tag. I know I can just split up the string from # and detect that, but I am having a hard time knowing where to start to get that text to begin with.
Any help would be great.
$(document).on('keyup', '.element', function(e) {
if (e.keyCode == 50) {
//get text here
}
})
Intro
Here is a sample of something that might cover your needs.
However, what I did was indeed of detecting the #, I detected the space.
Once the space was clicked, I went back to find the # .
JSFiddle: https://jsfiddle.net/2uqgorka/35/
JS
let output = document.getElementById("output");
let result = document.getElementById("result");
input.addEventListener('keyup', logKey);
function logKey(e) {
console.log(e);
output.innerHTML += ` ${e.code} + ${e.keyCode}`;
if (e.keyCode == 32) { //Detect a space
let startPos = e.target.selectionStart;
let endPos = e.target.selectionEnd;
//alert(startPos + ", " + endPos);
if(startPos == endPos){
console.log("full input:"+e.target.value);
let textUpToPosition =e.target.value.substring(0,endPos-1);
console.log("textUpToPosition:"+textUpToPosition);
let previousAt = textUpToPosition.lastIndexOf("#");
let previousSpace = textUpToPosition.lastIndexOf(" ");
console.log("previousAt:"+previousAt);
console.log("previousSpace:"+previousSpace);
if(previousSpace < previousAt){
let resultText = textUpToPosition.substring((previousAt));
result.innerHTML = resultText;
}
}
}
}
HTML
<textarea id="input">
#Someone test
</textarea>
<hr>
KeyStrikes<br>
<div id="output">
</div>
<hr>
Result<br>
<div id="result">
</div>

How to change if statement from alert to text

How would I instead of have the if statement come up as an alert, have it appear as text on my page. Thanks
document.getElementById("button").onclick=function() {
if (document.getElementById("ask").value=="how tall are the pyramids") {
alert ("146.5 meters");
} else if (document.getElementById("ask").value == "how tall is the gateway arch") {
alert("630 feet");
} else if (document.getElementById("ask").value == "how tall is the empire state building") {
alert("6900 feet");
I may have misunderstood, but it sounds like you want to display the value in an html element rather than alerting the value. See the below example
document.getElementById("button").onclick = function() {
var val = document.getElementById("ask").value;
var answer = "I don't know!";
if (val == "how tall are the pyramids")
answer = "146.5 meters";
else if (val == "how tall is the gateway arch")
answer = "630 feet";
else if (val == "how tall is the empire state building")
answer = "6900 feet";
document.getElementById("answer").innerHTML = answer;
}
And in the html, add an answer element like so
<p id="answer"></p>
See CodePen
You want to add another element to your page that can display the results.
In the demo below I have added a span element and set the id attribute to answer.
document.getElementById("button").onclick=function(){
var Q = document.getElementById("ask").value;
var A = document.getElementById("answer");
var Result = "Ask another?";
if (Q=="how tall are the pyramids"){
Result="146.5 meters";
}else if(Q=="how tall is the gateway arch"){
Result="630 feet";
}else if(Q == "how tall is the empire state building"){
Result="6900 feet";
}
A.innerHTML = Result;
}
<span id="answer"></span><br/>
<input type="text" id="ask" />
<button type="button" id="button">Ask</button>
If you don't understand any of the above source code, please leave a comment below.
I hope this helps. Happy coding!
change
document.getElementById("ask").value
to
document.getElementById("ask").innerHTML
or
document.getElementById("ask").innerText

Is there a DRY(er) way to add items to an array?

I have a snippet of code that works without issue. However, I feel like it is kind of long for what it does and I felt like I repeated my self a lot. This is a validation snippet that checks a form for all input fields and displays an error message with what you are missing (if you are) once you submit.
$scope.save = function() {
var post = new FormData();
post.append("title", $scope.post.title);
post.append("photo", $scope.photo);
post.append("body", $scope.post.body);
post.append("truncBody", $scope.post.truncBody);
if(!$scope.post.title || !$scope.photo || !$scope.post.body || !$scope.post.truncBody){
var thingsLeft= [];
if(!$scope.post.title){
thingsLeft.push(" Title");
}
if(!$scope.photo){
thingsLeft.push(" Cover Image")
}
if(!$scope.post.body){
thingsLeft.push(" Body");
}
if(!$scope.post.truncBody){
thingsLeft.push(" Summary");
}
Messages.error("Please fill out all fields. Fields left:" + thingsLeft);
return;
}else{
post to server
}
}
Again, this works perfectly, no errors, looks great client side. All I want to know is if there is a better/shorter/more DRY way of writing this.
If you really ended up having a lot of that sort of code, you could write a helper function:
function pushIf(array) {
for (var i = 1; i < arguments.length; i += 2)
if (arguments[i]) array.push(arguments[i + 1]);
}
then
pushIf(thingsLeft,
!$scope.post.title, " Title ",
!$scope.photo, " Cover Image ",
!$scope.post.body, " Body",
!$scope.post.truncBody, " Summary"
);
If thingsLeft is empty, no things are left, you may omit the doubly listed props in the if, that would annoy me personally:
var thingsLeft= [];
if(!$scope.post.title){
thingsLeft.push(" Title");
}
if(!$scope.photo){
thingsLeft.push(" Cover Image")
}
if(!$scope.post.body){
thingsLeft.push(" Body");
}
if(!$scope.post.truncBody){
thingsLeft.push(" Summary");
}
if ( thingsLeft.length > 0 ) {
Messages.error("Please fill out all fields. Fields left:" + thingsLeft);
return;
}else{
post to server
}
You could use an array of the required properties and hasOwnProperty(). Something along these lines:
var requiredFields = ['post.title', 'photo', 'post.body', 'post.truncBody'];
var missingFields = [];
for (field in requiredFields) {
if (!$scope.hasOwnProperty(field)) {
missingFields.push(field);
}
}

CSS Style Javascript

Im Making a question for a website and would like the the correct / try again messages in the var reltext to be different colours ie green for correct and red for wrong and maybe a small png beside each.
any ideas ?
<form name = "Q1">
<p>A local construction company has purchased 5 brand new diggers. Two of them have a telescopic jib. If a driver chooses a digger to use at random what is the probability it will have a telescopic jib?<br>
0/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1a', '1')">
1/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1b', '2')">
2/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1c', '3')">
3/5
<input name = "rad1" type = "radio" class="radio" onclick = "getAnswer('1d','4')">
<br><br>
</p>
<div id = "para"><div>
</form>
<script type = "text/javascript">
var reltext = [];
reltext[1] = "TRY AGAIN - 0/5 This would mean that there was no diggers with a telescopic jib."
reltext[2] = "TRY AGAIN - 1/5 This would mean that there was only 1 digger with a telescopic jib"
reltext[3] = "CORRECT - 2/5 This would mean that there was 2 diggers with a telescopic jib"
reltext[4] = "TRY AGAIN - 3/5 This would mean that there was 3 diggers with a telescopic jib."
function getAnswer(ans, rel) {
document.getElementById("para").innerHTML = reltext[rel];
if (ans == "1c") {alert ("Correct - Well done!")}
else {alert ("Incorrect - Try again")}
}
</script>
You may not style the contents of an alert box with JavaScript (or anything else for that matter).
A good alternative would be using a framework like jQuery UI and use modal dialogs instead of JS alerts. Here's a link to jQuery UI's dialogs: http://jqueryui.com/demos/dialog/
You could do this several ways.
1. You could replace your reltext with the following:
reltext[1] = "<div style='background-color:#dd0000;'>TRY AGAIN - 0/5 This would mean that there was no diggers with a telescopic jib.</div>"
reltext[2] = "<div style='background-color:#dd0000;'>TRY AGAIN - 1/5 This would mean that there was only 1 digger with a telescopic jib</div>"
reltext[3] = "<div style='background-color:#00dd00;'>CORRECT - 2/5 This would mean that there was 2 diggers with a telescopic jib</div>"
reltext[4] = "<div style='background-color:#dd0000;'>TRY AGAIN - 3/5 This would mean that there was 3 diggers with a telescopic jib.</div>"
2. Or you could setup a style for the div with id="para". Something like:
<style type="text/css">
.classWrong { bakcground-color: #dd0000; }
.classRight { background-color: #00dd00; }
</style>
and then in your script section change the function to set the style:
function getAnswer(ans, rel) {
document.getElementById("para").innerHTML = reltext[rel];
if (ans == "1c") {
document.getElementById("para").className = "classRight";}
alert ("Correct - Well done!");
else {
document.getElementById("para").className = "classWrong";}
alert ("Incorrect - Try again")}
}
3. As far as adding images to the response just add in an img element to your reltext. maybe like:
reltext[1] = "<div style='background-color:#dd0000;'>TRY AGAIN - 0/5 This would mean that there was no diggers with a telescopic jib.<img src='images/Wrong.png' /></div>"
reltext[3] = "<div style='background-color:#00dd00;'>CORRECT - 2/5 This would mean that there was 2 diggers with a telescopic jib<img src='images/Right.png' /></div>"
There are many other ways to do this but I thought I would just have a go at it.
To solve the issue the simplest way in my opinion is to make 2 div styles
Ex:
div.correct{
background-color: green;
}
div.wrong{
background-color: red;
}
make the reltext a multidimensional array, containing either the correct/wrong information, ex:
reltext[1][0] = "correct"
reltext[1][1] = "CORRECT - That answer is correct"
reltext[2][0] = "wrong"
reltext[2][1] = "WRONG - This is wrong!"
reltext[3][0] = "wrong"
reltext[3][1] = "WRONG - BLaBlah.."
and modify the function like:
function getAnswer(ans, rel) {
document.getElementById("para").innerHTML = reltext[rel][1];
document.getElementById("para").className = reltext[rel][0];

Indicate word wrap in textarea

I have textarea with rows="50" and cols="15".
I want when it's going to wrap the words to simulate enter pressing,because I check when the user goes to new row with keydown and e.which==13 ,but the word wrap prevents me to check this.
edit:
Because I want to try to make something like online editor ,and I dynamicly count the rows like Bespin`s(bespin.mozillalabs.com ,left) rows counting.For this counting I detect when enter is pressed and add new number,but when word wrap is on - it counts wrong ,because when the words are wrapping enter isn't pressed.
Edit 2:
I found a script ,that does what I want ,but how to simulate enter pressing?
<script language="javascript" type="text/javascript">
var ijk = 0;
function txt_ara()
{
//alert("1");
//alert(document.getElementById("email").value.length);
//var ijk = 0;
//var incr = 2;
if(document.getElementById("email").value.length <= 59)
{
if(document.getElementById("email").value.length == 59)
{
document.getElementById("email").value += "\n";
}
}
else
{
var lkm = "";
if(ijk == 0)
{
lkm = parseInt(document.getElementById("email").value.length % 120);
}
else
{
lkm = parseInt(document.getElementById("email").value.length % 60);
}
if(lkm == 0)
{
ijk = 1;
document.getElementById("email").value += "\n";
}
}
}
</script>
<textarea name="email" id="email" class="txtField1" cols="60" rows="26" wrap="off" onkeyup="txt_ara();" onkeydown="txt_ara();"></textarea>
i don't know why you want to do this but you could use 2 "hacks":
1) count the amount of letters and if is == to 1 line of text add a \n
2) use a rich editor as ckeditor in minimal whiteout plugins and add the word wrap option (most of them have something like that)

Categories

Resources