首页 > 解决方案 > How to access and store the input hidden field of a jsp page which is changing dynamically on button clicks?

问题描述

here is the script that in the jsp page

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#trno=${track.track_no}" class="album-poster" data-switch="${count}" data-value="${track.track_no}">Play Button</a>

<input type="hidden" id="trnum" name="trnum" value="">

here is the js script that I wrote

$(".album-poster").on('click', function(e) {

  var dataSwitchId = $(this).attr('data-switch');
  var datavalue = $(this).attr('data-value');

  //Add value to hidden field.
  $('#trnum').val(datavalue);
  
  //Show hidden field value
  console.log($('#trnum').val())

  ap.list.switch(dataSwitchId);

  ap.play();

  $("#aplayer").addClass('showPlayer');
});

here the anchor tag is in the foreach loop such that of different values will be there in the data-value attribute in the anchor tag

here I want to store these data values to the database such that when I'm trying to access like

$(".album-poster").on('click', function(e) {

  var dataSwitchId = $(this).attr('data-switch');
  var datavalue = $(this).attr('data-value');

  //Add value to hidden field.
  $('#trnum').val(datavalue);
  
  //Show hidden field value
  console.log($('#trnum').val())
  ****<%System.out.println(request.getParameter("trnum"));%>****

  ap.list.switch(dataSwitchId);

  ap.play();

  $("#aplayer").addClass('showPlayer');
});

in the highlighted code that I'm printing in the console it is printing null I need these values which are clicked to store them into the database and how can I get access them and store into the java list.

how can I do it ?

标签: javascriptjavajqueryjspservlets

解决方案


You need to submit your data to server to access request object .One way to achieve this is using ajax .You can send the datavalue which is clicked by user to backend and save it .So your jquery code will look like below :

 $(".album-poster").on('click', function(e) {
    
      var dataSwitchId = $(this).attr('data-switch');
      var datavalue = $(this).attr('data-value');
 //chcking if datavalue is not null
      if (datavalue != null) {
        $.ajax({
          url: "your_backend_url", //url or servlet
          type: "GET",
          data: {
            trnum: datavalue
          }, //pass data to backend access same using request.getParameter("trnum") in doGet method servlet
          success: function(data) {
            console.log("done");//this will print on success in browser console
          }
        });
    
      }
      ap.list.switch(dataSwitchId);
    
      ap.play();
    
      $("#aplayer").addClass('showPlayer');
    });

At backend get that data which is passed by user using request.getParameter("trnum") and do further operations .


推荐阅读