简体   繁体   中英

Validation in jsp using javascript

'

<TD CLASS="input-label" VALIGN="top">A:</TD>    
out.println(widget_renderer.getEditableField("A"));    
<TD CLASS="input-label" VALIGN="top">B:</TD>    
out.println(widget_renderer.getEditableField("B"));

I want to make the attribute B field required based on the values entered for attribute field A. Also would liek to validate it and print error message I did the below on jsp page:-

<TD CLASS="input-label" VALIGN="top">A:</TD>    
out.println(widget_renderer.getEditableField("A"));    
String ppn = (String)dataBean.getItemEntityData().get("A");    
System.out.println(dataBean.getItemEntityData().get("A"));    
if (ppn != null && (ppn == "A1" || ppn == "A2" || ppn == "A3" || ppn == "A4"))
{
>
<TD VALIGN="top"><SPAN  CLASS="req-indicator">*</SPAN></TD>
< } >
,<TD CLASS="input-label" VALIGN="top">B:</TD>    
out.println(widget_renderer.getEditableField("B"));

Please suggest

The original JSP code is irrelevant. Open the JSP page in your webbrowser, rightclick the page and choose View Source . All this generated HTML code which you now see is now really relevant for JavaScript since that's the only what it can see and access.

It's unclear what "widget" framework you're using since you didn't tell/tag anything about it, while that's unrelated to JSP. Anyway, if it has done its job right, then you should see <input> elements with an id attribute in the generated HTML code like so:

<input type="text" id="someId">

Now, in the JS code you can easily grab elements from the HTML DOM using document.getElementById() .

var inputElement = document.getElementById('someId');

If it's an input element, then you can get its value as follows:

var inputValue = inputElement.value;

You can compare string values in JavaScript as follows:

if (inputValue == 'foo') { 
    // Value is foo.
} else {
    // Value is not foo.
}

Note that this is not the way to compare strings in Java! You would rather use String#equals() for this.

You can also grab a different element from the DOM, eg a <div id="message"> which you've added yourself.

var messageElement = document.getElementById('message');

You can in turn set some text in its body as follows:

messageElement.firstChild.nodeValue = 'some message';

Do the math :)

See also:


By the way, the "style" you're using in your code is pretty old fashioned. It might happen that you inherited a legacy project, okay, but that 90's style is really not the right way to start HTML/JSP with nowadays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM