0

This is my code.

<!-- desktop -->
<div class="section hidden-xs">
  <input name="code" type="text" value="123">
</div>
...
<!-- mobile -->
<div class="section">
  <input name="code" type="text" value="456">
</div>

$('input[name="code"]').val() returns always 123 even I am on Desktop and Mobile.

Is there any way to get the correct value on each device?

Remy Wang
  • 666
  • 6
  • 26
  • 2
    I think if you're using bootstrap, the `hidden-xs` class will only hide the element from view -- the html will still get rendered to the browser. jQuery is selecting the first instance it comes across that matches your selector. Are you able to conditionally render the input or the value? – Damon Dec 03 '19 at 21:10

2 Answers2

1

You should use `:visible to get the value of the visible one.

$('input[name="code"]:visible').val()

Right now you are just getting the value of the first one on the page, even if it's not visible because that's how getters work in jQuery. See Get the sum of the outerHeight of all elements of the same class

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

You can use :visible selector inside your query selector. Bootstrap applies 'display:hidden' via hidden-## class at respective viewport which doesn't remove the element from the DOM.

You can read more about it from Check, using jQuery, if an element is 'display:none' or block on click

Try using:

$('.section:visible input[name="code"]').val()