Okay, I'm doing an exercise to learn Javascript, where I need to make a simple Sudoku app. There's a function to create the Sudoku field, and each little square is in a div with an id identifying the row number and column number.
Now the idea is that if a user clicks on an open field, a prompt appears asking him/her to enter a number. If the number is between 1 and 9, that number is then displayed inside the field.
I first invoked the function like this:
node.onclick=function(){fillNumber(this.id);};
This had the unexpected side-effect of making the prompt box appear three times in a row whenever a click was performed. Yet, it was clear that the first input by the user was accepted, stored and added to the div just like it was supposed to. The input from the second and third prompt box is simply lost.
I solved the problem by using the following invocation:
node.onclick=function(){if (parseInt(this.id) > 0) fillNumber(this.id);};
Yet I've no idea why this works (this is copied from a fellow student who did it this way, but doesn't know why). The value of this.id is always something like this: "11", "12", "13", "21", "22", ... So I don't even see the point of first parsing it to an int or checking whether it's bigger than 0. It always is both an int and bigger than 0 as far as I can see. Regardless, the code of the method itself didn't change and the method is invoked with the exact same argument value.
Here's the method fillNumber:
function fillNumber(id){
var input = -1;
do{
input = parseInt(prompt("Enter a number between 1 and 9: ", ""));
}while(input < 1 || input > 10);
var i = parseInt(id/10), j = id%10;
numbers[i][j] = input;
var tekst = document.createTextNode(numbers[i][j]);
document.getElementById(tekst).appendChild(tekst);
}
Can anyone explain this to me?
I may suggest you to check whether there are elements upon each other - this might be the reason for three prompts in a row.
I guess the reason the other student wrote parseInt(this.id) is the same.
He tries to parse an id into an int to escape the other clicked elements, so he makes sure the id is a valid number.
Try to use next lines:
node.onclick=function(e){
if( e.stopPropagation ) e.stopPropagation();
if( e.preventDefault ) e.preventDefault();
else e.returValue = false;
fillNumber(+this.id);
}
Note the + at +this.id parses a string to an integer or a float.
Related
Here Is My Logic:
It Didn't Work :(
function ShowDropMenu(){
var numfiled = document.getElementById('numpeple'); //I Want Whenever Someone Enters a Number In Input Field It Should Display The Dropdown Menu?
if (numfiled < 0 ) {
document.getElementById('dropmock').style.display="block"
}
else{
alert('Please Add Atleast 1 Or More People to go ahead)
}
}
I Don't Know What's Went Wrong?
numfiled is an Element, so comparing it with a number won't do anything meaningful.
You want the value of the Element. Additionally, since the value is always a string, you want to parse it as a number. For example:
var numfiled = parseInt(document.getElementById('numpeple').value);
Note: This assumes #numpeple refers to an <input> element, inferred from the comment in the code: "Someone Enters a Number In Input Field"
I have a web page with a form on it. The "submit" button is supposed to remain deactivated until the user fills in all the necessary fields. When they fill in a field, a checkmark appears next to it. When all the checkmarks are there, we're good to go.
A checkmark might be set by code like this:
if (whatever) checkLocation.innerHTML = CHECKMARK;
Here's the code I'm using to do the final check. It just loops through all the locations where there may be checkmarks. If it finds a location without a mark, it disables the submit button and leaves. If it gets through them all, it activates the button and returns true.
function checkSubmitButton() {
var button = document.getElementById(SUBMIT_BUTTON);
for (var i=0; i<CHECK_LOCATIONS.length; i++) { // should be for-each, but JS support is wonky
var element = document.getElementById(CHECK_LOCATIONS[i]);
console.log(CHECK_LOCATIONS[i] +": " +element.innerHTML);
// if found unchecked box, deactivate & leave
if (element.innerHTML != CHECKMARK) {
button.disabled = true;
return false;
}
}
// all true--activate!
console.log("ACTIVATING BUTTON!");
button.disabled = false;
return true;
}
Here's the problem: this works so long as the const CHECKMARK contains something simple, like "X". But specs call for a special HTML character to be used: in this case ✓, or ✓. When I do the comparison (in the if line) it ends up comparing the string "✓" to the string "✓". Since these two are not equal, it doesn't recognize a valid checkmark and the button never activates. How can I compare the contents of the HTML element my constant? (And hopefully make the code work even if down the road somebody replaces the checkmark with something else.)
Thanks.
There is no problem with the check character and it behaves exactly like the X character. The problem is, that your html have the checkmark character stored as html entity in hex string. If you compare checkmark to checkmark it works just fine: https://jsfiddle.net/m7yoh026/
What you can do in your case is to make sure the CHECKMARK variable is the actuall checkmark character, not the html entity.
Other option is to decode the html entity: https://jsfiddle.net/m7yoh026/3/
var CHECKMARK = '✓'
var decoded_checkmark = $('<textarea />').html(CHECKMARK).text();
console.log($('div')[0].innerHTML)
if ($('div')[0].innerHTML == decoded_checkmark) {
$('body').append('checkmark recognized<br>')
}
You can convert a character to its HTML entity equivalent like so:
var encoded = raw.replace(/[\u00A0-\u9999<>\&]/gim, function(i) {
return '&#'+i.charCodeAt(0)+';';
});
Well, here's what I ended up doing: I made a function called encodeHtml() that takes a character or string, writes it to a brand new div, and then returns what's contained in that div:
function encodeHtml(character) {
var element = document.createElement("div");
element.innerHTML = character;
return element.innerHTML;
}
Then I can compare to what it returns, since it automatically changes "✓" to "✓", and will work with any unforeseen changes to that character. It's a bit of a kludge, but it works. (It's still not clear to me why JavaScript does this automatic conversion...but there are many design choices in which JavaScript mystifies me, so there you go.)
Thanks all for the help.
I'd like to add a word counter to a large text box (think blog editor) that increments with every word that I enter. (i.e. after I type "Hello" it would increment from 0 to 1 and after I write "world" after that it would increment to 2). I'd like to do this within a webpage but I'm happy to consider other options.
I have no idea how to do this. I think there would be a way to do this with Javascript but I know next to nothing about Javascript.
Could someone point me in the direction of figuring out how to do this?
I think a good idea to implement this is to check inputed letter (for example, onKeyUp event). If previous character was non-space and current is not a letter, then increment count. Detail: if previous character is non-letter, increasing should not be done (double spaces e t.c.)
When user is pressing Backspace or Delete key, similar check should be done. Key codes you can find here
The difficult thing with this counting 'on the fly' is to check 'non-key' input. For example, user can use Ctrl+Insert combination to copy data from clipboard, or select text in the textbox and then press Del key. That should be handled separately if there is real need to avoid whole value processing (which could be really huge)
Use this functionality on the onkeyup event for the textbox.
document.getElementById("inputbox").addEventListener("keyup",function(e){
// Get the inputs text.
var inputVal = e.srcElement.value;
var counter = 0;
// Check input isn't empty.
if(inputVal){
// Count individual letters.
var wordlist = inputVal.split(" ");
for(var i=0;i<wordlist.length;i++)
if(wordlist[i])
counter = counter+1;
}
// Then set your counter element.
document.getElementById("counter").value = counter;
});
i have a table like below which each content is input pop-up
on square i spot you see on last digit have 1,2,8,9 format.
in my html the content of table is value of Posisi
Nomor Rak
<br><input type="text" id="posisi" readonly/></br>
that automaticly i pick using
<td class="data206"><div align="center"><input class="data206" type="button" onclick="popup_window_show('#sample', { pos : 'tag-right-down', parent : this});setvalue(this.value);" value="A1.7.8" /></div></td>
for an example.
so my pop-up like this
my purpose to bind the last digit and then i can manipulate line value. So for an idea script will like below
$(document).ready(function(){
var posisi = $("#posisi").val();
if (posisi== like "1" or like "2" or like "8" or like "9" ){
$("#line").val("9")
}
});
My problem: I don't know how to bind the last digit in jquery..to make conditonal that $("#posisi") last digit value between 1 or 2 or 8 or 9. if this conditional true i can add value in $("#line").val("whatever i want")
need help with an example will be appreciate
Your var posisi will contain a string like "A1.7.8" and you can easily get the last character of string. This may help
How can I get last characters of a string using JavaScript
There are a few more tips which may help.
It seems that you do not want to wrap the code in document.ready. I think you want to get the last digit value on every click. so get the value in "popup_window_show" function or function you are using to show popup.
Moreover if you want to make calculation on that number i.e 1,2,8,9 then convert it into integer form first.
var posisi = $("#posisi").val();
var regex = /\.(\d+)\.?$/;
// Catches the last set of digits following a period.
// Allowing for an additional period at the end.
var matches = posisi.match(regex);
if (matches) {
var lastNumber = parseInt(matches[1], 10);
// Do something
$("#line").val(lastNumber);
}
Ladies and gentlemen,
I'm stuck. I've been pondering this (and obviously have failed since I'm asking for your valuable assistance) in trying to get my code to work.
I need to come up with a simple (...I'm sorry, i'm new to this) code that prompt users to keep entering names using a loop. If the user does not enter 'q'(without quotes) and if the value entered is NOT null, then the value entered should be added to the array (in my case, names).
If the user enters 'q', the loop should stop, 'q' will not be entered in the array and the list of names should be printed (through the second function in my code).
Here's what I have so far... I can make the code work if I tell the loop to run i<5... it runs 5 times and then it stops. But it fails if i do i < names.length..it causes it say that length is null or not an object (on line 10). That's problem one. And for the life of me, I can't figure out how to add the logic that will run the loop until user enters q.
Please help!
Thank you.
function getNames(){
var names = new Array();
for(i=0;i<names.length;i++){ /*if i do i=0;i<5;i++, the code works; it doesn't with this*/
names[i] = prompt("Enter an item to add to the Name list (enter \'q\' to quit","");
}
printNames(names);
}
function printNames(names) {
for(x=0; x < names.length;x++){
document.write(names[x] + '<br />');
}
}
getNames();
printNames();
I am sure somewhere in your class/book it talks about while loops. So you want to use a while loop if you want them to keep entering without a limit.
while (myCondition===true) {
//do something
}
Now look at your for loop and figure out why it is failing.
for(i=0;i<names.length;i++)
Look at what it is doing:
i = 0
names.length = 0
Is 0 < 0?
Well to start with Problem 1:
Your names array begins with a length property of 0 and so your first for loop doesn't run because 0 is not less than 0.
Which leads to Problem 2:
Again since nothing was entered into your names array your second for loop again does nothing and doesn't execute document.write because the length property of your array is still 0.