hegendroffer hegendroffer - 3 months ago 22
HTML Question

How to get text from hidden field in HTML by using jQuery

I need to get the value out of the hidden field using jQuery.
My code, where I hide some value is following:

(...)$.each(response, function (index, value) {
$('#notiContent').append(
$('<li>Nowa wiadomosc : ' + value.Subject +
' od ' + value.Receive + ' data ' + ToJavaScriptDate(value.Date)
+ ' </li>' + '<li style = "display: none;">' + value.IDMessage + '</li>'))
});(...)


and after the value.IDMessage is hidden, I have to get its value again, and pass to another place. The code is following:

(...)$("#notiContent").delegate('li', 'click', function () {
var type = $(this).val(); (...)


Unfortunately the
type
variable gives 0 all the time. When I changed
.val()
to
.text()
or
.html().toString()
it works, but I am not able to get the value out of hidden field.

How can I do this?

Answer

try this out , I think this is what you want.in this example I have shown you how to get the hidden field values from static elements and , how to get hidden field values in dynamic environment.

note : when you want to assign and get values from hidden field, best practice is to use field with type="hidden".

try below two examples and try.good luck.

<html>
<head></head>
<title></title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>


<body>


<h2>Get the value from static element ---> Note : to get the hidden value, best practice is to use <span style="background-color:red;color:white;">input</span> field</h2>

<div id="notiContentone">
  <li style="cursor:pointer;">Nowa Wiadomosc bla bla bla</li>
  <input type="hidden" id="myhidden" value="give_your_value_here">
</div>

<br><br><br><hr>

<h2>Get the value from dynamic elements</h2>
<div id="notiContentwo"></div>


</body>

<script type="text/javascript">

//get the value from static element implement 
$("div#notiContentone li").click(function(){// in here we choose the li element inside the notiContentone
      var hiddenValue = $("#myhidden").val(); //here we get the assinged value for the hidden field.
      alert(hiddenValue);
});


//get the value from dynamic elements
$(document).ready(function(){
  var createelement_li = $('<li style="cursor:pointer;color:orange;background-color:pink;width:400px;">Nowa Wiadomsc bla bla bla </li>');
  var createelement_hidden_input = $('<input type="hidden" id="myhiddentwo" value="dynamically_added_value_here">');
  $("#notiContentwo").append(createelement_li);
  $("#notiContentwo").append(createelement_hidden_input);
   
  $("div#notiContentwo li").click(function(){
    var gettheHiddenValue = $("#myhiddentwo").val();
    alert(gettheHiddenValue);
  });

});

</script>

</html>

Comments