html: text and createElement - javascript

i have difficulty understanding the below code snippet. I am trying to understand where the value attribute is assigned to, however i only see the property attribute.
<html:text indexed="true" name="<%=(String)
currentItr.next()%>" property="<%=(String) currentItr.next()%>"/>
because i am slightly more familiar with HTML DOM, i was able to create the element i want using below:
object<%=i%> = document.createElement('
<input type="text" name="<%=name%>' + '[' +
sectionId + '].mySpecialList[' + row[id] + '].
<%=curProp%>" id=' + sectionId +
'size="<%=curItr.next()%>" value="<%=curItr.next()%>">');
which i know i can grab and access using the following:
var obj = document.forms["myForm"].elements["mySpecialList[0].mySmallList[0].someProperty"];
what is the html:struts equivalent of the createElement bit? Because when i use the html:text code snippet, i am unable retrieve or parse the value attribute.
for example: the <html:text> tag seems to automatically create an element with name, value and size. however, when i try to access the same element in javascript, i get the element's column name instead, and not the value

It's unreadable and you should not use scriptlets, use JSTL for that.
<html:text property="propertyNameOfYourBean"/>
For list you should use <c:forEach> tag.

Related

Extract value from html select tag using JavaScript

I am getting whole select tag as a value from my code, in order to do work around the value i need to extract the value from my select tag,as this tag is dynamically created by the code.
Below is the value i am getting. How can i extract this using java script.Thanks for your help.
rowId[0].QValue = "<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>"
The proper way to do this would be to select the element from the DOM with one of the selection functions. In this case, I prefer document.querySelector:
var type112 = document.querySelector('#type112');
The # means 'id', and you can pass any combination of valid CSS to document.querySelector.
Then, to produce the value of this element, simply call
type112.value
This will give you the text value of the currently selected option within the select element.
Based on your comment, I'm sensing that perhaps you have the text of an element and want to parse out the id? If that's the case, you can try:
var elemString = // whatever your str is
var id = (elemString.match(/id="([^"]+)"/) || [])[0];
This assumes that the id is the first attribute in the string, as well as a whole litany of other things that will probably break in production but will work in the absence of a coherent understanding of what you're trying to do.
You can simply use the select element id to retrieve the value of the element.
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>
You can write the javascript to get the element by id Type112
and so on to get the value:
var s = document.getElementById("Type112");
var selNum = s.options[s.selectedIndex].value;
alert(selNum);
Here's a jsfiddle example
Try this.
var list = document.getElementById("Type112");
console.log(list.value)
<select id="Type112" class="GridList" rownumber="0" value="Q1 Only" ><option></option><option value="1" selected="selected">Q1 Only</option><option value="2">Q2 Only</option></select>

HTML Label name instead of ID?

I am making website where I am created a lot of labels that are assigned in output as here
Use fiddle link at the end of the post
<!-- lets say that I want to make a kind of board to show some game clans or... whatever -->
<label class='team' name='ally'>Madcowz</label><BR>
<label class='team' name='ally'>Fluffy Unicorns</label><BR>
<label class='team' name='enemy'>Blue bastards</label><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<!-- The problem is that the NAME tag does not exist for label in this case: -->
<!-- I can't use ID because ID should be unique values -->
<script>
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
document.getElementById('printSomeOutputHere').innerHTML += teams[i].name + ": " + teams[i].textContent;
document.getElementById('printSomeOutputHere').innerHTML += "<BR>";
}
</script>
Fiddle:
http://jsfiddle.net/cusnj74g/
name attribute is undefined, so how can I mark these labels with same name if I can't use (I can, but I should not) ID
A couple of points:
You seem to know that name is not a valid attribute for label elements. So don't use it, use data-name instead.
You're using label elements incorrectly. There are two ways you use label: A) By putting the input, select, or textarea it relates to inside it (<label><input type="checkbox"> No spam please</label>), or by using the for attribute to associate it with one of those elements elsewhere in the document (<label for="no-spam-please">No spam please</label>...<input id="no-spam-please" type="checkbox">). Having a label with no control in it and no for is fairly pointless; just use a span.
You're using jQuery in one place, but not in others. I suggest that if you're going to have a library on your page, it's best to get full use out of it. In this case, to access the attribute, you'd use $(teams[i]).attr("name") or better, $(teams[i]).attr("data-name") if you're using a data-* attribute (see #1 above). (Some may tell you to use .data to access the attribute; don't, that's not what it's for. But you might consider looking at what it's for and whether that helps you.)
.innerHTML += "content" is an anti-pattern. It makes the browser loop through all elements within the element you're doing it to to build a string, then append the string on the right with it, then parse the result, and delete all existing elements within the element and replace them with the parsed result. Instead, consider .insertAdjacentHTML("beforeend", "content")
You don't declare i anywhere, which means your code falls prey to The Horror of Implicit Globals. Declare i, or use any of several other ways to loop that don't require an index counter.
Your output will be fairly hard to read, recommend breaking it up (perhaps a div for each team?).
textContent is not reliable cross-browser, some browsers use innerText instead. (And there are differences in how whitespace is treated between them.) Since you're using jQuery, use text.
...but yes, the code would work if you used .getAttribute("name") rather than .name. Browsers make access to even invalid attributes available through getAttribute. They just don't necessarily create reflected properties for them.
Here's a version with the various comments above applied:
var output = $("#printSomeOutputHere");
$(".team").each(function() {
var $this = $(this);
output.append("<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>");
});
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
...or to avoid repeated appends we could use map and join:
$("#printSomeOutputHere").append(
$(".team").map(function() {
var $this = $(this);
return "<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>";
}).get().join("")
);
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
From https://developer.mozilla.org/en-US/docs/Web/API/Element.name:
[The name property] only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>.
Since you're using jQuery I would use something like:
for(var t in teams){
$('#printSomeOutputHere').get(0).innerHTML +=
teams[t].getAttribute("name")
+ ": "
+ teams[t].text()
+ "<BR />";
}
Use getAttribute instead:
teams[i].getAttribute('name')
Why not use multiple classes:
<label class='team ally'>Madcowz</label><BR>
<label class='team ally'>Fluffy Unicorns</label><BR>
<label class='team enemy'>Blue bastards</label><BR><BR>
And the JS:
<script>
var outEl = document.getElementById('printSomeOutputHere');
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
outEl.innerHTML +=
(teams[i].hasClass('ally')? 'ally':'enemy') + ": " +
teams[i].textContent;
}
</script>

Get element from string

I have a large string in a variable that includes a whole bunch of HTML tags.
I want to get the value of a hidden input field within the string and store it in its own var.
<input type="hidden" value="WantThis" />
Can anyone help me out at all?
You can parse the HTML with jQuery to get the value:
var theValue = $(myString).find('input[name=something]').val();
I'm assuming the hidden field has a name. If it doesn't, you'll need to specify input[type=hidden] and find it using its position relative to the rest of the content.
If your string does not already have a root element and the <input> is not nested, you'll probably want to use $('<div>' + myString + '</div>') instead.
Get the hidden input like so:
$(html).find("input[type=hidden]").val()
Create an ID for the hidden input and call it like normal
<input type="hidden" value="WantThis" id="myInput" />
Then call it
var myval = $('#myInput').val();

Get a value from an input textbox

Okay. So I have this code
<input id="suspect" value="" type="text">
<input id="reason" value="" type="text">
<textarea></textarea>
var suspect = $('input#suspect').text();
var reason = $('input#reason').text();
$('textarea').val('' + suspect + ' and ' + reason + '')
Then I put something in both of those 2 inputs and then the textarea recieves no value from the inputs. How to fix that problem ?
Because when you set the variables there's no text inside the elements from which you're trying to recover the entered-text (incidentally, for inputs you're looking for .val()). If you bind to the focus event:
$('textarea').focus(
function(){
var suspect = $('#suspect').val(),
reason = $('#reason').val();
$(this).val('' + suspect + ' and ' + reason + '');
});
JS Fiddle demo.
Also, in this case (since you've placed the JavaScript after the elements in the DOM, albeit you've omitted the <script></script> tags) you might be okay not using the $(document).ready() event handler, but I'd normally suggest wrapping jQuery in such, just to be sure that events are being bound after the elements to which they're being bound exist in the DOM.
References:
focus().
val().
.text() -- Gets the text inside the elements
.val() -- Gets the value of the elements
Since the text is stored inside the value, therefore you should use .val() instead of .text().
var suspect = $('input#suspect').val(),
reason = $('input#reason').val();
$("textarea").val(suspect+" and "+reason);
If you want instant change try the keyboard events
$(window).keyup(function() {
var suspect = $('input#suspect').val();
var reason = $('input#reason').val();
$('textarea').val('' + suspect + ' and ' + reason + '');
});
see here: http://jsfiddle.net/TtAVS/
​
You probably want to use val() here instead of text(), and there also needs to be some kind of event (like a click) that causes the data to be extracted from the inputs and put into the textarea.
It also might be worth noting that since id's are unique,
var suspect = $('#suspect').val();
var reason = $('#reason').val();
are sufficient as selectors and (I find) easier to read.
should use .val() to get value from the input box

Setting the value of a hidden input

The idea: I'm setting the value of an input with type="hidden" via regular Javascript or jQuery.
The issue: neither jQuery nor document.getElementById will find the hidden input, even though I'm absolutely sure the selector is correct and there are no conflicting elements.
The code:
I can't really post much of it, because it's full of rather complicated PHP that confuses me when I just look at it.
Here's the javascript:
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
Note: there's nothing wrong with the selector, and the "input" is a different element that I'm using to reference the hidden.
Here's the HTML:
<input type="hidden" name="s<?=$step_counter?>_budget_hidden"
id="s<?=$step_counter?>_budget_hidden" value="0" />
The code is kind of out of context, but it's more of a general problem with Javascript than a syntactical error. Thoughts?
In $("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total); you take two chars before the first underscore in your hidden id. However your hidden id have only one char 's'
EDIT
Ok the <?= ?> was hidden before the question edit.
Do you call your script after the body onload event?
EX:
$(document).ready(function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").bind("keyPressed",function(){
$("#" + input.id.substr(0,2) + "_budget_hidden").val(budg_total);
}
});
FYI: We can get the hidden input value using jQuery, even we can also edit any hidden input value using jQuery.
I think your way of getting the hidden value using 'substr' method is causing some problem. You are using like substr(0, 2) so are sure that the variable $step_variable is a single digit number, otherwise your code will not return correct result.
I am giving some sample code below, check it once.
Here's the javascript:
var input_id = $("hidden_val").attr("id").substr(1);
$("#" + input_id + "_budget_hidden").val(budg_total);
Here's the HTML:
input type="hidden" class="hidden_val" name="s_budget_hidden" id="s" value="0"
I think this will help you. Let me know if you are not following this flow to solve your issue.
I think that input.id.substr(0,2) says to start at the start of the string, take 2 characters and use that.
http://www.w3schools.com/jsref/jsref_substr.asp
Try using Firebug to see what the result of that method call is.

Categories