Paul Paul - 1 year ago 56
Javascript Question

Getting the value of a name array

I am wanting to store more than one value into option inputs. I searched around and figured out how to do this. However, what I could not find is how I get the value out of the name array. As you can see in the snippet, I have this in a change event and write the value to

#result
. I am wanting to write the value of the
years[]
to
#years
.

How can I get the value of the name array?

In case you want one, here is a fiddle.



$('#tp-frequency').on('change', function () {
var templates = $('#tp-frequency option:selected').val();
$('#result').html(templates);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="tp-frequency">
<option value=''disabled selected>Please choose option</option>
<option class="choice" value='3' name="years[3]">3 years - 3 cards</option>
<option class="choice" value='4' name="years[2]">2 years - 4 cards</option>
<option class="choice" value='2' name="years[5]">5 years - 2 cards</option>
</select>
<p id="result"></p>
<p id="years"></p>




Answer Source

If you just want to get number that is inside name attr you can use attr('name') of selected option and then regular expression to get number.

$('#tp-frequency').on('change', function() {
  $('#result').html($('#tp-frequency option:selected').val());
  $('#years').html($(this).find(':selected').attr('name').match(/\[(.*?)\]/)[1])
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="tp-frequency">
  <option value='' disabled selected>Please choose option</option>
  <option class="choice" value='3' name="years[3]">3 years - 3 cards</option>
  <option class="choice" value='4' name="years[2]">2 years - 4 cards</option>
  <option class="choice" value='2' name="years[5]">5 years - 2 cards</option>
</select>
<p id="result"></p>
<p id="years"></p>

You can also create custom data attribute called data-years and then you can get its value using data("years")

$('#tp-frequency').on('change', function() {
  $('#result').html($(this).find(':selected').val())
  $('#years').html($(this).find(':selected').data('years'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="tp-frequency">
  <option value='' disabled selected>Please choose option</option>
  <option class="choice" value='3' data-years="3">3 years - 3 cards</option>
  <option class="choice" value='4' data-years="2">2 years - 4 cards</option>
  <option class="choice" value='2' data-years="5">5 years - 2 cards</option>
</select>
<p id="result"></p>
<p id="years"></p>

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