My aim is to use a single input to collect numbers and strings then use it to determine a math operation.
For example, I parse in values such as √64 intending to find the square root of 64. Knowing that this is no valid javascript, so I decided to get the first character with result[0]; which is "√" and then slice out the remaining values with result.slice(1); which is "64", then when the condition that result[0] == "√" is true then Math.sqrt(sliceVal) . This seems perfect and runs well in a mobile editor, but doesn't run in any web browser.
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
I do not know why It is not running at your end but It is working perfectly according to your requirement I tested above code :)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function actn() {
var input = document.getElementById("test").value;
var result = input.toString();
var firstVal = result[0];
if (firstVal == "√") {
var sliceVal = result.slice(1);
alert(Math.sqrt(sliceVal));
}
alert("No match found");
}
</script>
</head>
<body>
<input type="text" id="test" />
<button type="button" onclick="actn()">Test</button>
</body>
</html>
Checking ASCII value instead of character comparison should work.
<html>
<body>
<input type="text" id="input" />
<button type="button" id="sqrRoot">Square Root</button>
<h1 id="display"></h1>
<script>
function actn() {
var input = document.getElementById("input").value;
var display = document.getElementById("display");
var result = input.toString();
var firstVal = result[0];
/* Ascii value for √ is 8730 */
if (firstVal.charCodeAt(0) === 8730) {
var sliceVal = result.slice(1);
display.innerHTML = Math.sqrt(sliceVal);
}
}
document.getElementById("sqrRoot").addEventListener("click", function () {
actn();
});
</script>
</body>
</html>
Related
DISCLAIMER: i'm legit a newbie
I have a 2nd parameter in the getInput function, I should use it for the 9 zeros that I should input. But I don't know how to loop it to become 9 zeros instead of putting it in a variable.
How do I loop and store 9 zero's into my "digit" parameter without declaring it as var zr = "000000000"
here's my code:
<html>
<head>
<title>Search</title>
<script>
//This method does the processing
function getInput(input, digit){
var str=input.substring(0,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output="A"+zrsub+""+str;
//can also be var output=input[0]+zrsub+""+str;
return output;
}
//Displays output
function showOutput(){
var input=document.getElementById("search-input").value;
var dislay=document.getElementById("search-output");
dislay.value=getInput(input);
}
</script>
</head>
<body>
<div class="wrapper">
<input type="text" id="search-input">
<input type="button" id="btn" value="ENTER" onclick="showOutput()"> <br><br>
<input type="text" id="search-output">
</div>
</body>
</html>
Sorry just a newbie in this whole programming thing. Just a little confused.
with for loop join string
function joinString(input,digit) {
var inputArr = input.split("");
// var n = 9; // the length of the ouput string;
for (var i = 0; i < digit; i++) {
inputArr.unshift(0);
if (inputArr.length === digit) {
return inputArr.join("");
}
}
}
console.log(joinString("123456"));
You can use padStart
function getInput(input, digit){
return 'A'+ input.toString().padStart(digit, '0');
}
document.getElementById('target').innerHTML = getInput(132,9)
<p id="target"></p>
IE may not support it though.
I am new to java and am trying to create a game that simulates hangman. I am trying to get the letters from the user after they input on keyboard. However, when I type something it doesn't make any difference, it doesn't output whether it is correct or incorrect. I think I may not be using the event in my guessLetter() function correctly, any help would be greatly appreciated.
window.addEventListener("DOMContentLoaded", function() {
var word = ['taco'];
let randNum = Math.floor(Math.random() * word.length);
let chosenWord = word[randNum];
let underScore = [];
let docUnderScore = document.getElementsByClassName('underScore');
let docRightGuess = document.getElementsByClassName('rightGuess');
let docWrongGuess = document.getElementsByClassName('wrongGuess');
console.log(chosenWord); //lets grader cheat
let generateUnderscore = () => {
for (let i = 0; i < chosenWord.length; i++) {
underScore.push('_');
}
return underScore;
}
document.onkeyup = function guessLetter(event) {
let letter = String.fromCharCode(event.keyCode || event.code).toLowerCase();
if (chosenWord.indexOf(letter) > -1) {
rightWord.push(letter);
underScore[chosenWord.indexOf(letter)] = letter;
docUnderScore[0].innerHTML = underScore.join(' ');
docRightGuess[0].innerHTML = rightWord;
if (underScore.join('') === chosenWord) {
alert('CONGRATS! YOU WIN!!!');
} else {
wrongWord.push(letter);
docWrongGuess[0].innerHTML = wrongWord;
}
}
underScore[0].innerHTML = generateUnderscore().join(' ');
}
});
<!DOCTYPE html>
<html>
<head>
<h1> Hangman </h1>
<div id="guesses">
<div class="letter" id="letter" </div>
</div>
</head>
<body>
</body>
<div class="container">
<div class="underScore">_ _ _ _</div>
<div class="rightGuess"> right guess </div>
<div class="wrongGuess"> wrong guess </div>
</div>
</html>
In the JS console, ReferenceErrors are being thrown as a result of the fact that the rightWord and wrongWord variables have not been defined.
You are writing the in head tag why ? it doesn't shown in your web page , place the html tags within body.
I've got a product title which I'm splitting and inserting a linebreak using javascript like this:
<script>
function myFunction() {
var str = "How are you - doing today?";
var res = str.split("-").join('<br>');
document.getElementById("demo").innerHTML = res;
}
</script>
This works for most case scenarios, however in some cases I will need to remove the second line completely. So everything after the - will need to be removed. Only within that element though, so if I've got this for example
<h3>This is a product - title</h3>
the result should be
<h3>This is a product</h3>
Again this only needs to apply to elements with a certain class. Anybody got any idea ow to do this?
Why not us a simple replace,
string = string.replace(/-/g, '<br>');
or for complete deletion, take
string = string.replace(/-.*$/g, '');
Check className of the element:
function myFunction() {
const str = `How are you - doing today?`
const first = str.split(`-`)[0]
const all = str.split(`-`).join(`<br/>`)
const el = document.getElementById(`demo`)
const el.innerHTML = el.className === `any-name` ? first : all
}
Try this:
(function() {
// For splitted titles
var split = document.querySelectorAll(".dash-split");
var splits = [];
split.forEach(function(spl) {
splits.push(spl.innerHTML.split("-").join("<br>"));
});
console.log(splits); // Outputs ["This is <br> split!"]
// For removed titles
var removedEls = document.querySelectorAll(".dash-split");
var removed = [];
removedEls.forEach(function(rem) {
removed.push(rem.innerText.split("-")[0].trim());
});
console.log(removed); // Outputs ["This is"]
})();
<!DOCTYPE html>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<div>
<h1 class="dash-split">This is - split!</h1>
<h1 class="dash-remove">This is - removed!</h1>
</div>
</body>
</html>
This should get you what you want, provided the script runs at the end of the document. For wrapping, it keys off of the class title-wrap.
<html>
<head></head>
<body>
<h3>This is a product - title</h3>
<h3 class="title title-wrap">This is a product - with a wrapped title</h3>
<h3>This is a product - with another title</h3>
<script>
(function() {
var titles = document.querySelectorAll('h3');
titles.forEach(function(o, i) {
var title = o.innerHTML;
if (/title-wrap/ig.test(o.className)) {
o.innerHTML = title.replace(/-/g, '<br />');
} else {
o.innerHTML = title.replace(/-.*$/g, '');
}
});
})();
</script>
</body>
</html>
My code
<!DOCTYPE html>
<html>
<body>
<input type="text" id="text" value=""><br>
<button onclick="myFunction()">Submit</button>
<script>
function myFunction() {
var str = document.getElementById("text");
var res = str.replace("1", "2");
document.getElementById("text") = res;
}
</script>
in input field i am taking some input from user on (click) submit i want to replace all 1 with 2 and i want to display result in same field but its not working..
You need to get the value
function myFunction() {
//getElementById returns dom object
var el = document.getElementById("text");
//you want to replace its value
var str = el.value;
//use a simple regex to replace all instances
var res = str.replace(/1/g, "2");
//set the value property of the target element
el.value = res;
}
Demo: Fiddle, short version
This is what you want:
function myFunction() {
var inputElt = document.getElementById("text");
var res = inputElt.value.replace("1", "2");
inputElt.value = res;
}
Your line:
document.getElementById("text") = res;
instead, should look like this:
document.getElementById("text").value = res;
I have 3 checkboxes and 1 textbox
i use only these controls mentioned above ..
I want ---- when i check checkbox1 and checkbox2 then it will display in textbox1 as 1,2 as it is as the same ascending order not 1,2, or 2,1,
I use this type of coding in asp.net (VB) , i wanna use this coding for 45 checkboxes........
Can anybody solve this problem in asp.net (vb)
JS solution (needs adaptation to your markup) as question is tagged with javascript
<html>
<head>
<title>S.O. 4121588</title>
<script type="text/javascript">
var gMax = 45;
function $(aId) {
return document.getElementById(aId);
}
// generates gMax checkboxes with value from 1 to gMax
function onload() {
var form = $('theForm');
for (var i = 1; i != gMax; i++) {
var cb = document.createElement('input');
cb.setAttribute('type', 'checkbox');
cb.setAttribute('id', 'checkbox-' + i);
cb.setAttribute('value', i);
form.appendChild(cb);
}
}
// update the result textarea
function updateResult() {
var num = [ ];
for (var i = 1; i != gMax; i++) {
var cb = $('checkbox-' + i);
if (cb.checked) {
num.push(cb.getAttribute('value'));
}
}
$('result').innerHTML = num.join(", ");
}
</script>
</head>
<body onload='onload()'>
<form id="theForm"></form>
<input type="button" id="resultBtn" value="Result"
onclick="updateResult()" />
<br/>
<textarea id="result"></textarea>
</body>
</html>
Tested under Chrome 9.0.570.1 dev