Alex Alex - 6 months ago 19
jQuery Question

How to make sure multiple inputs each have a unique value

I have six input boxes which will be updated dynamically. I want to force the user to have a unique number in each of the inputs before they can submit.

Below I have the following code;

HTML:

<input type="text" value="10" class="check" />
<input type="text" value="8" class="check" />
<input type="text" value="9" class="check" />
<input type="text" value="10" class="check" />
<input type="text" value="12" class="check" />
<input type="text" value="11" class="check" />
<input type="submit" id="check" value="Submit">


JS:

var inputs = [];

function validateInput() {
$(".check").each(function(i, elem) {
if (inputs.hasOwnProperty(elem.value)) {
inputs[elem.value] += 1;
} else {
inputs[elem.value] = 1;
}
});
}

$("#check").click(function() {
validateInput();
console.log(inputs)
if (inputs.length <= 5) {
console.log("fail")
} else {
console.log("success!")
}
})


Currently
var inputs
outputs this in the console;

[8: 1, 9: 1, 10: 2, 11: 1, 12: 1]

I was hoping there would be a way for me to count the number of objects, so I could say if the number of objects is less or equal to 5 you have to go back and fix it, else if it's six you can proceed.

Hopefully this makes sense?

Hoping it's an easy fix!

fiddle

Answer

Use Object to store key/value pairs . You can use Object.keys().length to get no. of properties present.

var inputs = {};

function validateInput() {
  $(".check").each(function(i, elem) {
    if (inputs.hasOwnProperty(elem.value)) {
      inputs[elem.value] += 1;
    } else {
      inputs[elem.value] = 1;
    }
  });
}

$("#check").click(function() {
  validateInput();
  console.log(inputs)
  if (Object.keys(inputs).length <= 5) {
    console.log("fail")
  } else {
    console.log("success!")
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" value="10" class="check" />
<input type="text" value="8" class="check" />
<input type="text" value="9" class="check" />
<input type="text" value="10" class="check" />
<input type="text" value="12" class="check" />
<input type="text" value="11" class="check" />
<input type="submit" id="check" value="Submit">