jQuery how to get indexed text value of <select> form field and and apply min max lengths to input textbox

StackOverflow https://stackoverflow.com/questions/23138573

  •  05-07-2023
  •  | 
  •  

Frage

I have an indexed select list (goes up to ~5 instances, from 1 to 5) as follows:

<div>
<label for="ccType[1]">Credit Card Type</label>
<select name="ccType[1]" id="ccType[1]" class="jq__creditCardTypeChange">
<option value="0">No Card Selected</option>
<option value="1">American Express</option>
<option value="2">Discover</option>
<option value="3">MasterCard</option>
<option value="4">Visa</option>
</select>
</div>

And I have a corresponding indexed textbox (matches select list instance) as follows:

<div>
<label for="creditCardNumber[1]">Credit Card Number</label>
<input type="text" value="" name="creditCardNumber[1]" id="creditCardNumber[1]" class="jq__ccMinMaxLengthControl">
</div>

How can I use jQuery to test if "American Express" is selected and set the min & max lengths on the creditCardNumber[] textbox to a certain value?

Here is what I have started with:

    $(document).on('change', '.jq__creditCardTypeChange', function(event) {

      var triggerID = event.target.id; // get the id that triggered the event

      var nStart = triggerID.indexOf('[') + 1;
      var nEnd = triggerID.indexOf(']');
      var i = triggerID.substring(nStart, nEnd); // get the index of the id that triggered the event

      var el = $('[id="' + event.target.id + '"]');

      if (el.val() == '1') {
        $('#creditCardNumber\\['+ i +'\\').attr('minlength', '15');
        $('#creditCardNumber\\['+ i +'\\').attr('maxlength', '15');
      }
      else {
        $('#creditCardNumber\\['+ i +'\\').attr('minlength', '16');
        $('#creditCardNumber\\['+ i +'\\').attr('maxlength', '16');
      }

    }); // end .on('change') Credit Card Number Length

So, I prefer to test for "American Express as the selected value rather than "1" because the index for AmEx could change at some point but the text itself would not change. And, any suggestions for improving the script performance would be a great learning experience for me. Thanks

War es hilfreich?

Lösung

You can get the text of the selected option like this:

var el = $('option:selected', this);
if (el.text() == 'American Express') {
    // rest of your code...
}

Also, using indexed id or class attributes leads to ugly code, such as you have dissecting the id string for square brackets. You can use DOM traversal to get related elements. If you can post a full HTML example I can give you more information on how to do this.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top