K20GH K20GH - 1 year ago 85
jQuery Question

jQuery keyup - multiple inputs and pass id name?

I've got a number of input id's in a form as follows (example, not complete form) This is for a Chrome Extension so I cannot modify the form.

<form>
<input id="data-draft-brand-name" />
<input id="data-draft-name-en-us" />
<input id="data-draft-bullet-points-bullet1-en-us" />
<input id="data-draft-bullet-points-bullet2-en-us" />
<input id="data-draft-description-en-us" />
</form>


What I am doing is using keyup on each on the inputs, and then doing the same thing for each id like so:

$( "#data-draft-description-en-us" ).keyup(function() {
var currentVal = $(this).val();
currentVal = currentVal.toLowerCase();

var currentLength = currentVal.length;
currentLength = 2000 - currentLength;

$('#description-count').text(`${currentLength} characters left`);

if(currentVal.indexOf('word') !== -1) {
$('#data-draft-description-en-us').css('border','1px solid red');
$('#data-draft-description-en-us').css('background','red');
} else {
$('#data-draft-description-en-us').css('border','1px solid #a6a6a6');
$('#data-draft-description-en-us').css('background','none');
}
});


As you can see, there will be a lot of repetition. Is there anyway I can pass an array of id's to keyup, and then access the id in the function. Some pseudo code as an example..

$(["#data-draft-brand-name","#data-draft-name-en-us"]).keyup(function(inputID) {
$(inputID).css('border','1px solid red');
}

Answer Source

Here you go with a solution

$("#data-draft-brand-name, #data-draft-name-en-us").keyup(function() {
  var id = $(this).attr('id');
  $('#' + id).css('border','1px solid red');
});

No need to provide square brackets [], id should be separated by comma.

Here you go with jsfiddle https://jsfiddle.net/tjkah0ck/2/

$( "#data-draft-brand-name, #data-draft-name-en-us" ).keyup(function() {
    var currentVal = $(this).val();
        currentVal = currentVal.toLowerCase();
    console.log(currentVal);
    var currentLength = currentVal.length;
        currentLength = 2000 - currentLength;

    $('#description-count').text(`${currentLength} characters left`);

    if(currentVal.indexOf('word') !== -1) {
        $('#data-draft-description-en-us').css('border','1px solid red');
        $('#data-draft-description-en-us').css('background','red');
    } else {
        $('#data-draft-description-en-us').css('border','1px solid #a6a6a6');
        $('#data-draft-description-en-us').css('background','none');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
   <input id="data-draft-brand-name"/>
   <input id="data-draft-name-en-us"/>
   <input id="data-draft-bullet-points-bullet1-en-us" />
   <input id="data-draft-bullet-points-bullet2-en-us" />
   <input id="data-draft-description-en-us" />
</form>

Hope this will help you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download