Array sorting: Alphabetical and Numerically - javascript

I want a webpage that has a text box. There are two buttons underneath the text box that says "Sort Alphabetically" and "Sort numerically." I want it so that whatever the user types in the box, it sorts. If the user types in numbers and letters, it will cancel the sorting and an alert will pop up saying "Cannot be letters and numbers." When the "Sort Alphabetically" button is clicked, the JavaScript code will activate and sort the words alphabetically. Same goes with the "Sort Numerically" button. I can't seem to get the words/numbers to sort.
HTML:
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>
JavaScript:
function sortAbc() {
var captureText = document.getElementById('textbox');
captureText.sort();
//Help! How to make alert pop up when numbers and letters are typed?
}
function sortNumber() {
var captureNumb = document.getElementByid('textbox');
captureNumb.sort(function(a, b){return a-b});
//Same problem here! How to make alert pop up when numbers and letters are typed?
}

Here a complet live sample.
check for number or words using regular expression (.match)
use the array function sort
function sortAbc() {
var captureText = document.getElementById('textbox');
if (captureText.value.match(/(?:^| )[\d]+(?: |$)/)) {
alert("no digits");
return;
}
var words = captureText.value.split(" ");
captureText.value = words.sort().join(" ");
}
function sortNumber() {
var captureNumb = document.getElementById('textbox');
if (captureNumb.value.match(/[^\s\d]/)) {
alert("no letters");
return;
}
var numbers = captureNumb.value.split(" ");
captureNumb.value = numbers.sort(function (a, b) { return a - b }).join(" ");
}
<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>

Related

Page refreshes after I hit the button

It's a simple counting vowels page. When I insert a word WITH vowels, the result shows up for a second and then page refreshes. When there are no vowels, the output is not as expected and then the page refreshes again. Could anyone help me out please?
function findVow(event) {
event.preventDefault();
var input, result;
// Get value of the input
input = document.getElementById('text').value;
var regex = /[aeiou]/gi;
//unify the case and get the length
var count = input.match(regex).length;
if (count > 0) {
result = "Vowels found : " + count;
} else {
result = "No vowels found";
}
//print the number of vowels if any
document.getElementById("demo").innerHTML = result;
};
<!DOCTYPE html>
<html>
<head>
<title>challenge1</title>
</head>
<body>
<form>
<input id="text" placeholder="Enter a word" type="text" />
<br><br>
<button onclick="findVow()">Count vowels</button>
<br>
<p id="demo"></p>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
You are submitting the form when using default buttons.
The event you wanted is not passed as you expect - it is the button that is passed.
EITHER use type=button OR better: use event.preventDefault as now, but on the submit event
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
var input, result;
// Get value of the input
input = document.getElementById('text').value;
var regex = /[aeiou]/gi;
//unify the case and get the length
var count = input.match(regex).length;
if (count > 0) {
result = "Vowels found : " + count;
} else {
result = "No vowels found";
}
//print the number of vowels if any
document.getElementById("demo").innerHTML = result;
});
<form id="myForm">
<input id="text" placeholder="Enter a word" type="text" />
<br><br>
<button>Count vowels</button>
<br>
</form>
<p id="demo"></p>
add type='button' to the button in the form
<button onclick="findVow()" type='button'>Count vowels</button>
Add type="button" to the button and if you want to capture button event you can do it like this:
$('btnClick').on('click',function(event){
event.preventDefault();
var input, result;
// Get value of the input
input = document.getElementById('text').value;
var regex = /[aeiou]/gi;
//unify the case and get the length
var count = input.match(regex).length;
if (count > 0) {
result = "Vowels found : " + count;
} else {
result = "No vowels found";
}
//print the number of vowels if any
document.getElementById("demo").innerHTML = result;
});
<!DOCTYPE html>
<html>
<head>
<title>challenge1</title>
</head>
<body>
<form>
<input id="text" placeholder="Enter a word" type="text" />
<br><br>
<button class="btnClick" type="button" >Count vowels</button>
<br>
<p id="demo"></p>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

When user inputs a number in a textbox will get an array element dynamically javascript or PHP

i have an array:
var array = ['Mon','Tue','Wen','Thur','Fri','Sat','Sun']; //JS
or i can get it like this:
$arr = array('Mon','Tue','Wen','Thur','Fri','Sat','Sun'); //PHP
i want to get "Mon" dynamically when a user inputs in a textbox num 1, 'Tue' when inputs num 2...
JS or PHP whatever.
please help.
If you just want the value of the array at that index in PHP you can use the form:
$dayName = $arr[$number];
And similarly in javascript
var dayName = array[number];
You need to remember arrays start at index 0, and the user input might start at 1.
If the goal is just get the value of index then return the related value to user I would use javascript..
<html>
<head> </head>
<script type="text/javascript">
function myfunction() {
var array = ['Mon','Tue','Wen','Thur','Fri','Sat','Sun']; //JS
var first =parseInt( document.getElementById("textbox1").value);//store user input for control
//Control user input.
if(first<1 || first > 7 ||!Number.isInteger(first) )
{
alert("Please enter a number between 1 and 7");
}
var textbox2 = document.getElementById('textbox2');//get textbox2
//control if index is defined and assign it to textbox2.value
if(array[first-1]){
textbox2.value= array[first-1];
}
//if not assign empty string
else{
textbox2.value= "";
}
}
</script>
<body>
<input type="text" name="textbox1" id="textbox1" />
<input type="submit" name="button" id="button1" onclick="myfunction()" value="get" />
<br/>
<input type="text" name="textbox2" id="textbox2" readonly="true"/>
</body>
</html>

I need to find the longest word in a sentence using JS

I am having trouble getting my JS to return the longest word when I click on the button. I am not sure what in my JS code I am missing or have put incorrectly, but when I type in three words nothing is given back to me. I have pasted below both my JS and html codes.
HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Longest Word</title>
<link rel="stylesheet" href="../css/easy.css">
<script src="p3-longest.js"></script>
</head>
<body>
<header>
<h1>Longest Word</h1>
</header>
<body>
<form action="demo_form.asp" id="demo_form">
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="Longest Word">
</form>
</body>
</html>
JS:
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length ; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
function init() {
alert('count words');
var countTag = document.getElementById('btn1');
countTag.onclick = longestWord(string);
}
window.onload = init;
try this:
Phrase:
<input type="text" id="input1" name="LongestWord" placeholder="Put Phrase Here">
<br>
<input type="button" id="btn1" value="get Longest Word">
<br/>
Longest Word: <span id='sp1'></span>
<script>
var btn = document.getElementById("btn1");
var in1 = document.getElementById("input1");
var sp1 = document.getElementById("sp1");
btn.onclick = function(){
var vals = in1.value.split(' ');
var val = vals[0];
vals.forEach(function(v){ if(v.length>val.length) val = v;});
sp1.textContent = val;
}
</script>
Fiddle Demo
Add this to your button:
onClick="alert(longestWord(document.getElementById('input1').value))"
It will take the value of input1 and send it to your longestWord-function. Then put up an alert-box with the return value from your function.
I don't see anything particularly wrong with your code ... except for the fact that "I don't see any code here that will ever 'give anything back to you!'" :-)
Presumably, "onload", the init() function dutifully runs ... and setting countTag.onclick to whatever integer value longestWord() might return when given the undefined value of the non-declared non-variable length. (Which is of no good use at all to onclick, which expects a function, not an integer...)
None of which, even if it did work (which it doesn't ...), ever asks the digital computer to, by any means at all, "give anything back to you!"

Validate input field and block characters

Hello guys i have an input field and i want to validate in real time the insterted characters.
I want that this input field accept only letters, number and one blank space. If is inserted for example *, script delete this characters.
Regards
On input filed:
onkeyup="check(this,'onlyletter')" onblur="check(this,'onlyletter')
On JS:
var r={
'onlyletter': // i need correct regular expression
}
function check(o,w){
// i need function
}
I have: Abc123' 123* but i accept Abc123 123
with raw JS:
the clue is in the method transform
<html>
<head>
<script>
function transform(elem) {
var v = elem.value;
var n = "";
//loop it to cut of more than 1 -- e.g. on copy & paste
if(v.length) {
n = v.slice(-1);
if( !isNaN(parseFloat(n)) && isFinite(n) ) {
elem.value = v.substring(0, v.length - 1);
}
}
}
</script>
</head>
<body>
<input
type="text"
name="date"
placeholder="Text only!"
onkeyup="transform(this);"
maxlength="10"
>
</body>
</html>
alternate way using jquery
MASK the textfield to only accept letters. now that can be done a number of ways. one is the query mask plugin
you only need query, query-mask and then it is 1 line of code ;)
demo:
<html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.mask.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//masked input for alphabets only
//constrained to 20 characters in length without spaces
$("#myTextField").mask("SSSSSSSSSSSSSSSSSSSS");
});
</script>
<body>
<br><input type = "text" id="myTextField" name="Text Field"></br>
</body>
</html>

Display the form again?

I want to ask about the form in Javascript.
I want to do a game where the user enters the correct word, then an alert message will appear for this correct word. When the user does the first word correct, the program will display another word (to be corrected). But the problem which I faced that I can't make the form display again to continue the game.
I used:
var d = document.getElementById("form1"); d.style.visibility = "visible";
but it doesn't work!
This is my code:
<head>
<title>Word Decoder</title>
<script type="text/javascript">
function checkWord(word, score)
{
var ok = words[score].valueOf();
var ok1 = document.getElementById("wordid");
if(ok1.value == ok)
{
score ++;
alert("Correct, your score is: " + score);
var d = document.getElementById("form1");
d.style.visibility = "visible";
return false;
}
else
{
alert("Wrong Spelling");
return false;
}
}
</script>
</head>
<body>
<script type="text/javascript">
var words = new Array ("apple", "orange", "banana", "manago", "table");
var reWords = new Array ("alpep", "ergano", "aaabnn", "goamna", "lbeat");
var count = 0;
var score = 0;
"</br>";
</script>
<form id="form1">
<br>
<dir id="displayForm"
style="position: relative;
visibility: visible;
display: block">
<h3><b> <script> document.write(reWords[score]);</script> </b></h3>
<br>
Enter the correct word: <input type="text" value="" id="wordid"/>
<input type="submit"
value="Check Answer ??"
onclick="return checkWord(wordid, score);" />
</dir>
</form>
</body>
Again: I want the game will display a scrambled word and the user must unscrambled the word to move to the other word. The problem is I can't display the form again to make the user unscrambled the second, third etc. words.
Use d.style.display="none" to hide and d.style.display="block" to show.
Think your post got mangled, I don't see where you are hiding it in the first place.. Also, avoid using document.write if you don't need it... inject the element or use .innerHTML if you need to, but not document.write.

Categories

Resources