Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've simple javascript function mentioned below:
<script>
function getValue(val)
{
document.getElementById('answer').value = val;
}
</script>
This function get's called on click of span and returned value gets displayed in input text.
I've three questions:
1] On click of span, if I want to append current value of varible 'val' with previous value; and return appended value to calling function. can you please suggest, how to achieve same without using jQuery?
2] There is one span which is suppose to work like Backspace. So click of span, i want to remove last character from document.getElementById('answer').value [This also without using jQuery]
3] There is one span which is suppose to work like Navigation keys [Right & Left]. So click of span [Let's say right], i want to move cursor position of the input text one character right and similarly for Left [This also without using jQuery]
Can you please suggest some pointers to achieve this?
For your question 1 I think you can do below. Code not tested
function getValue(val)
{
var currentVal = document.getElementById('answer').value
if(currentVal.length > 0 )
currentVal = parseInt(currentVal);
document.getElementById('answer').value = currentVal + val;
}
For question 2 :
Get the value and then do string operation to remove the last char. Its easy little google search for the string operations
For question 3 :
you can use event oncontextmenu for right click. Example below.
How can I capture the right-click event in JavaScript?
For moving cursor check below
Set keyboard caret position in html textbox
+= oprator appends string to existing string(not applicable in this case).
use return keyword to return updated value.
for removing last character use substring.
so try:
function getValue(val)
{
var currentText = document.getElementById('answer').value;
var updatedText = currentText.substring(0,currentText.length-2) + val;
document.getElementById('answer').value = updatedText;
return updatedText;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 months ago.
Improve this question
I've searched the jQuery docs and here and can't find an answer to my exact problem...
With a DRY spirit, I want to use javascript to add a character object countdown helper to any textarea element with maxlength and aria-describedby attributes.
Obviously I also need to use javascript to monitor keyup events to update the counter. I'm using jQuery 3.6.0. However, I can't seem to get the countdown method to recognize the newly-added "helper" div element. Here's what I have so far:
$(document).ready(function () {
// "characters remaining" countdown
function textCounter(field) {
var charLimit = field.attr("maxlength");
console.log("charLimit=" + charLimit);
// hack to *double-count* '\r\n' (client/DB discrepency)
var numLines = (field.val().match(/\n/g) || []).length;
var charLength = field.val().length + numLines;
console.log("charLength=" + charLength);
var charDiff = charLimit - charLength;
console.log("charDiff=" + charDiff);
if (charLength > charLimit - numLines)
field.val(field.val().substring(0, charLimit - numLines));
var count = $("#" + field.attr("aria-describedby") + " .count");
console.log(count.html());
count.html(Math.max(0, charDiff));
}
// add countdown helper div
$("textarea[maxlength]").each(function (e) {
var helpID = "#" + $(this).attr("aria-describedby");
var helpDiv = $('<div id="' + helpID + '"><span class="count"></span> characters left.</div>')
$(this).after(helpDiv);
textCounter($(this));
})
// update counter on keyup events
$("textarea[maxlength]").keyup(function () { textCounter($(this)); })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea maxlength="2000" aria-describedby="content-help" id="content" name="content"></textarea>
I can confirm that:
The helper div element is getting added
Via the console.log statements, the textCounter() method is getting called, but the count object resolves to undefined (even though it is clearly there), and
If the element is hardcoded in HTML (i.e., not dynamically added) the counter works as expected.
Other searches suggest that .delegate() or .on() are part of the answer, but everything I've tried has the exact same behavior as above. :( Every other Q/A I've come across is, for example, binding a click/hover event to the newly-added element, but here it's the textarea that needs monitoring (not the new helper element, although it will be updated), if that makes sense...
Note that I want the solution to work on pages that have multiple textareas, each with potentially different maxlength attributes.
Any thoughts how to accomplish this?
The line:
var helpID = "#" + $(this).attr("aria-describedby");
means that your selector:
var count = $("#" + field.attr("aria-describedby") + " .count");
Should be:
var count = $("#\#" + field.attr("aria-describedby") + " .count");
Or you could simply not include the "#" character when creating the element, giving:
var helpID = $(this).attr("aria-describedby");
Unfortunately this is a typo question (so it will be closed as such), this answer exists only temporarily to clearly show the error.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to replace all occurrences of li tags in a string with "\par {\pntext\f1 ''B7\tab}" and then append whatever data was within tags to the end of it.
Basically converting html to rtf format.
e.g
<ul><li>list1 line1</li></ul>
<ul><li><span>list2 line1</span></li></ul>
In the end i want to remove all ul tags
function convertHtmlToRtf(html) {
var richText = html;
richText = richText.replace(/<(?:b|strong)(?:\s+[^>]*)?>/ig, "{\\b\n");
return richText;
}
Your question is a bit broad, but since you say you are using javascript and want a Regex. Then I assume you have a string and want to replace pairs of <li></li> with the given string. Also assuming that your HTML is always very simple and predictable (no <li>s within <li>s), then you could do something like this:
var str = "<ul><li>list1</li></ul>\n<ul><li><span>list2 line1</span></li></ul>";
str.replace(/<li( [^>]*){0,1}>(.*)<\/li>/, "\\par {\\pntext\f1 ''B7\\tab} $2");
Here I'm using a regular expressions that matches a pair of <li> and replace them by that magic string but keeping whatever is inside (note you can easily extend it to also remove the ul if necessary. Ending result:
<ul>\par {\pntext1 ''B7\tab} list1</ul>
<ul>\par {\pntext1 ''B7\tab} <span>list2 line1</span></ul>
Now you can notice right away that it won't remove tags inside - so the <span> will be left there. If you can use jQuery, then it might be easier to convert the nodes correctly than using Regex (which can get quite complicated)
Edit:
Since it's been clarified that jQuery can be used to help on the parsing, then here is a simple example of how you could use it:
https://jsfiddle.net/nazy8sc6/2/
var html = "<ul><li>list1 <b>line1</b></li></ul><ul><li><span>list2 line1</span></li></ul>";
var TAB_STR = "\\par {\\pntext1 ''B7\\tab}";
function convertLi(parent, node) {
var convertedText = TAB_STR + " " + $(node).text() + "<br>";
var convertedNode = $('<span></span>').html(convertedText);
$(parent).append(convertedNode);
}
function convertHtmlToRtf(html) {
var result = $('<span></span>');
$(html).find('li').each((_, node) => {
convertLi(result, $(node));
})
return result.html().replace(/<br \>/g, "\n");
}
var res = convertHtmlToRtf(html);
console.log(res);
In this solution, you simply find all <li> tags and extract the content from it - I keep the original HTML always there and simply copy the converted content into a new HTML from which we finally extract the fully converted text. Hope this helps you, but let me know if I haven't managed to explain myself very well.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
In my javascript code I need to get the definition of an element, but without its content - neither text nor children.
E.g. for:
<div id="my_example_id" class="ShinyClass">
My important text
<span> Here</span>
</div>
I would like to write a javascript fucntion that when provided with the element of the div above will return the following as string:
<div id="my_example_id" class="ShinyClass">
I have been trying with different manipulations over the elements, functions like innerHTML, outerHTML and similar, but I was unable to figure out how to fetch only the part I am interested in. Is substring until the first > the best possible solution?
EDIT: selecting the element is not part of the question - I know how to do that, no prob. Rather the question is: when I have already selected a particular element how to parse as string only its own definition.
UPDATE:
const div = document.getElementById('my_example_id'); // get the node
const html = div.outerHTML.replace(div.innerHTML || '', ''); // simple set logic
console.log(html);
Just some way to do this, not saying the best.
const div = document.getElementById('my_example_id');
const copy = div.cloneNode(true);
const parent = document.createElement('div');
copy.innerHTML = '';
parent.appendChild(copy); // I forgot to add this line.
const html = parent.innerHTML;
console.log(html);
Basically you create a copy of the div, create a parent, then remove innerHTML of the copied node to leave out just the 'div' itself. Append the copied node to the new parent and show the parent's innerHTML which is just the 'div' you wanted.
you don't need to do all that fancy stuff copying it to a parent..
// make a copy of the element
var clone = document.getElementById('my_example_id').cloneNode(true);
// empty all the contents of the copy
clone.innerHTML = "";
// get the outer html of the copy
var definition = clone.outerHTML;
console.log(definition);
I threw it in a function in this fiddle: https://jsfiddle.net/vtgx3790/1/
I guess that a Regex is what you need. Check if this works for you
function getHtml(selector) {
var element = document.querySelector(selector)
var htmlText = element.outerHTML
var start = htmlText.search(/</)
var end = htmlText.search(/>/)
return htmlText.substr(start, end + 1)
}
alert(getHtml('.ShinyClass'))
example here
console.log(getElementTag("my_example_id"));
function getElementTag(myElementId) {
var FullEelementObject = document.getElementById(myElementId);
var FullElementText = FullEelementObject.outerHTML;
var regExTag = new RegExp(/(<).*(>)/i);
openingTag = FullElementText.match(regExTag);
return openingTag[0];
}
Just threw together this JSFiddle, it gets the outerHTML of the element you pass the function, the regExp to get the full opening tag.
Edit: Here is the JSFiddle
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi I am developing a small application in JSP.
My idea is to give reference to a JSON element while user is typing in the text area.
for example:
If my JSON contains:
cO2,
H2O,
c9O
and in the text area the user is typing a sentence and as soon as the user types a special character such as # or \ or / if he/she writes "c" character I want a small drop down to appear with the two elements starting with c.
The user can select the element afterwards and then when the form is posted I want to extract those information which was entered from JSON.
This is like when you start typing a name in Facebook I guess.
Any ideas?
Thanks in advance
EDIT: JS Fiddle
<form action="./Protocol" method="POST">
<textarea rows=5 cols=50></textarea>
<input type="submit"/></form>
$('textarea').textcomplete([{
match: /(^|\s)(\w{2,})$/,
search: function (term, callback) {
var words = ['google', 'facebook', 'github', 'microsoft', 'yahoo'];
callback($.map(words, function (word) {
return word.indexOf(term) === 0 ? word : null;
}));
},
replace: function (word) {
return word + ' ';
}}]);
The above JS Fiddle does what I want partly.
One of the two things I want to accomplish here
1. if in the JSON, each word has an ID like {"ID": "1","name": "GOOGLE"} can I get the IDs that are in the textarea to be posted when the form is posted
2. or just the array index numbers, how do I POST the values in the form separately from the textarea.
OK, despite what I said, here's a basic example of how you might achieve this (because I was bored, but not so bored I'm going to do it all for you :)):
HTML
<input id="input"/>
<div id="dropdown"></div>
JS
// grab the DOM elements
var input = document.getElementById('input');
var dropdown = document.getElementById('dropdown');
// assign an function to the onkeyup event for your input box
input.onkeyup = search;
// define your data structure
var arr = ['cO2', 'H2O', 'c9O'];
function search() {
// get the content and length of the content
// `this` in this instance refers to the element to which
// we assigned the function
var val = this.value;
var len = val.length;
// filter out the elements from the array that match
// the content, or nothing if the input is empty
dropdown.textContent = arr.filter(function(el) {
return val !=='' ? el.substring(0, len) === val : '';
});
}
DEMO
Hope that helps you on your way.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have this function which produces the correct value when run, but I am having a hell of a time displaying the results.
Here is the JS which is calculated onChange in a form I am trying to display the resulting value elsewhere on the form. The alert displays the correct value but my id remains blank.
Thanks in advance for taking a look
function calculate_mtow1() {
togw_n = 0;
togw = $('#togw').val();
if (togw != '' && togw != 0 && togw != 'Nan') {
var togw = togw.replace(",", "");
togw_n = togw;
}
burn_n = 0;
burn = $('#burn').val();
if (burn != '' && burn !=0 && burn != 'Nan') {
var burn = burn.replace(",", "");
burn_n = burn;
}
var mtow1 = parseInt(togw_n) + parseInt(burn_n);
$('#mtow1').val(mtow1);
document.getElementById('mtow1');
alert(mtow1);
}
<td>TOW + Fuel Burn =<span id="mtow1"></span></td>
Your code is getting the element with getElementById but then not doing anything with it. You need to assign the result of getElementById to something, or call methods on it on the same line. If your goal is to put the value of mtow1 into your <span>, try doing this:
// Solution 1
var spanElement = document.getElementById("mtow1");
spanElement.innerHtml = mtow1;
Alternatively, perhaps you were trying to display the value of mtow1 by using this jQuery:
$('#mtow1').val(mtow1);
That doesn't do what you think it does. It changes the "value" attribute of the span to the value of mtow1, but that change isn't visible to the user. It's the same as writing this as your HTML:
<td>TOW + Fuel Burn =<span id="mtow1" value="valueofmtow1"></span></td>
If you want to use jQuery instead of the getElementById method I posted above, you could do this:
// Solution 2
$('#mtow1').html(mtow1);
You don't need to do both. Either solution will work on its own.