'
<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, e.g. 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:
W3Schools JavaScript tutorial
W3Schools HTML DOM tutorial
Essential JavaScript - tutorial
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.
Related
Note: I'm not a javascript expert so please be kind. I continue to get a Null value from a variable that I believe is triggered from a DOM event. I have two functions. One looks at form text whether it is present, if not it pulls from another existing variable so it should never be empty/null. However when I try to pull these variable results into another function it returns Null. I'm trying to have a form where the user enters a filename (picture name) and the script inserts the rest of the string around this filename. Allowing the user to not have to enter a full url path and especially not html code. This works if I put the variables in manually as text strings, I'm just not able to get anything other than null from that variable inside this function.
I thought this was due possibly to the DOM event but I tried everything I could find on here with no success. I even tried making the variable global which didn't help. I'm trying to concatenate text before and after this other variable data. If I put these other variables in as string text it works fine, but whenever I try to pull the other variable outside of the function I get Null. I've mascaraed my java at this point. I've been coming back to this the past few days trying different thing with no success. Thank you.
// This checks for radio toggle and writes html(var string) if on
function output_headshot() {
var text1 = "<td border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><br><img src=\"https://url/Headshots/";
var text2 = headshot_path;
var text3 = "\" width=\"154\" height=\"154\"></td>";
var headshot_html = text1 + text2 + text3;
$(".headshot_element").show();
$(".headshot_element").html(headshot_html);
// Monitor logo option to hide/show
$(".input_headshot input[type=radio]").on("change", function(){
if(document.getElementById('headshot_show').checked) {
$(".headshot_element").show();
$(".headshot_element").html(wpe_headshot_html);
} else if(document.getElementById('headshot_hide').checked) {
$(".headshot_element").hide();
$(".headshot_element").html('');
}
updateHtmlSigRaw()
});
}
output_headshot();
// This looks at form contents, if empty pulls from another static variable employee.headshot_location
// This will display the text string on HTML using this: <span class="output_headshot_location"></span>
$(".input_headshot_location input").on("change keyup paste", function(){
var headshot_location = $(this).val();
if(headshot_location) {
$("span.output_headshot_location").html(headshot_location)
} else {
$("span.output_headshot_location").html(employee.headshot_location);
}
updateHtmlSigRaw()
});
EDIT: Added for context
// Place raw HTML of each version into appropriate containers
function updateHtmlSigRaw() {
get_html_signature_full_visual = document.getElementById("signature-full-visual").innerHTML;
get_html_signature_horizontal_visual = document.getElementById("signature-horizontal-visual").innerHTML;
$("#signature-full-html textarea").text(get_html_signature_full_visual);
$("#signature-horizontal-html textarea").text(get_html_signature_horizontal_visual);
}
This is starting normal variables.
// Start Normal variables
var employee = {
headshot_location: "TimC-Rounded-SQ-SM.png"
}
The following is how I'm placing in HTML for the image to toggle off an on.
<td height="237" valign="middle" style="padding:0px 10px 0px 0;">
<div class="headshot_element" onClick="document.location = 'https://url'" border="0" cellpadding="0" cellspacing="0" >
Next is the form for input.
<div class="input_headshot_location form-group">
<label>Headshot Location</label>
<input class="form-control" type="text" name="headshot_location" placeholder="Enter Full Filename">
</div>
Expecting to pull string from variable to add/concatenate to other static string variables to insert html into page using Span class or Div class.
I have a table cell that contains HTML, e.g.,
<td id="test">something™ is here</td>
I have an input field that I want to use to edit the HTML inside the table cell, e.g.,
<input type="text" id="editor" value="">
I need to get the string something™ is here from the table cell so I can put it into the <input> for editing. I have tried
var txt=$("#test").text();
var htm=$("#test").html();
Both of them are returning "something™ is here" rather than the raw HTML - I have a breakpoint in Firebug immediately after setting the two test values, and that's what I'm seeing.
Reading the jQuery documentation, I really expected the .html() method to return the raw HTML I'm looking for, but that's not what is happening.
I know that Javascript doesn't have an encoder like PHP's htmlspecialchars() function and that I have to work around that, but all four of these operations produce the same results:
var enchtm=$("<div/>").text(htm).html();
var enctxt=$("<div/>").text(txt).html();
var htmenc=$("<div/>").html(htm).text();
var txtenc=$("<div/>").html(txt).text();
Every permutatation puts "something™ is here" in the editfield, not the raw HTML.
How do I get the string something™ is here from the table cell into the <input> so I can edit it?
It doesn't exist. Entities are decoded before the DOM is produced, and .html() (which is really just a wrapper for the innerHTML property) doesn't re-encode it because there's no reason for it to -- something™ is exactly as valid a representation of the HTML as something™ is. There is no "completely raw" (pre-character-decoding) view of the HTML provided by the browser.
Suggestion: provide the initial value as the value attribute of the input, instead of having it as the content of the div, so that the flow of data is always one way and this problem doesn't occur.
As the other answers have indicated, what I was trying to do is literally impossible - the original HTML source code that was used to populate the table cell no longer exists in the browser by the time it gets written to the DOM document.
The way I worked around this was using a title attribute on the table cell, e.g.,
// in the PHP/HTML source document
<?php $text='something™ is here'; // the contents of the table cell ?>
<td id="test" title="<?php echo htmlspecialchars($text) ?>"><?php echo $text ?></td>
Now the Javascript is relatively simple:
$("#editor").val($("#test").attr("title"));
The problem with this is that some of these table cells are supposed to have tooltips - which use the title attribute - and some are not. Fortunately for me, the table cells that may contain HTML that needs to be edited never need to show a tooltip, and the ones that show tooltips have simple text that can be retrieved using the .text() method. I can set a class attribute on the cells that need a tooltip, e.g.,
<td class="tooltipped" title="This is a tooltip">Hover here!</td>
I can then use jQuery's .not() method to suppress the tooltips on the cells were the title is being used for storing encoded HTML:
// suppress browser's default tooltip on td titles
$("td[title]").not(".tooltipped").mouseover(function()
{ var elem=$(this);
elem.data("title",elem.attr("title"));
// Using null here wouldn't work in IE, but empty string does
elem.attr("title","");
}).mouseout(function()
{ var elem=$(this);
elem.attr("title",elem.data("title"));
});
I don't think that you would be able to get the exact value as html parses the document and displays the it on the browser and I don't know of any keyword or library that helps to find the exact contents of the element.
But you would use Ajax in this case and get all the contents of the file in the string format to get the exact value.
var client = new XMLHttpRequest();
client.open('GET', './file.html'); // get the file by location
client.onreadystatechange = function() {
if (client.readyState === 4) {
if (client.status === 200) { // when the file is ready
var file_contents = (client.responseText); // the whole file is stored in the string format in the variable
get_value(file_contents); // function get_value fetches the exact value
}
}
}
client.send();
function(str_file) {
var indextest = str_file.indexOf("test"); // fetches the index of test
var indexclosing = str_file.indexOf("</td>"); // fetches the index of closing td tag
var td_content = "";
var condition = false;
for (var i = indextest; i < indexclosing; i++) {
if (str_file.charAt(i - 1) == ">") {
condition = true; // the condition is true when the previous character is '>'
}
if (condition) { // when the condition is true start storing the value in the td_content element
td_content += str_file.charAt(i);
}
};
console.log(td_content) // display it
};
Javascript has escape function but it won't help you in this case, I just did a trick for you, but stay to get best answer.
var htm = $("#test").html().replace(/™/g, '™');
$('#editor').val(htm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="test">something™ is here</td>
</tr>
</table>
<input type="text" id="editor" value="">
I seem to be doing something wrong in the following code: http://jsfiddle.net/yunowork/qKj6b/1/
When you click next, the text within the span .hiddentext should be displayed in the span .showtext on top and correspond to the right Race (Rn). For example when R3 is highlighted the content of that .hiddentext "Race 3Oregon 14:30" should be displayed within the span .showtext.
This is the line where I make a mistake:
$('.showtext').text($('.hiddentext').first('td:first').text());
What am I doing wrong here?
Let's start simple:
Your problem:
$('.showtext').text($('.hiddentext').first('td:first').text());
you are saing, that, grab all .hiddentext, choose the first that has a td ... witch is not what you have in code, you have, td that contains hiddentext... so, the other way around.
What you want to do is simply get the current NEXT td and grab the hiddentext, so, just change to:
$('.showtext').text($nextCol.find('.hiddentext').text());
Now, can you see that the <br/> is not correctly rendered? That's because you are setting the text property, and you should set the html property.
the final code should be something like:
$('.showtext').html($nextCol.find('.hiddentext').html());
live example: http://jsfiddle.net/qKj6b/8/
Your code:
every time you need to have placeholders to provide some data to a context, please, DO NOT USE HTML TAGS to hold such values and hide them... make the use of the data- attribute, witch is a HTML5 complience, and works very well in any browser even if it does not have not HTML5 support, like IE6.
your table definition (td) that currently is:
<td class="visible" id="r2">
<span class="hiddentext">Race 2<br />Santa Fe 12:00</span>
<strong>R2</strong>
</td>
should be something like:
<td class="visible" id="r2" data-text="Race 2<br />Santa Fe 12:00">
R2
</td>
witch is way easier to read, and from your javascript code, you can easily get this as:
var hiddenText = $nextCol.data("text");
Your code (part 2):
This one is quite simple to know
Every time you are repeating yourself, you're doing it wrong
You have the methods for Next and Prev almost exactly as each other, so, you are repeating everything, for this, you should refactor your code and just use one simple method, this way, any future change only happens in one place, and one place only.
$(".next").click(function(e){
e.preventDefault();
var $nextCol = $('.highlighted').next('td');
MoveCursor($nextCol, 'next');
});
$(".previous").click(function(e){
e.preventDefault();
var $prevCol = $('.highlighted').prev('td');
MoveCursor($prevCol, 'prev');
});
function MoveCursor(col, side) {
var maxCol = 8;
if((side === 'next' && col.length != 0) ||
(side == 'prev' && col.length != 0 && col.index() >= maxCol)) {
$('.highlighted').removeClass("highlighted");
col.addClass("highlighted");
// show current title
$('.showtext').html(col.data('text'));
if (col.hasClass("invisible")) {
col.removeClass("invisible");
col.addClass("visible");
var $toRem;
if(side == 'prev')
$toRem = col.next('td').next('td').next('td').next('td').next('td').next('td');
else
$toRem = $nextCol.prev('td').prev('td').prev('td').prev('td').prev('td').prev('td');
$toRem.removeClass("visible");
$toRem.addClass("invisible");
}
}
}
Live Example: http://jsfiddle.net/qKj6b/22/
It should be
$('.showtext').html($('.highlighted .hiddentext').html());
Similar for the prev link...
or even better, thanks to #balexandre:
$('.showtext').html($nextCol.find('.hiddentext').html());
$('.showtext').html($prevCol.find('.hiddentext').html());
Fiddle
Update to match #balexandre hint: Fiddle 2
Do the following:
var $currCol = $('.highlighted'); //to get the current column
$('.race strong').text($currCol.closest('.highlighted').first('td:first').text());
.hiddentext class selects all the spans and the first() will always return you the first td.
Just make sure you select .hiddentext from the currently highlighted column and you are good to go.
$('.showtext').text($('.highlighted .hiddentext').first('td:first').text());
Try this (Same for both)
$('.showtext').html($currCol.find('span.hiddentext').html());
Working Example.
I have an HTML form with input text fields which i would like to have pasted back into the HTML body resulting in a text string returned by a JavaScript function i.e. in the place where the input fields are sequentially. A simple example would be:
<html>
<body>
This is the first field <input type="text" id="first"/>
and this is the second <input type="text" id="second"/> one.
</body>
</html>
When i now view this page and enter ABC into field 1 and XYZ into field 2, i'd like to know how to use JavaScript to create a piece of text like so:
This is the first field ABC and this is the second XYZ one.
So just to be clear, the web page itself need not change dynamically, i only want to be able to call the JavaScript function from elsewhere and then get the resulting text back with whatever is currently entered, pasted into the body text.
Any help much obliged.
Tiaan
You can use the DOM to loop through the child nodes of body (probably recursively), collecting the nodeValue properties of the text nodes (those are the bits containing "This is the first field " and such) and, where you encounter an input element, getting its value property instead. Build all of that text up into a string and you're there.
Some references:
DOM2 Core
DOM2 HTML
DOM3 Core
HTML5 Web Application APIs
Place form text and input fields into a div and call makeRecursive() (i.e. no args) to kick-start the text creation.
function makeRecursive(o)
{
var b = o || document.getElementsByTagName('div')[0];
var t = "";
if (b.nodeType === 1 && b.tagName === "INPUT")
t += b.value;
else if (b.nodeType === 3)
t += b.nodeValue;
if (b.hasChildNodes())
{
var c = b.firstChild;
while (c)
{
t += makeRecursive(c);
c = c.nextSibling;
}
}
return t;
}
I'm using mootools to toggle the display (and existence) of two DOM elements in one of my forms. Then, I am using javascript to validate the form to make sure that all of the required fields were filled in. The problem is that the the browser seems to be caching the elements. For example, I have html like this:
<input name="inputbox" id="inputbox" type="text" />
<select name="selection" id="selection">...</select>
And the javascript for validation is something like this:
if (form.inputbox != null && form.inputbox.value == "") {
//don't submit form
{
else if (form.selection != null && form.selection.value == 0) {
//don't submit form
}
Now, this works fine when the page is first loaded and the input element has been removed. However, when I click the button that replaces the input element with the select element, from then on the form.inputbox and form.selection in the javascript code contain the respective element as it was in its last state in the DOM - even if it is no longer in the DOM. So is the javascript caching the DOM and not updating the elements when they are removed from the DOM? What is going on here, and, more importantly, how should I go about fixing it?
Edit: I am using mootools to do the removing and replacing of the elements, the documentation for the respective functions can be found here and here.
Evaluating an element by name (form.elementName) when non-existent returns undefined. Evaluating the property value of an object ($('elementId')) returns null. Undefined and null are treated differently.
Well, I can answer the second part of my question now: how to fix it. If you are using mootools, then use the dollar function (or getElementById might work) instead of using form.selection and form.inputbox:
if ($("inputbox") != null && $("inputbox").value == "") {
//don't submit form
{
else if ($("selection") != null && $("selection").value == 0) {
//don't submit form
}
It works, but I don't have an explanation for why the other didn't...