XPages - get value of a textarea inside a dialog - javascript

I am trying unsuccessfully to get a handle on the text input into a textarea which is contained inside an xe:dialog. The xe:dialog "pops up" after a button on the XPage is pressed. Here is my code:
<xe:dialog id="InputDialog5">
<xe:this.title>"Input Dialog</xe:this.title>
<xp:panel>
<xp:inputTextarea id="InputTextBox5" value="#{document1.InputTextBox5}"
cols="60" rows="4"></xp:inputTextarea>
</xp:panel>
<xe:dialogButtonBar id="dialogButtonBar15">
<xp:button value="OK" id="button37">
<xp:eventHandler event="onclick" submit="true"
refreshMode="complete" immediate="true">
<xp:this.action><![CDATA[#{javascript:
var request = facesContext.getExternalContext().getRequest();
var header = request.getHeader("Cookie");
var inputVal = #Middle(header,"InputTextBox5=",";")
setJobReferenceStatus(40,inputVal);
var redirect = "window.location='"+applicationScope.get("redirect")+"'";
facesContext.getViewRoot().postScript(redirect);}]]></xp:this.action>
<xp:this.script><![CDATA[
var inputvalue = document.getElementById("InputTextBox5").value;
alert("inputvalue = " + inputvalue);
dojo.cookie("InputTextBox5", inputvalue, { expires: 1 });
]]></xp:this.script>
</xp:eventHandler>
</xp:button>
</xe:dialogButtonBar>
</xe:dialog>
My idea is to get the value of the textarea, add it to a dojo cookie, retrieve the cookie value using SSJS and then pass the value to an SSJS function. However the code fails already at the stage of getting the textarea value. The line "alert("inputvalue = " + inputvalue);" is not executed and the dialog box remains "frozen". Any idea on how I can resolve this problem?

In order to get a handle on the text field from client side Javascript you have to know the XPages generated client id. So do this instead to calculate the id inside your CSJS:
<xp:this.script><![CDATA[
var inputvalue = document.getElementById("#{id:InputTextBox5}").value;
alert("inputvalue = " + inputvalue);
dojo.cookie("InputTextBox5", inputvalue, { expires: 1 });
]]></xp:this.script>

at a quick look I can already see two major obstacles:
a) document.getElementById(..) probably won't do (in fact I never really tried). I use XSP.getElementById(..) or dojo.byId(..) instead
b) your textarea will never ever have the same id at runtime that it has at design time. Just use your browser's sourcecode viewer, and you will see what I mean. Therefor we have to instructions to calculate the resulting ids for us like this:
dojo.byId("#{id:InputTextBox5}")
this then will be translated into the client object's final id so that your client side script code can find it.
Didn't look at the rest of your code, so I can't tell if there are more potential problems in there

Related

Click a button with part of current URL for language use

Halo everyone,
Cause I got a website which have many language and each language will have a subdirectory.
for example
1) sample.com/en
2) sample.com/jp
3) sample.com/zh
And the question is, I want the user stay on their curent page, when they change the language.
for example
sample.com/en/about-us (change to)
sample.com/jp/about-us
I have all the button for each language. Just want to use javascript to make each button will go to their own language with their current URL.
When I am in one language "about us" page, other language button link will turn to something like this.
US button > sample.com/en/about-us(base on current URL.)
Japan button> sample.com/jp/about-us (just change the country code with every other botton)
<input type="button" onclick="location.href=window.location.href.replace('en', 'el');" value="Greek" />
I found something like this, but with no luck.
Thanks everyone!!!!
To clean up the HTML, you can add a data attribute to each button for that button's language.
Then instead of using an inline event handler, you can delegate the event handler to the document itself. Then check for a data attribute for language. Then I'm splitting the current URL by the slash to get the page name. In my example, I'm logging the URL but you will want to location.href the URL instead.
var currentLocation = location.href.split("/");
let _page = (currentLocation.length == 4) ? "" : "/" + currentLocation[currentLocation.length-1];
document.addEventListener("click",function(e){
let btn = e.target;
if(btn.getAttribute("data-lang")){
_url = "/" + btn.getAttribute("data-lang") + _page;
console.log(_url)
//location.href = _url
}
});
<button data-lang="en">En</button>
<button data-lang="es">Es</button>
to redirect to another language, use the following code
<input type="button" onclick="window.location.href = window.location.href.replace('sample.com/en', 'sample.com/jp');" value="Greek" />

changing the textbox text to xxxx after tabbing out of it

I have a textbox that takes social security number. I have a requirement to change the first 5 numbers of social security number to X's once the user tabs out of that field so if the user enters
123456789
the number should become XXXXX6789
I tried doing it using txtSSN_TextChanged event, but that causes a postback. Can I do something like this in Javascript or Jquery. Below is my C# code:
string lastFourSSN = "";
lblHidden.Text = txtssn.Text.ToString().Replace("-", "");
lastFourSSN = Utility.Encode.GetLast(lblHidden.Text.ToString(), 4);
txtssn.Text = "XXX-XX-" + lastFourSSN;
It is a certainly a great idea on your part. jQuery will do the trick here.
First up, you can wire in a client side event and then turn auto-postback for that text box off (and likely you already did, since you note you never wanted a post-back for such a little task).
Ok, so your standard text box will look like this:
<asp:TextBox ID="TextBox1" runat="server"
onchange="mychange();" Width="280px" ClientIDMode="static" ></asp:TextBox>
I did add ClientIDMode static, it just makes the js more friendly to pick up the control.
And the "onchange" event is really the same as the server side post-back and change event (but of course client side).
So, our js? this works:
<script>
function mychange() {
var txt1 = $('#TextBox1');
s = txt1.val();
if (s.length > 5) {
s = "XXXXX" + s.substring(s.length - 4, s.length);
txt1.val(s);
}
}
</script>
There is no handy "right" function in js, or jQuery. But you can tweak the above a bit.
Note that substring is 0 based.
You could perhaps tweek the above. You could even remove the "if" in above, but the above quite much is a good base starting point.

How to set a textbox to an eval() in javascript

Okay, so I am trying to make a quiz where you enter some code and the quiz executes the code to see if what you typed is the same as the answer.
Here is the code and this is how the webpage looks like:
questions = "PRINT HELLO"
document.getElementById("Question").innerHTML = questions
function check(){
document.getElementById("answertext").innerHTML = eval(document.getElementById("answerbox").value)
}
#answerbox{
width:100%;
height:500px;
font-size:25px;
}
<h1>QUIZZZ</h1>
<h2 id = Question>JAVASCRIPT CONSOLE AND EXERCISES</h1>
<h1 id = "hi"></h1>
<textarea rows="4" cols="50" id = "answerbox">
//put your answer here
</textarea>
<textarea rows= '4' cols = "50" id = "answertext">lol</h1>
</textarea>
<input type = "submit" onclick = "check()">
Run the code to see
I want the user to enter a document.write() statement inside the textbox, and have the evaluated code to be shown in the smaller multiline text box.
Try to put a document.write() statement in the textbox and run it. You should see a new page instead of the answer written in the text box.
I know that document.write is a bad practice to output things in javascript, and I know that you can edit raw HTML, but is there any other way a user can print a message without doing any of these choices?
Don't use eval.
Using eval is considered to be a bad practice. Read more for Why here. You can ask your user to just return the answer using a return statement as shown below, instead of asking them to do something complicated like document.write().
// Ask them to do this:
var codeFromTheAnswerBox = "var answer = 'HELLO'; return answer;"
// instead of this:
// var codeFromTheAnswerBox = "var answer = 'HELLO'; document.write(answer)";
// execute user's code
var code = new Function(codeFromTheAnswerBox);
var returnValue = code();
// Now do whatever you want to do with the answer like the following
alert("Your answer is " + returnValue);
You can use .append instead of document.write()
document.body.append("Hello World!", document.createElement('p'));
If you go to the Console tab of the DevTools in your browser, you can type javascript code and press enter to execute it. You will get helpful error messages that should help you with your project.
Ok. I realized your problem.
You can use iframe for this purpose. Add an iframe with an id similar 'answerIframe' instead of #answertext element.
Then move your #answertext element to a separated html and set address of iframe to it.
In iframe:
window.check=function(){
document.getElementById("answertext").innerHTML =
eval(document.answer);
}
And add a button to your iframe too. for iframe's button set this:
onclick="window.check()"
Add an Id to iframe's button similar: iframe_bt.
Now, when user clicks on button (in current page, no iframe) must call this (new check function in your main page):
function check(){
document.getElementById('#answerIframe').contentWindow.document.answer=document.getElementById("answerbox").value;
document.getElementById('#answerIframe').contentWindow.document.getElementById('#iframe_bt').click();
}
Also in your iframe, call a function in document's onload and add answertext dynamically if is not exists (because document.write) or reset the iframe before execute per answer.
Another way is replacing the document.write with other code similar: elem.insertAdjacentHtml(..) or etc before execute it.
Excuse me for any mistake, i typed with my cellphone.
I did not have a tool to test it, but the method and its generalities are correct.

Submitting data from text box to Firebase not working

I have this text box in HTML:
<script src="../js/writeTo.js"></script>
<form>
<div class="post-title">
<input type="text" placeholder="Post Title">
</div>
<div class="post-content">
<textarea type="text" placeholder="Post Content"></textarea>
</div>
<button type="submit" class="submit">Submit</button>
</form>
and my js file called writeTo.js contains this code:
var url = "https://blog-posts.firebaseio.com/";
var firebaseRef = new Firebase(url);
function funct1()
{
var title = $('#post-title').val();
var post = $('#post-content').val();
var date = Date();
firebaseRef.set({Title: +title, Content: +post, Date: +Date()});
}
submit.onclick = funct1();
When I type something in my text box and click submit, I look at my Firebase and there is no new data (I'm also new to using Firebase).
It does not work, can anyone see the problem? (There are probably a few, I am new to JavaScript)
There are a few problems with your script. I've solved them in this jsfiddle, but will also explain below.
Getting the text content of your inputs
Your HTML for the inputs looks like this:
<div class="post-title">
<input type="text" placeholder="Post Title">
</div>
The JavaScript you use to read the value is:
var title = $('#post-title').val();
If you read the documentation for val, you'll see that it is meant to be invoked on the input element itself. You are invoking it on the wrapping div.
The simplest change is to get the value like this:
var title = $('#post-title').text();
Associating the handler with the form
You hook up your event handler with the form like this:
submit.onclick = funct1();
Unfortunately this will not work as you expect it to.
What is does is:
Invoke funct1
Assign the return value of funct1 to onclick
What you instead want to do is:
submit.onclick = funct1;
So this will assign funct1 to onclick.
You might want to read up on more modern approaches of assigning event handlers btw.
Passing the values to Firebase
Your code for passing the values to Firebase seems a bit off. Use this instead
firebaseRef.set({Title: title, Content: post, Date: date});
Cancel the regular browser handling of the form submit
The browser normally handles clicks on a form's submit button by posting the form's values to a URL.
But in your application you are handling this yourself, so you should tell the browser to ignore the submit.
You can do this by returning false from your function:
return false;
Note that this will give the following warning in Chrome:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
So you should indeed consider using event.preventDefault() instead of returning false. See the total code below for how to do that.
Complete code
var url = "https://blog-posts.firebaseio.com/";
var firebaseRef = new Firebase(url);
function funct1(evt)
{
var title = $('#post-title').text();
var post = $('#post-content').text();
var date = Date();
firebaseRef.set({Title: title, Content: post, Date: date});
evt.preventDefault();
}
var submit = document.getElementsByTagName('button')[0];
submit.onclick = funct1;
Adding a new post, instead of overwriting the existing one
Your code will now replace the blog post that lives at your Firebase. I imagine that you'll probably prefer to add a new post, when pressing the submit button.
To accomplish this, you'll need to call Firebase's push function. Firebase has some great documentation on managing lists.
The gist of it is this though:
var postRef = firebaseRef.push(); // create a new post
postRef.set({Title: title, Content: post, Date: date});
So you create a new post and then set your values on that, instead of on the top-level Firebase ref.

How can I send POST data and navigate with JQuery?

On my blog I have a lot of <pre> blocks containing code snippets.
What I want to do is add a .click() handler to all the <pre> elements on the page which will send its content to another page - let's call it viewcode.php - via POST.
I know how to send information to this page using $.ajax, I'm just not sure how to send the information and navigate to the page.
The idea is that visitors can click a <pre> which will navigate to another page containing the code on its own for readability and easy copy / paste.
I have a feeling the solution is dead simple and probably obvious, I just can't think of it.
Not sure I would handle it this way, probably I would simply pop up a dialog with the code rather than leave the page, but you could handle this by building a form using javascript then triggering a submit on that form instead of using AJAX.
Using dialogs with jQuery UI:
$('pre').on('click', function() {
$('<div title="Code Preview"><p>' + $(this).text() + '</p></div>').dialog({
... set up dialog parameters ...
});
});
Build a form
$('pre').on('click', function() {
var text = $(this).text();
$('<form class="hidden-form" action="something.php" method="post" style="display: none;"><textarea name="code"></textarea></form>')
.appendTo('body');
$('[name="code"]').val(text);
$('.hidden-form').submit();
});
You could use a hidden <form> element. Then set the onclick() attribute of the <pre> to copy the value from the <pre> to the form. Optionally, you can set the action attribute to select the page you'd like to post the information to. Finally, submit that form.
I know it's not elegant, but it'll work.
If your code snippets are stored somewhere in a database or files, I suggest you just link the snippets to a page where you get the snippet based on some identifier.
If the snippets are only contained in your html, and you just want to display them in a cleaner way, you shouldn't need any ajax posting. You might want to Use a hover div or a jquery plugin, that pop's up and shows a cleaner piece of code obtained from the pre element, something like:
$('pre').click(function() {
var code = $(this).html(); //this is the pre contents you want to send
$('#hoverDiv').html(code).show();
});
Yes, you have to create a form and submit it. You can do all sorts of things with ajax posts/gets but the only way to navigate to a post result is via an actual form post. Here is concise version of it:
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();
My code does this:
// Navigate to Post Response, Convert first form values to query string params:
// Put the things that are too long (could exceed query string limit) into post values
var form = $('#myForm');
var actionWithoutQueryString = form[0].action.split("?")[0];
var action = actionWithoutQueryString + '?' + $.param(form.serializeArray());
var html = myArray.map(function(v, i) { return "<input name='MyList[" + i + "]' value='" + v + "'/>"; }).join("\n");
$('<form style="display: none;"/>').attr('action', action).html(html).appendTo('body').submit();

Categories

Resources