coder
coder

Reputation: 6233

How do you access a model attribute in jquery?

I'm adding an object to my ModelAndView in spring and forwarding to my jsp view. I need to access that object in my jquery. Is this possible without first putting the value in a hidden field? How is it done?

Upvotes: 13

Views: 52464

Answers (3)

Muhammad Saimon
Muhammad Saimon

Reputation: 281

In java controller,

model.addAttribute("key", "value");

inside jQuery,

let name = [[${key}]];
console.log("modelAttributeValue: ", name)

Upvotes: 2

thil
thil

Reputation: 51

probably, you can save the model attribute in a hidden field and access it onload as below.

$(document).ready(function(){
  var modelAttr = $("#modelAttr").val();
  alert(modelAttr);
}

input type="hidden" id="modelAttr" name="modelAttr" value="${modelAttribute}"/>

Add c:out around the ${modelAttribute} in the jsp.

Upvotes: 4

Bozho
Bozho

Reputation: 597432

<script type="text/javascript">
   var modelAttributeValue = '${modelAttribute}';
</script>

This will resolve the model attribute added by model.addAttribute("modelAttribute", value)

Upvotes: 29

Related Questions