test1001 test1001 - 3 months ago 15
jQuery Question

JQuery - random code generator on selecting data in select options without if condition

I'm writing the code for generating random code using jquey. it was working fine. but i used if condition to achieve that. what i need is to write that function without if conditions... how can i get that ?



function getcodes()
{

var input_data = $('.getvalue').val();
var select_data = $('.control').val();
if(select_data == "Binary" )
{
select_data = "BY";
}
else if(select_data == "Alpha" )
{
select_data = "AA";
}
else if(select_data == "AlphaNumeric" )
{
select_data = "AN";
}
else if(select_data == "Numeric" )
{
select_data = "NC";
}
else
{
select_data ="";
}

$('.disabled').val(input_data + select_data);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selector">
<div class="get-values">

<input type="text" value="" class="getvalue">
<select class="control">
<option value="">select</option>
<option value="Binary">Binary</option>
<option value="Alpha">Alpha</option>
<option value="AlphaNumeric">AlphaNumeric</option>
<option value="Numeric">Numeric</option>
</select>
<input type="button" value="getcode" class="getcode" onclick="getcodes()">
<input type="text" value="" class="disabled" disabled>
</div>
</div>




Answer

If you can change value of options, use it, else - use data api

function getcodes() {
  $('.disabled').val($('.getvalue').val() + $('.control option:selected').data('val'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selector">
  <div class="get-values">

    <input type="text" value="" class="getvalue">
    <select class="control">
          <option value="" data-val="">select</option>
          <option value="Binary" data-val="BY">Binary</option>
          <option value="Alpha" data-val="AA">Alpha</option>
          <option value="AlphaNumeric" data-val="AN">AlphaNumeric</option>
          <option value="Numeric" data-val="NC">Numeric</option>
      </select>
    <input type="button" value="getcode" class="getcode" onclick="getcodes()">
    <input type="text" value="" class="disabled" disabled>
  </div>
</div>