LemonCake LemonCake - 2 months ago 25
jQuery Question

Checking multiple DOM values

In jQuery I have the following array:

var arr = [{ "id" : "txt1", "value" : 180 }, { "id" : "txt2", "value" : "Text"}];


On the keyup event I want any of these text fields to check if all the fields have the corresponding value from the array.

How can I do this most efficiently?

Answer

Iterate over the array and bind event handler based on the id.

// iterate over the array elements
arr.forEach(function(v) {
  // get element using the id selector and then bind 
  // keyup event for listening
  $('#' + v.id).keyup(function() {
    // compare the current value with array element value
    if (this.value == v.value) {
       // do the rest of code
    }
  })
})

var arr = [{
  "id": "txt1",
  "value": 180
}, {
  "id": "txt2",
  "value": "Text"
}];

arr.forEach(function(v) {
  $('#' + v.id).keyup(function() {
    if (this.value == v.value) {
      console.log('matched');
    }
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt1" />
<input id="txt2" />


Or generate a helper object which holds id as property name and value as it's value. On click event get the value from the array using id property of the element.

// object for holding corresponding value based on id
var obj = {},
  // variable for selector
  sel;

// iterate and generate object and selector
sel = arr.map(function(v) {
  // add object property
  obj[v.id] = v.value;
  // return id selector
  return '#' + v.id;
  // combine the id selectors
}).join();


// bind keyup event
$(sel).keyup(function() {
  // compare the current value and correponding array object value
  if (this.value = obj[this.id]) {
    console.log('matched');
  }
})

var arr = [{
    "id": "txt1",
    "value": 180
  }, {
    "id": "txt2",
    "value": "Text"
  }],
  obj = {},
  sel;

sel = arr.map(function(v) {
  obj[v.id] = v.value;
  return '#' + v.id;
}).join();

$(sel).keyup(function() {
  if (this.value == obj[this.id]) {
    console.log('matched');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="txt1" />
<input id="txt2" />