Is there a way for JSP to get value from id element in a html? Just like what javascript doing document.getElementById.value

Dani AI

Generated

JSP runs on the server before the HTML ever reaches the browser. The DOM (and any id values you can read with JavaScript) exists only in the browser. So JSP cannot call document.getElementById(...). To get a value from the page to JSP/servlet code, you must send it in an HTTP request. That is why and are pointing you toward request parameters. The id attribute is for client-side lookup; the server receives values by parameter names or JSON keys.

If you do not want to use a traditional <form>, send the value with JavaScript. For example, post it to a servlet (recommended) or JSP endpoint as application/x-www-form-urlencoded:

<input id="city" type="text">
<script>
  const val = document.getElementById('city').value;
  fetch('saveCity', {
    method: 'POST',
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    body: 'city=' + encodeURIComponent(val)
  });
</script>

Server-side you read it exactly as suggested:

String city = request.getParameter("city");

If you just want to navigate to another JSP with the value, put it in the query string:

const val = document.getElementById('city').value;
window.location = 'view.jsp?city=' + encodeURIComponent(val);

Then render it in JSP using EL (avoid scriptlets):

${param.city}

Practical tips for : give your input a name when possible, even if you submit via JavaScript; that keeps forms and non-JS fallbacks easy. If the value is not from an <input> (e.g., a <div>), read its text with JS and send it as shown above. In short: you cannot read an element by id on the server; you must send its value to the server as part of the request.

Recommended Answers

All 3 Replies

Why do you want to do this? There is request.getParameter("name") where the name is the name of the input you have. What do you want to take? The parameters of the forms that was submitted or something else?

I do not want to use form, instead, I would like to use id only. Can JSP take ID element value?

why don't you want to use a form? that is exactly designed to communicate the values of the fields to servlets.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.