I am just getting started with JavaScript so it is a fairly simple question..
I have a value "x" which was calculated/derived in a JavaScript function "y".
I wish to display this value in HTML. I am using Internet Explorer (yeah..) and the "" tag is not valid here...
Since it is a single vale I won't be using a dropdown box. The other alternative being "". Can I show this value in a label? If so how, if not what do I do?
Technically you can use any element you like. The usual DOM methods (document.createTextNode, someElement.appendChild, etc) will work.
A <label> almost certainly wouldn't be suitable though. It is designed to tell the user what to enter into an input or other form control.
Pick the element which has the semantics that best match that data you are outputting. (Keeping in mind that if nothing has suitable semantics then <div> and <span> don't have any so are the safe fallback).
Say you have value "X",
With the following Markup:
<label id="lblMyValue">
</label>
Your code, should look for the DomElement with that ID:
document.getElementById("lblMyValue").innerHTML= X;
I was also a beginner (and am still learning a lot), and I must give you the following advice: Start using JQuery. Even if it is not always wanted, coding with it when you can will really teach you the "ins and outs" as it were, of JavaScript.
Have Fun Learning.
You can display the calculated result in a variety of places, depending on what makes the most sense. If you want to show it in an element that contains HTML, you would use the innerHTML property. If you want to show it in some input element, you could use value instead.
var result = 2 + 2;
document.getElementById('infoSpan').innerHTML = result;
document.getElementById('infoTextInput').value = result;
<div>Result: <span id="infoSpan"></span></div>
<div>Result: <input id="infoTextInput" type="text" /></div>
Related
I would like to dynamically filter bad words using this profanity filter. The api will change "ass" to "***" in the given example, only if the text was there before page load. I would like it to change recognized bad words as they are typed, to prevent someone from sending a naughty messages through a my contact form.
Here is what i've got so far:
<div id="msg">
<textarea type="text" onkeypress="badFilter()" id="mess_box" name="cf_message" style="height:150px;" maxlength="500" placeholder="Message" ></textarea>
</div>
<script>
function badFilter() {
$typedText = $('#mess_box').val();
$typedText.profanityFilter({
customSwears: ['ass']
});
}
</script>
I would think that the 'onkeypress' attribute would force the script to check for updated textarea values, but that is not the case.
Help appreciated!
You are assigning the filtered value to a variable, and then you are not using it.
function badFilter() {
$typedText = $('#mess_box').val();
$typedText.profanityFilter({
customSwears: ['ass']
});
$('#mess_box').val($typedText);
}
the last line will apply text back to the input box.
The problem is that you are changing the value of the input element while the user is typing. This way, there will be glitches if the user types in the middle of the text (not at the end).
You could create a system of two input controls (one hidden, one visible) where user types into one (hidden) and censored text appears in the visible one. When user positions cursor in the visible control, you would position it on the same character in the invisible one. Updating the text of the visible control will not glitch while the user is writing.
This will work only if profanityFilter can work with string object.
If not, the correct way to initialise it would be
$('#mess_box').profanityFilter({
customSwears: ['ass']
});
I do not know how the plugin works, but
$typedText = $('#mess_box').val(); <-= reading the value, storing a string
$typedText.profanityFilter({ <-- expects jQuery object of an element, you have a string
customSwears: ['ass']
});
Should be
$('#mess_box').profanityFilter(...);
To clear up vagueness from my question, the Profanity filter i was using is this --> https://github.com/ChaseFlorell/jQuery.ProfanityFilter
And to my understanding (which isn't great), the plugin wasn't designed to filter out words dynamically as being typed, this might require Angularjs or more DOM manipulation.
Vinko Bradvica provided a good explanation and work around with this plugin in order to dynamically censor bad words as they are being typed.
The right way to handle it is like that:
Create a <p> tag in your html with style="visibility: hidden;"
Then add this code in your JS file:
$('#textarea').keyup(function () {
$('#textarea-filter').text($('#textarea').val());
$('#textarea-filter').profanityFilter({
customSwears: ['ass']
});
$('#textarea').val($('#textarea-filter').text());
});
I'm currently a student in Software Engineering, and I'm trying to create a small program (I don't know if the word "macro" is appropriate for it) in HTML or JavaScript, to fill a form from a webpage.
The webpage has the following code, placed in the head section:
input type=password name=code size=8 maxlength=8
input type=password name=nip size=8 maxlength=8
input type=password name=naissance size=8 maxlength=8
I've been thinking of maybe using JQuery, as I've browsed a little bit on the internet to figure out how to do it, but I don't really know how to do that. I'm pretty sure the only way to do it is to modify the values of the fields "code", "nip" and "naissance", but how do I get access to them from an external file?
Please note that I have bases in HTML and JavaScript, but nothing amazing - I'm still learning :/
Since you're looking to use jQuery, this might be a good place to start:
http://api.jquery.com/attribute-equals-selector/
Next might be a good tutorial in jQuery to get you started. I'm going to assume you can find those on your own, and I'm going to jumpstart your work:
var selector = 'input[name="code"]'; // <-- we define the element we want to find here
// we will use that to select a jQuery element like this --> $(selector)
$(selector).val('CODE!!'); // <-- it's just that easy to set a value.
So if that's what it takes to set the value for code from javascript, you can guess what the other two would look like. I'll give you a hint on the second one:
$('input[name="nip"]').val('NIP!!');
Of course, all this assumes you do use jQuery in the browser to accomplish this
I believe what you are looking for is simply accessing the fields from javascript. You can include any external javascript on the HTML page:
<html>
<head>
<script src="http://someexternalurl.com/js/jsfile.js" type="text/javascript"></script>
...
Then in this javascript file you can access the elements as:
alert(document.getElementByName("nip").value);
document.getElementByName("nip").value = "abc";
Hope that helps.
You can accomplish you project by going through this links
w3school
tizag
jqueryui
jquery
Go through this links
with regards
Wazzy
I'm trying to create a simple extension for personal use. It's partially from laziness, and partially from an urge to learn. I've never made extensions before, but I've been looking at the documentation. Now I just need to write the code. What I'm trying to do, is when the browser loads a certain page, to insert text into a specific form. The form is as follows
<div id="set_tags" class="advanced_option">
<label for="post_tags" class="inline_input_label" id="post_tags_label"
onclick="Element.remove($(this))"
style="left:8px; right:auto; text-align:left">tags</label>
<input id="post_tags" name="post[tags]" type="text"/>
</div>
I haven't worked much with javascript, so is there a way to add the text "Music" to this when the page is loaded?
You can use the onload function to start your function.
http://javascript.about.com/library/blonload.htm
Since you are new to javascript you may want to get familiar with unobtrusive javascript (http://www.onlinetools.org/articles/unobtrusivejavascript/chapter4.html) which I find is a better way to write javascript, as you can then easily comment out javascript and see how it works when that is disabled. But, it would be easier to learn this in the beginning.
To get the input tag you can use document.getElementById() which would be something like:
var elem = document.getElementById('post_tags');
Then, to add text to this field there should be a value property in your input definition above, and you would just do:
elem.value = "Music";
document.getElementById("post_tags_label").appendChild(
document.createTextNode("Music"));
I'm assuming that you want to put it at the end of the element post_tags_label.
This is really easy to do if you use GreaseMonkey. It's perfect for personal changes you want to make to web pages, etc.
I have website that converts Japanese Kanji into Romaji (roman letters):
and the output shows and hides with CSS what the user needs to see depending on their input criteria. For example:
<div id="output"><span class="roman">watashi</span> <span class="english">I</span></div>
The interface allows the user to flip between and output of watashi or I depending on what they want to see. The CSS hides one or the other using jQuery and a toggle button. (the hiding mechanism involves simple adding a class to the body and letting CSS do its thing).
The problem is that when users copy/paste the text into Word it copies everything. So I decided to use a system to copy paste the text using JavaScript and jQuery, but the problem repeats itself:
$('#output').text() outputs watashi I even if I is invisible on the page itself rather than watashi. Is there any way to get just the visible text?
the other solutions did not give me what I needed.
Short Answer
my answer is :
$('#output *:not(:has(*)):visible').text()
plunkr
TL;DR
The problem with marcgg's solution
You should not ask the text of all element under some root element..
why? - it will repeat output and ignore hidden flag
lets look at a simple example
<div id="output" class="my-root">
<div class="some-div">
<span class="first" style="display:none"> hidden text </span>
<span class="second" > visible text </span>
</div>
<div>
now if I do $('#output').children(":visible").text()
I will get .some-div and .second..
when in fact .some-div is of no concern to me..
when I ask for text() on those elements, .some-div will return the hidden text as well..
so technically marcgg's solution is wrong IMHO...
The reason for my answer
Now, in order to properly answer the question, we have to make an assumption. One that, for me, seems reasonable enough.
The assumption is that text only appears in leaf elements..
So we won't see something like this:
<div id="output" class="my-root">
<div class="some-div">
<span class="first" style="display:none"> hidden text </span>
<span class="second" > visible text </span>
</div>
some text here..
<div>
Why does this assumption seem reasonable to me? two reasons:
Because it is hard to maintain a page that is constructed this way - and with time people with experience learn that and avoid it.
It is easy to convert your html to such a structure. just wrap parents' text with spans. So even if this assumption does not exist right now, it is easy to get there.
With that assumption, what you want to do is request all leaf elements (elements without children) , filter out the visible, and ask for their text..
$('#output *:not(:has(*)):visible').text()
This should generate the correct result.
Gotta have text outside leaf element?
the comments suggest sometimes you just got to have text outside leaf element
<div> This is some <strong style="display:none"> text </strong> </div>
As you can see, you have <strong> as a leaf and it is common to have text outside it like in this example.
You could go around it with the workaround I suggest above.. but what if you can't?
You can clone the dom and then remove all hidden elements.
The problem here is that in order for :visible selector or :hidden selectors to work, I must have the dom element on the document (which means actually visible to the user).
And so, this method comes with some side effects, so be careful.
Here is an example
for this html
<div id="output" class="my-root">
<span>
some text <strong style="display:none">here.. </strong>
</span>
</div>
This javascript works
$(function(){
var outputClone = $('#output').clone();
$('#output :hidden').remove();
console.log($('#output').text()); // only visible text
$('#output').replaceWith(outputClone);
console.log($('#output').text()); // show original state achieved.
})
see plunker here
as mentioned - side effects may appear like a momentary flicker, or some initialization script that should run.. some may be avoided with some original thinking (div with size 1px/1px to contain the clone alongside original content?) depending on your scenario.
Use the :visible selector of jQuery
In your case I think you want to do:
$('#output').children(":visible").text()
Try this in modern browsers (here 'element' is a non-JQuery DOM object):
function getVisibleText(element) {
window.getSelection().removeAllRanges();
let range = document.createRange();
range.selectNode(element);
window.getSelection().addRange(range);
let visibleText = window.getSelection().toString().trim();
window.getSelection().removeAllRanges();
return visibleText;
}
then:
getVisibleText(document.getElementById('output'));
Guy has the correct answer.
However, I was dealing with a "this" object, so to get his answer to work you need to use the following syntax...
$('*:not(:has(*)):visible', this).text()
var lookup = function(element, text) {
//DFS Recursive way of finding text on each level
//Visible only works on elements that take up space(i.e. not fixed position elements)
var results = element.children(':visible');
//Look at the text at each level with the children removed
var newText = '';
results.each(function(index, value) {
newText += $(value).clone()
.children()
.remove()
.end()
.text();
});
var moreResultText = '';
results.each(function(index, value) {
moreResultText += lookup($(value), text);
})
if (results.length > 0) {
return text + newText + moreResultText;
} else {
return text;
}
};
lookup($('#output'), ''));
Most of the other functions fall apart when run on large sections of a page, this should be a more accurate way to determine what is actually displayed to the user, without corrupting the page, and without returning text that is not visible to the user.
Be careful of course, this does not preserve any sense of formatting, and the spacing of the output may not be correct between elements. Also, it probably does not correctly order the returned text, in these aspects its usages will be limited. Another consideration is the real definition of visible is a little hard to nail down, but for this example I accept that ":visible" works for most common cases.
I use it to check if a page contains visible text(just run it on the body element), but it would probably work for this example too.
Instead of hiding a span, remove the span element and keep a reference to it. When the user clicks on the toggle button, remove the other one and insert the one you kept a reference to. The user won't be able to select something that isn't in the DOM anymore.
I'm trying to change the value of a text input field based on user actions. I'm doing it like this:
document.getElementById(textFieldID).value = newValue;
It isn't quite working -- the original text in the field remains on the screen, unchanged. However, when I submit the form, it behaves as though the value was indeed changed correctly. (And a debug alert confirms that yup, I'm hitting that bit of the code and passing in the right field ID and text value.) Anybody have any insights? Is there something I need to be doing to redraw the input element?
Edit: Per Jeff B's request, and per the fact that this seems to have everybody stumped, here's some relevant bits of code:
<script LANGUAGE="JavaScript" TYPE="text/javascript">
function changeText(changeSelector)
{
var myindex = document.getElementById(changeSelector+"Recent").selectedIndex;
var SelValue = document.getElementById(changeSelector+"Recent").options[myindex].value;
document.getElementById(changeSelector).value = SelValue;
document.getElementById("historicalText").value = SelValue;
document.getElementById("historicalTextSelect").value = changeSelector;
}
</script>
<input onChange="updateScrollingPreview1217(this); return true;" type="text" id="crawlMsg1217" name="crawlMsg1217" size="60" maxlength="1000" value="">
<select id="crawlMsg1217Recent" name="crawlMsg1217Recent" onchange="javascript:changeText('crawlMsg1217');">
[options go here]
</select>
And that "onChange" handler isn't what's gumming up the works; I get the same behavior with or without it.
Edit 2: It looks like the problem is being caused by "JSpell", a third-party spelling checker our product uses. (I'm told that clients prefer using it to a spellcheck built into the browser; go figure.) It appears to be slightly misconfigured on my test machine, so I'm going to try straightening that out and praying that it makes the problems go away. If it doesn't ... should be interesting.
Edit 3: Yup. Fscking JSpell. Just posted a complete answer for the sake of posterity, will accept it tomorrow when I'm allowed. My thanks to everybody who tried to help; +1's all around, wish I could give more.
I have confirmed that the culprit is indeed JSpell, and that the precise trouble spot is this line:
window.onload=jspellInit;
Despite the prayers mentioned in Edit 2 above, making sure it was configured correctly did NOT make the problem go away. And this line is indispensable to JSpell's functionality. I don't know if JSpell always hoses Javascript functionality this way, or if there's some sort of perfect storm of factors that's causing it to pick a fight with my page, but that is indeed the source of my problems.
My thanks to everybody who tried to help. This was obviously a bit of a no-win in terms of getting the right answer, since it was caused by a component that was seemingly entirely unrelated and thus didn't get mentioned by me, but you at least confirmed that I was (in theory) doing things right and not simply going insane.
Is the document's id actually "textFieldID" or is "textFieldID" a javascript variable that contains the ID of the text input to change? If it is not a variable, I believe you should make it:
document.getElementById('textFieldID').value=newValue;
It's hard to debug this without the context, since the code you have ought to work fine. Can you confirm that you've got the right node by doing something like:
document.getElementById(textFieldID).style.border = "4px solid red";
What does any other element on the page have a name attribute that is the same as the id?
Internet Explorer 8 and later. In IE8
mode, getElementById performs a
case-sensitive match on the ID
attribute only. In IE7 mode and
previous modes, this method performs a
case-insensitive match on both the ID
and NAME attributes, which might
produce unexpected results. -
http://msdn.microsoft.com/en-us/library/ms536437%28VS.85%29.aspx
Try alerting your the nodeName and id ofr the returned element and make sure its the input you expect.
Use div element instead of textfield. I had same problem, my textfield which is changed with another script wasnt get the right value. you can easily use any div element like textfield with some CSS. than you can get the value from div using innerHTML.