passing names into an array and sorting them - javascript

what im tryng to do is enter a first and last name into a textarea, once the "enter name" button is hit the names will go into an array, where they are sorted, then put back into a string and displayed in the "output" box. everytime a name is entered it will be added into the same array and sorted.
I was able to get the names into an array, and displayed in the output box, but i cant get it to add names to the list, or sort them alphabeticly. it just replaces them. I thought i could use push to add the names, but it doesnt seem to work. Any help would be very appreciated. Thanks in advance.
here is what i have so far:
<body>
<p>
<label for="name">Enter First and Last Name: </label>
<input id="name" name="name" />
<input type="button" id="addNameBtn" value="Enter Name" />
<input type="button" id="clearBtn" value="Clear Output" />
</p>
<p>
<label for="output">Output:</label><br />
<textarea cols="20" rows="15" id="output" ></textarea>
</p>
<script type="text/javascript" src="js/main.js"></script>
<script type="text/javascript">grabText();</script>
</body>
</html>
`function grabText(){
var arr = [];
var arr2 =[];
var len = arr.length;
for (var i = 0; i<len; i++);
{
var txt = document.getElementById('name').value;
var textArea = document.getElementsByTagName('textarea');
if (txt !=="")
{
arr.push(txt);
}
}
arr2.push(arr);
arr2.sort();
var arrStr = arr2.join();
textArea[0].value = arrStr;
document.getElementById('name').value = '';
}
var btn = document.getElementById('addNameBtn');
btn.onclick = grabText;`

Playground
var textArea = document.getElementById('output');
var name = document.getElementById('name');
var btn = document.getElementById('addNameBtn');
var arr = [];
// Why whould you need arr2? to store the original?
function grabText(){
var txt = name.value;
if (txt !==""){
arr.push(txt);
}
arr.sort();
var arrStr = arr.join();
textArea.value = arrStr;
name.value = '';
}
btn.onclick = grabText;

A few things:
The for statement for (var i = 0; i<len; i++); - notice the very last character - a semi-colon. This for statement does very little - it evaluates and increments i, not the statements which follow.
var len = arr.length; syntax is correct, but the problem is arr is declared immediately before it and has a length of zero.
var arr2 stores the contents between invocations, but it has function scope and needs to be moved outside of the grabText function.

Related

getElementByID.readOnly in array

Im trying to create a list of input ID's and use it in array, to make them readOnly - but the result is error -> "cannot read property 'readOnly' of null".
Can you give me a hint what I should change?
script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function(){
var index, len;
$.get('/SomeList.txt', function(data){
var SomeList = data.split('\n');
for (index = 0, len = SomeList.length; index < len; index++) {
document.getElementById(SomeList[index]).readOnly = true;
}
});
});
});
</script>
and txt file contains name of input ID:
TextFieldName
TextFieldEmail
TextFieldDepartment
TextFieldOffice
Assuming you have some elements with the given IDs you must check if the element exists first before doing
document.getElementById(SomeList[index]).readOnly = true;
so replace that line with
var myElement = document.getElementById(SomeList[index]);
if(myElement == null) {
return;
}
myElement.readOnly = true;
That should work like following example where the IDs come from an array and the second one will not mach because of xxxxx so it's not readonly. But all the others are.
var dataArray = [
'TextFieldName',
'TextFieldEmailxxxxx',
'TextFieldDepartment',
'TextFieldOffice'
];
dataArray.forEach(function(id){
var myElement = document.getElementById(id);
if(myElement == null) {
return;
}
myElement.readOnly = true;
});
<input id="TextFieldName" type="text">
<input id="TextFieldEmail" type="text">
<input id="TextFieldDepartment" type="text">
<input id="TextFieldOffice" type="text">
var id_array=["email","country"];
for (i = 0; i <id_array.length; i++) {
document.getElementById(id_array[i]).readOnly = true;
}
Email: <input type="text" id="email" value="test#mail.com"><br>
Country: <input type="text" id="country" value="Norway" >
it is working fine in my case.
i think there may be whitespace in your array items because your are reading them from file.so try to trim array items.
and make sure you assign id's to input elements

Nothing appears on console in chrome,taking information from form

I'm creating a simple string reverse project.
I want the user to enter input, then that input will be displayed below the text box in reverse order.
<form id = "frm1">
<input type="text" id="userInput"=> give me input</input>
<button onclick="strRev()">Submit</button>
</form>
<script type="text/javascript">
function strRev(str){
str = document.getElementById("userInput").toString().value;
console.log(str);
var originalStr = str.split("");
console.log(originalStr);
var finalArray = [];
var j = 0;
for(i = originalStr.length-1; i >= 0; i--){
finalArray[j] = originalStr[i];
j++;
}
for(k = 0; k <finalArray.length; k++){
document.write(finalArray[k]);
}
}
</script>
When pressing submit, the information in the box is what should be reversed
Nothing happens on submit and nothing appears in console to debug.
Try the below code:
str = document.getElementById("userInput").value;
onclick="strRev()"
and you are calling
function strRev(str) // function with one argument, must be showing error in console
Add type="button" in your button input, that way the form won't refresh
<button type=button onclick="strRev()">Submit</button>
You will probably be able to continue solving your other problems after that.
You have an error in your html here <input type="text" id="userInput"=>
it should be <input type="text" id="userInput">
also fetching the value of input should be like this
str = document.getElementById("userInput").value;
After applying these changes you will see the output in console

Print an array from user input in JavaScript

I am trying to create an array from user input in JavaScript and display the latest array as the numbers are appended to the array. The numbers are not getting printed.
Kindly help.
HTML part :
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<form id = "arrays" method = "" onsubmit="arrAppend(document.getElementById('num').value);">
<input type ="submit" value="Append" />
</form>
JavaScript part :
<script>
var myarr = [];
function arrAppend(num) {
myarr.push(+num);
text = "";
for (var x = 0; x< myarr.length; x++) {
text += myarr[x];
}
console.log(text);
}
</script>
This is working :
HTML :
<input type = "text"
id = "addNumber" />
<input type = "button"
id = "addToArray"
value = "Append"
onclick = "arrAppend();" />
JavaScript :
function arrAppend() {
myarr[x] = document.getElementById('addNumber').value;
alert("Element : "+myarr[x]+" is added at index "+x);
x++;
document.getElementById('addNumber').value = "";
<textarea form = "arrays" cols = 10 rows = 2 id = "num">
</textarea><br />
<input type ="submit" value="Append" onclick="arrAppend(document.getElementById('num').value);"/>
why do you need a form? are you submitting something to the server? when you submit a form it will clear the global array as well.

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

Is possible to get all the values of all the <input>s inside a div?

<div id="test">
<input type="text" value="10" size="3">
<input type="text" value="0" size="3">
<input type="text" value="25" size="3">
<input type="text" value="0" size="3">
</div>
I want a function to get all the values of the inputs. I was trying with this:
var inputs = $("test :input");
But I don't know how to go from there or even if it's correct.
Thank you
You can do this:
var inputs = new Array();
inputs = $('#test :text').map(function(){
return this.value;
}).get(0);
Or:
var inputs = new Array();
inputs = $('#test :text').each(function(){
inputs.push(this.value);
});
You can access each value like this:
alert(inputs[0]);
alert(inputs[1]);
alert(inputs[2]);
// and so on
The :text refers to inputs of type text.
$("#test :input").each(function(){
var value = $(this).attr("value"); //Save value in an array or something
});
Do you mean like this?
var values = [];
$('input').each(function(index, element){
values.push($(element).val());
});
Non-jQuery version:
var values = [];
var inputs = document.getElementById("test").getElementsByTagName("input");
for (var i = 0, len = inputs.length; i < len; ++i) {
values.push(inputs[i].value);
}

Categories

Resources