2

How to get the array of my input using getElementsByClassName? Is it possible to get that? Because I was planning to get the array of all of the classnames of my input and compare whether there are same element or not, if there are same value inside the array, it will alert user they had enter invalid input, it kind like a validation. Here are my code.

<table class="table table-responsive table-striped table-hover ">
    <thead>
        <tr>
            <th>#</th>
            <th colspan='2'>L</th>
            <th colspan='2'>O</th>
            <th colspan='2'>G</th>
            <th colspan='2'>B</th>
        </tr>
    </thead>
    <tbody>
        <tr class="info">
            <td width="30px">1</td>
            <td width="200px">Likes Authority</td>
            <td  width="75px;">
                <select class="r1" style="position: absolute; z-index:9999;"
                    onmouseover="this.size=this.options.length"
                    onmouseout="this.size=1" onchange="this.size=1"  name="qtyL" >  
                    <option value="0">-</option>
                    <option value="1" >1</option>
                    <option value="2" >2</option>
                    <option value="3" >3</option>
                    <option value="4" >4</option>
                </select>
            </td>
            <td  width="200px">Enthusiastic</td>
            <td  width="75px;"> 
                <select class="r1" style="position: absolute; z-index:9999;"
                    onmouseover="this.size=this.options.length"
                    onmouseout="this.size=1" onchange="this.size=1"  name="qtyO" >  
                    <option value="0">-</option>
                    <option value="1" >1</option>
                    <option value="2" >2</option>
                    <option value="3" >3</option>
                    <option value="4" >4</option>
                </select>
            </td>
            <td width="200px">Sensitive Feelings</td>
            <td width="75px;">
                <select class="r1" style="position: absolute; z-index:9999; "
                    onmouseover="this.size=this.options.length"
                    onmouseout="this.size=1" onchange="this.size=1"  name="qtyG" >  
                    <option value="0">-</option>
                    <option value="1" >1</option>
                    <option value="2" >2</option>
                    <option value="3" >3</option>
                    <option value="4" >4</option>
                </select>
            </td>
            <td  width="180px">Likes Instructions</td>
            <td width="75px;">
                <select class="r1" style="position: absolute; z-index:9999; "
                    onmouseover="this.size=this.options.length"
                    onmouseout="this.size=1" onchange="this.size=1"  name="qtyB" >  
                    <option value="0">-</option>
                    <option value="1" >1</option>
                    <option value="2" >2</option>
                    <option value="3" >3</option>
                    <option value="4" >4</option>
                </select>
            </td>
        </tr>
    </tbody>
</table>

<script>
function validateNresult()
{
    var totr1=document.getElementById("totalr1").value;

    var arr1=document.getElementsByClassName("r1");

    var allr1=arr1.value;

    Array.prototype.allValuesSame = function() 
    {
       for(var i = 1; i < this.length; i++)
       {
          if(this[i] !== this[0])
            alert("Invalid input");
       }
      return true;
    }

    var checkarr1=allr1.allValuesSame();

}

Maybe my logic is wrong, but the importance part is how do get all the value of classname which is r1? Thank you.

4
  • 2
    getElementsByClassName does not return an array. Try calling Array.from(allr1).allValuesSame(). However, I think your basic logic is flawed. You are checking if all elements returned by getElementsByClassName are the same, but they will never be. Commented May 11, 2017 at 4:35
  • I try already, but still can't get anything :( Ohh, that's means I should another method instead of this right? Thank you. Commented May 11, 2017 at 4:44
  • 1
    getElementsByClassName returns a NodeList. Not quite the same as an array. Array.from isn't supported everywhere. Commented May 11, 2017 at 4:47
  • @Phix Thanks, btw, do you have any suggestion for me about what I am doing? Because I had 10 row to verify. Commented May 11, 2017 at 4:49

5 Answers 5

2

Update

To go one step further I added:

  1. A <form> to which we register the change event to with addEventListener()

  2. When a new value is added to any <input> the callback (fancy name for a function the gets called on an event), the indexOf() method will try to find a match between the new value and the values of the array created previously.

  3. If there is a match, then an alert will fire and if there isn't a match then false is returned (basically it doesn't do anything until a matching value has been entered on any of the inputs).


OLD

  1. Use document.querySelectorAll('.className') to gather all elements assigned to the .whateverClass into a NodeList
  2. Next use the Array.from() to convert that NodeList into an array.
  3. From this point on you deal with arrays and the most versatile array method to use is Array.prototype.map().

Demo

const kArray = Array.from(document.querySelectorAll('.K'));

console.log(kArray);

const arrayOK = kArray.map(function(kay, idx) {
  var ok = kay.value;
  return ok;
});

console.log(arrayOK);

var FK = document.getElementById('formK');

FK.addEventListener('change', function(evt) {
  if (evt.target !== evt.currentTarget) {
    var tgt = evt.target.value;
    if (arrayOK.indexOf(tgt) > -1) {
      alert('Hey! That\'s already been entered, try something different.');
    }
    return false;
  }
});
.as-console-wrapper {
  max-height: 75px !important;
}
<form id='formK'>
  <input class='K' value='0'>
  <input class='K' value='b'>
  <input class='K' value='8'>
  <input class='K' value='f'>
  <input class='K' value='6'>
  <input class='K' value='c'>
  <input class='K' value='1'>
  <input class='K' value='2'>
  <input class='K' value='7'>
  <input class='K' value='5'>
  <input class='K' value='9'>
  <input class='K' value='d'>
  <input class='K' value='3'>
  <input class='K' value='a'>
  <input class='K' value='e'>
  <input class='K' value='4'>
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, this is nice :D but how should I compare the result if I do it like this way?
@Beginner Just added the .map() method to answer. to see results scroll down the console window.
1
var v = document.getElementsByClassName('r1');
var len = v.length - 1;
var val = v[0].value;
var same = true;
while(len > 0)
{
    if (val != v[len].value)
    {
        same = false;
        break;
    }
    len--;
}

Comments

1

var arr1=document.getElementsByClassName("r1");

This returns a NodeList object. The NodeList object represents a collection of nodes.

var allr1=arr1.value;

This is not valid. You should iterate over this object and then compare values of its items.

for (var i = 0; i < arr1.length; i++) {
    console.log(arr1[i].value);
}

2 Comments

Thanks, but how should I iterate the array?
I'm sorry I updated the answer. It's a NodeList object actually.
0

The below code should do the trick:

  let select_element = document.getElementsByClassName("r1"); //puts all the select elements into an array
  let values = []; //create a new array that will store the values of each select

  for (let i = 0; i < select_element.length; i++){
  //loop through the array to get all the chosen select values
    values.push(select_element[i].options[select_element[i].selectedIndex].value); 
  };

  //this check if any of the values are duplicated and alerts the user if they are
  sorted_array = values.sort();
  for (let i = 0; i < sorted_array.length; i++){
    if (sorted_array[i + 1] == sorted_array[i]){
      alert("duplicates exist");
      break;
    };
  };

The working JSFiddle can be found here: https://jsfiddle.net/darkisa/38u1t564/

Of course, you can also just check to see if all the values add up to more or less than 10. Since you need each select value to be unique and since you only have four of them that can have a value of 1 to 4, after you sum all of the values, anything that does not equal 10 means there is a duplicate somewhere.

1 Comment

Yeah! This is exactly what I want. Thank you!
0

You can use spread operator as well.

[...document.getElementsByClassName('some-class-name')].map(e => e.innerText)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.