jQuery variable reference order - javascript

I have a question, in the code below if I declare the start_date & end_date variables before $.each the last part which inserts some span tags doesn't work, but if they are declared after $.each then it does.
Why is this? I cannot figure it out and I have no ideas at all.
var dates_para = $("#field_dates p");
dates_para.each(function(){
var html_content = $(this).html();
$(this).html(html_content.replace("–", ""));
});
var start_date = $("#start_date");
var end_date = $("#end_date");
start_date.after("<span id='start_datepicker' class='datepicker'></span>");
end_date.after("<span id='end_datepicker' class='datepicker'></span>");

If the #start_date and #end_date elements are parts of the paragraphs, then writing new html to the paragraphs will create new elements and the old references are invalidated.

Related

Parse HTML using javascript

I have a string which is inside the HTML code.
here, I need to get a string separately using javascript.
outsidePara
and
insidePara
var msg="<p><sp id='msgId'>insidePara</sp>outsidePara</p>"
Is the <p> always in the same format (i.e. will always have a ```
If so, jQuery's $('p sp#blablabla') should be able to help as you can then select the text of the parent <p> and trim off the <sp>
var sender = $('p sp#blablabla').text()
var msg = $('p sp#blablabla').parent('p')
var msgHTML = msg.html()
var msgBody = msgHTML.substr(msg.length - (9 + sender.length)); // 9 for the two <sp> tags
const cheerio = require('cheerio')
const $ = cheerio.load(`<p><sp id=\"blablabla\">puppy</sp>hi</p>`)
console.log($("p sp").text()) // will print puppy
console.log($("p").contents().last().text()) // will print hi

Calculate age based on birthday with JQuery

I am trying to calculate how old a person is with jQuery. I tried using this code but I am not getting any results. I assume that I cannot but a varible in date(). What could I do to make this work?
<p id="age">2015/01/01</p>
var ptag = $('#age');
var birthdate = new Date(ptag);
var cur = new Date();
var diff = cur-birthdate;
var age = Math.floor(diff/31536000000);
alert(age);
You need to get the contents of the #age element, not the element itself.
var ptag = $('#age').text();
var age = new Date() - new Date($('#age').text());
age /= 31536000000;
$(selector).text() will return the content of a DOM element as a text.
And since we do not want to use a bunch of variables, we simply define one, as the difference of two dates: the 'now' minus the one from the text.
And since the above is in miliseconds, we devied it... and that will return age in years.
jQuery .text()

document.getElementById doesn’t work

If I write code 2 without code 1, the code works and it shows me “aaaaa”.
But if I write code 1 and code 2, the code doesn’t work. Instead of showing me “vvvaa”, it doesn’t show me anything (not “aaaaa” and not “vvvaa”).
Why doesn’t it work? (The document.getElementById doesn’t send the information to the <div>.)
Code 1:
document.getElementById('na').innerHTML = "vvvaa";
Code 2:
document.write("<div id='na'> aaaaa </div>");
Complete Code: (the only thing on the page)
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
timeago('1376743609');
document.write("<div id='na'> aaaaa </div>");
</script>
Order matters. You cannot access your element 'na' before having it in the document.
You naturally need to add the element to the document first. If that's done, you can access it by functions like getElementById().
This...
document.write("<div id='na'></div>");
document.getElementById('na').innerHTML = "vvvaa";
... will work.
You may shortcut this to:
document.write("<div id='na'>vvvaa</div>");
I am assuming your console says that document.getElementById('na') is undefined and innerHTML is not a method of undefined. This is caused by the fact that there is no such element when the code is called. A fatal error will stop any further javascript execution, in this case your document.write.
Add the element to your document first before trying to access it via document.getElementById
You can't access a piece of text unless it really does exist. In your case, you are trying to access the text when it doesn't even exist at that point. The order matters. Code 2 should go first and Code 1 should go last. First write the text, then access it.
The document.write only be passed after timeago() therefore does not exist over the <div>, so just call "timerago" after using document.write Try:
<script>
function timeago(time) {
var new_date = new Date();
var time_ago = Math.floor(new_date.getTime()/1000-time);
var d = Math.floor(time_ago/24/60/60);
var h = Math.floor((time_ago-d*24/60/60)/60/60);
var m = Math.floor((time_ago-d*24/60/60-h*60/60)/60);
var s = Math.floor(time_ago-d*24/60/60-h*60/60-m*60);
document.write(d+"d - "+h+"h - "+m+"m - "+s+"s");
document.getElementById('na').innerHTML="vvvaa";
// setTimeout( function(){ timeago(time); }, 2000 );
}
document.write("<div id='na'> aaaaa </div>");
timeago('1376743609');
</script>

Finding the difference between two fields using JavaScript in iText

I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.

create javascript timestamp from innerhtml string values

I'd like to create a javascript timestamp based on a rails date_select and time_select property. I attached an onChange function to the select helper and fetching the innerhtml to read the values into a div which works fine. Now I want to use those strings from the select property and create a timestamp in js (using it for validations).
I did first try this by making integers from the innerhtml values:
function insertText10()
{
var start_day = document.new_link['link[start_at(3i)]'];
var start_month = document.new_link['link[start_at(2i)]'];
var start_year = document.new_link['link[start_at(1i)]'];
var start_hour = document.new_link['link[start_at(4i)]'];
var start_minute = document.new_link['link[start_at(5i)]'];
var selOption1 = start_day[start_day.selectedIndex];
var selOption2 = start_month[start_month.selectedIndex];
var selOption3 = start_year[start_year.selectedIndex];
var selOption4 = start_hour[start_hour.selectedIndex];
var selOption5 = start_minute[start_minute.selectedIndex];
start_date = new Date(parseInt(selOption3.innerHTML),parseInt(selOption2.innerHTML),parseInt(selOption1.innerHTML),parseInt(selOption4.innerHTML),parseInt(selOption5.innerHTML),0,0);
then by using strings:
start_date = new Date(selOption3.innerHTML+selOption2.innerHTML+selOption1.innerHTML+selOption4.innerHTML+selOption5.innerHTML);
but neither works.
What am I doing wrong?
--
PS: I checked the w3s docu http://www.w3schools.com/jsref/jsref_obj_date.asp to find the solution above.
Solved:
start_date = new Date(parseInt(selOption3.value),parseInt(selOption2.value),parseInt(selOption1.value),parseInt(selOption4.value),parseInt(selOption5.value),0,0);

Categories