Display value + text using jQuery - html

I am a total beginner. I have a form in HTML and am trying to calculate a specific value using jQuery. I want this value to be displayed in paragraph <p id="final"></p> under the submit button, but am actually not sure, why my code isn't working.
jQuery(document).on("ready", function() {
jQuery("final").hide();
jQuery("#form").submit(function(e){
e.preventDefault();
const data = jQuery(this).serializeArray();
/*
some calculations
*/
$('#final').html($('#final').html().replace('','result + " text"'));
jQuery("#final").show();
}
}
Do you have any idea, what could I be doing wrong??

You've got a several issues here.
Firstly, don't mix jQuery and $. If you're using the former, it's normally to avoid jQuery's alias, $, from conflicting with other code that might use $.
Secondly, you don't actually do any calculation (from what I can see in your code), so I'm not sure what you're wanting to output. I'll assume you're going to fill that in later.
Thirdly, jQuery('final').hide() is missing the # denoting you're targeting by element ID.
Fourthly, the line
$('#final').html($('#final').html().replace('','result + " text"'));
...doesn't quite do what you think it does. For one thing, it makes no reference to your data variable. And running replace() on an empty string doesn't make much sense.
All in all I'm guessing you want something like (note also how I cache the #final element - that's better for perforamnce):
jQuery(function() { //<-- another way to write a document-ready handler
let el = jQuery('#final');
el.hide();
jQuery("#form").submit(function(e){
e.preventDefault();
const data = jQuery(this).serializeArray();
let calc = 5+2; //<-- do what you need to here
el.html(calc).show();
}
}

Guessing result is your variable and your above code is your current status, you should fix the html replacement to something like (depending on your acutal usecase):
$('#final').html(result + " text"));

Related

How the letters turn to yellow on google chrome while searching for a text?

When i hit Ctrl+F to find words in chrome all the letters with the search text becomes yellow.
Anyone have any idea how it is done? Am just curious to know this!
BTW i'am searching for this is to implement a functionality like this using google extensions. Right now what am doing is finding that particular text and replace it with something like below.
Original text: hello
Replaced text: '<span style="background:yellow;">hello</span>';
Any ideas?
Edit: I think browsers don't allow you to use native higlight
mechanism. But you can imitate this functionality using
Javascript/jQuery.
There are lots of javascript and jQuery plugins to do that. General idea is finding all occurrences of the given word(s) and replacing them with some HTML code. (Which have different background color or larger font size etc.) For find-replace operations, RegEx will be beneficial.
Basic, non-optimized example;
/* Instead of body you can use any container element's selector */
$('body').each(function(){
var allContent = $(this).text();
var wordsToBeHighlighted = ['Hello','World'];
wordsToBeHighlighted = $.map(wordsToBeHighlighted, function(str) {
return preg_quote(str);
});
$(this).html(allContent.replace(new RegExp("(" + wordsToBeHighlighted.join('|') + ")" , 'gi'), "<b style='color: red;'>$1</b>"));
});
function preg_quote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
Source

Applying variable to element jquery

I'm wondering if you can do this in jquery. I'm using version 1.10:
var myImage = $('#myImage');
What i basically want to do is assign the image as a variable so that i can use it anywhere. I want to use it during event handling:
E.g.
myImage.click(function () {
alert('Image Clicked');
});
If the above code is incorrect, I would really like to know the appropriate code.
Yes you can do it. In fact, it is recommended that you assign it to a variable so that you selector is not evaluated each time you use it. It is good for performance reasons.
Finding element by Id (such as in your case $('#myImage');) is fast but imagine if you have a selector like
$('ul > li.myClass:has(p) a:eq(2)')
Using a variable will speed things up for you in such scenarios.
I usually use $ sign in variable name like. var $varName = $('.selector') It helps me better understand the code and to distinguish between regular variables and variables that contain DOM elements.

How to enforce LI formatting in a contenteditable UL

I'm trying to allow users to edit a list (UL). In my attempts, it appears that contenteditable doesn't do anything special (like enforcing behind-the-scenes markup) -- it just gives the user a window into the innerHTML.
This is causing issues in that if there is not already a LI, and the user adds something, it doesn't get LI-ized. Similarly, if there are list items, but the user deletes them, then the LI gets deleted, and any new text is added without LI's. See http://jsfiddle.net/JTWSC/ . I've also found that it's sometimes possible for the cursor to "get outside" of an LI that does exist, but I can't reproduce consistently.
I have to include code, so this is what the "result" looks like:
<ul>whatever the user typed in</ul>
How do I fix this? I started down the path of a $('ul').keyup() handler that checks the html and wraps as necessary, but I was running into a handful of gotchas, like timing, losing focus on the element, having to refocus in the right place, etc. I'm sure it's possible if I work at it, but I'm hoping for an easier solution.
I built the following keyup/down handler in order to make my contenteditable <UL>s idiot proof.*
It does two things:
Adds <LI>s to the <UL> when the <UL> is empty. I use some code I found on SO (from Tim Down) to place the caret in the expected place
Cleans up all non-LI / non-BR tags. This is basically a quick-and-dirty paste-cleaner.
This is pushing my comfort-level on jquery and DOM manipulation, so there are probably a few things I could do better, but it works pretty well as-is.
//keyup prevented the user from deleting the bullet (by adding one back right after delete), but didn't add in li's on empty ul's, thus keydown added to check
$('ul').on('keyup keydown', function() {
var $this = $(this);
if (! $this.html()) {
var $li = $('<li></li>');
var sel = window.getSelection();
var range = sel.getRangeAt(0);
range.collapse(false);
range.insertNode($li.get(0));
range = range.cloneRange();
range.selectNodeContents($li.get(0));
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
} else {
//are there any tags that AREN'T LIs?
//this should only occur on a paste
var $nonLI = $this.find(':not(li, br)');
if ($nonLI.length) {
$this.contents().replaceWith(function() {
//we create a fake div, add the text, then get the html in order to strip out html code. we then clean up a bit by replacing nbsp's with real spaces
return '<li>' + $('<div />').text($(this).text()).html().replace(/ /g, ' ') + '</li>';
});
//we could make this better by putting the caret at the end of the last LI, or something similar
}
}
});
jsfiddle at http://jsfiddle.net/aVuEk/5/
*I respectfully disagree with Diodeus that training is the best / easiest solution in all cases. In my situation, I have several contenteditable <UL>s on a page that are very in-line WYSIWYG (ie, not a lot of room for tinymce-style chrome) and used by casual, first-time, non-advanced users.

Trim not working in Coldfusion 8.0

I am trying to trim a string returned by one of my Coldfusion component but whatever I do Coldfusion add line feed at the start of the String without any reason resulting in an error in my Javascript. Do you have any idea of what's wrong with this code?
function back(){
window.location = <cfoutput>"#Trim(Session.history.getBackUrl())#"</cfoutput>;
}
The code above produce the following peace of HTML:
function back(){
window.location = "
http://dummy_server_address/index.cfm?TargetUrl=disp_main";
}
Looking at the Coldfusion specs here is the trim definition :
A copy of the string parameter, after removing leading and trailing spaces and control characters.
So it should have done the job! I am therefore wondering how to do that properly, I don't want to use replace or some similar function.
EDIT : very surprisingly this is working... but I don't like this solution, so if you have any other idea, or at least explanations about this behaviour.
<cfset backUrl = Session.history.getBackUrl()>
function back(){
window.location = <cfoutput>"#backUrl#"</cfoutput>;
}
Make sure your History component has output disabled. i.e:
<cfcomponent output=false >
Then make sure the getBackUrl function (and every other function) in the CFC also has output=false set.
Also, don't forget to use JsStringFormat on the variable, to ensure it is appropriately escaped:
<cfoutput>"#JsStringFormat( Session.history.getBackUrl() )#"</cfoutput>
Otherwise, there's a potential risk for JavaScript injection, or just JS errors, if the URL happens to contain ".
I've tested your current code and it works fine for me, I suspect that your CFC might be returning more then you think, which I obviously can't duplicate. I would personally always ensure that the component returns 'clean' results rather then removing junk characters after the fact :)
I have had similar issues in the past and it has always turned out to do with cfoutput, never got to the bottom of it. As a starting point I would rewrite this way and see if it makes a difference...
<cfset variables.stWindowLocation = '"' & Trim(Session.history.getBackUrl()) & '"'>
<cfoutput>
function back() {
window.location = #variables.stWindowLocation#;}
</cfoutput>

Greasemonkey script for auto-fill form and submit automatically

As the title suggests, I want to actually brute-force (don't pay attention, useless information) using grease-monkey script by trying each word/alphabet I provide.
But as I think jQuery is more easier than Javascript itself , so I would also like to embed jQuery in it.
The second thing thats bugging me is to actually submit a form with a specific value.
And is there a way to store some values...like if "abcd" did not work in the input field then the page would refresh thus this un-intelligent script won't be able to detect that this word did not work already..and it will try that same "abcd" word again.
Sorry for the vague details
var lastTried = parseInt(GM_getValue("LAST", "-1")); //GM_* will not work on Chrome to the best of my knowledge, would have to use cookies in that case.
if((docIK.location.href == AddressA) || (docIK.location.href == AddressA?error)) //for example, pseudo code
{
if(lastTried < wordsToTry.length){
lastTried++;
form.data.value = wordsToTry[lastTried]; //form.data.value is more pseudo code, wordsToTry is array of the words that you are going to provide
GM_setValue("LAST", lastTried.toString());
form.submit();
}
}
else //Address B
{
//Success
}