Create Form Row with Dojo - javascript

I am new to Dojo and working with someone else's code. Currently, this function looks to see the value of a dropdown box. Based on that value, it adds another form box, on the fly, for a user to fill out. In all the examples I have, I've only seen the function create one added form box. In a particular case, though, I'd like to add a second row with another form box. I thought maybe repeating the line twice would do the trick, but it doesn't. Any thoughts how to do this? Thanks in advance...
Switch Statement:
if (form_row != null)
dojo.destroy(form_row);
//Add the correct new field to the form.
switch (inquiry.selectedIndex) {
case place_order:
html = this.create_form_row(id, "Account Number");
break;
case order_status:
html = this.create_form_row(id, "Order Number");
break;
case telalert_signup:
html = this.create_form_row(id, "Account Number");
break;
case invoice_questions:
html = this.create_form_row(id, "Invoice Number");
break;
case new_option:
html = this.create_form_row(id, "Invoice Number");
(WANT TO CREATE A SECOND ROW HERE!)
break;
default:
}
Function being called:
create_form_row: function(id, label) {
//Container
var a = dojo.create("div", { id: id, className: "question", style: "padding-top:4px;" });
//Label
var b = dojo.create("div", { className: "label", innerHTML: label, style: "margin-top:8px;" }, a);
//Field
var c = dojo.create("div", { className: "field" });
var d = dojo.create("span", { className: "full_number_span span" });
var e = dojo.create("input", { type: "text", className: "textbox acct_num", name: label }, d);
dojo.place(d, c);
dojo.place(c, a);
return a;
}

If you tried
case new_option:
html = this.create_form_row(id, "Invoice Number");
html = this.create_form_row(id, "SOMETHING ELSE");
break;
it wouldn't work because you would just overwrite the html variable and throw away the first one.
You can either change stuff so that html is supposed to be a list of nodes or you can try wrapping your two form nodes inside a single one
var html = dojo.create('div');
dojo.place(this.create_form_row(...), html);
dojo.place(this.create_form_row(...), html);

Related

Change liferay-ui:input-localized XML with javascript

I have the following tag in my view.jsp:
<liferay-ui:input-localized id="message" name="message" xml="" />
And I know that I can set a XML and have a default value on my input localized. My problem is that I want to change this attribute with javascript. I am listening for some changes and call the function "update()" to update my information:
function update(index) {
var localizedInput= document.getElementById('message');
localizedInput.value = 'myXMLString';
}
Changing the value is only updating the currently selected language input (with the whole XML String). The XML String is correct, but I am not sure on how to update the XML for the input with javascript.
Is this possible?
PS: I have posted this in the Liferay Dev forum to try and reach more people.
After a week of studying the case and some tests, I think that I found a workaround for this. Not sure if this is the correct approach, but it is working for me so I will post my current solution for future reference.
After inspecting the HTML, I noticed that the Liferay-UI:input-localized tag creates an input tag by default, and then one more input tag for each language, each time you select a new language. Knowing that I created some functions with Javascript to help me update the inputs created from my liferay-ui:input-localized. Here is the relevant code:
function updateAnnouncementInformation(index) {
var announcement = announcements[index];
// the announcement['message'] is a XML String
updateInputLocalized('message', announcement['message']);
}
function updateInputLocalized(input, message) {
var inputId = '<portlet:namespace/>' + input;
var xml = $.parseXML(message);
var inputCurrent = document.getElementById(inputId);
var selectedLanguage = getSelectedLanguage(inputId);
var inputPT = document.getElementById(inputId + '_pt_PT');
inputPT.value = $(xml).find("Title[language-id='pt_PT']").text();
var inputEN = document.getElementById(inputId + '_en_US');
if (inputEN !== null) inputEN.value = $(xml).find("Title[language-id='en_US']").text();
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
var inputLabel = getInputLabel(inputId);
if (selectedLanguage == 'pt-PT') inputLabel.innerHTML = '';
else inputLabel.innerHTML = inputPT.value;
if (selectedLanguage == 'pt-PT') inputCurrent.value = inputPT.value;
else if (inputEN !== null) inputCurrent.value = inputEN.value;
else waitForElement(inputId + '_en_US', inputCurrent, inputId, xml);
}
function getSelectedLanguage(inputId) {
var languageContainer = document.getElementById('<portlet:namespace/>' + inputId + 'Menu');
return languageContainer.getElementsByClassName('btn-section')[0].innerHTML;
}
function getInputLabel(inputId) {
var boundingBoxContainer = document.getElementById(inputId + 'BoundingBox').parentElement;
return boundingBoxContainer.getElementsByClassName('form-text')[0];
}
function waitForElement(elementId, inputCurrent, inputId, xml) {
window.setTimeout(function() {
var element = document.getElementById(elementId);
if (element) elementCreated(element, inputCurrent, inputId, xml);
else waitForElement(elementId, inputCurrent, inputId, xml);
}, 500);
}
function elementCreated(inputEN, inputCurrent, inputId, xml) {
inputEN.value = $(xml).find("Title[language-id='en_US']").text();
var selectedLanguage = getSelectedLanguage(inputId);
if (selectedLanguage == 'en-US') inputCurrent.value = inputEN.value;
}
With this I am able to update the liferay-ui:input-localized inputs according to a pre-built XML String. I hope that someone finds this useful and if you have anything to add, please let me know!
To change the text value of an element, you must change the value of the elements's text node.
Example -
xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue = "new content"
Suppose "books.xml" is loaded into xmlDoc
Get the first child node of the element
Change the node value to "new content"

Changing values of DIV buttons using javascript

this is a noob question:
I'm defining a button in HTML like this:
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
To avoid showing too many buttons I'd like the button to toggle between
value="Select good points"
and
value="Select bad points
So in javascript i'm using
$(".btn-change").on("click", function() {
alert("you pressed the " + nextMark + " button");
switch(nextMark) {
case "bad":
nextMark = "good"
document.getelementsbyclassname("btn-change").value="Select good points";
break;
case 'good':
nextMark = "bad"
$("btn-change").value = "Select bad points";
break;
}
}
The nextMark var changes the colour of marks placed on a leaflet map depending on the value of the button.
The alert shows the case structure is working but the button value isn't changing - what is the correct way of doing this?
jsfiddle right here
To assign a value to the input using JQuery you need to use .val() and not .value
var nextMark = "good";
$(".btn-change").on("click", function() {
switch (nextMark) {
case "bad":
nextMark = "good";
$(".btn-change").val("Select good points");
break;
case 'good':
nextMark = "bad";
$(".btn-change").val("Select bad points");
break;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
You need to specify index to document.getElementsByClassName("btn-change")[0].value = as 0
var nextMark = "good";
$(function(){
$(".btn-change").on("click", function() {
alert("you pressed the " + nextMark + " button");
switch(nextMark) {
case "bad":
nextMark = "good"
document.getElementsByClassName("btn-change")[0].value = "Select good points";
break;
case 'good':
nextMark = "bad"
document.getElementsByClassName("btn-change")[0].value = "Select bad points";
break;
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>
First, you're missing an ending ); to close of the … .on("click" ….
If you are using jQuery, you need to remember to include that first (at the top in <head>), then you should define the JavaScript sheet later. Common practice is at the end, right before the </body> tag.
<script type="text/javascript" src="js.js"></script>
</body>
Next, for the alert, nextMark is not defined.
You can do that with this. when using jQuery, you should keep to it, so use $(this).
Put this inside the function to define nextMark:
var nextMark = $(this);
Once that is done, you need to get the value of it, unless it will say you pressed the [object Object] button. You do that by adding .val() at the end of the target with jQuery; so nextMark.val() inside the alert.
Now to make it switch, you could use a simple if-else statement to switch between the two with:
if (nextMark.val() == "Select good points") {
nextMark.val("Select bad points");
} else {
nextMark.val("Select good points");
}
If you want to use switch, then at least to make it work you need to give it what case it is. What goes inside the (…) of the switch is the case it will use to check.
If I put switch(x) and define x as var x = 1 or var x = "one, we will use this to decide which case to use:
case 1: or case "one": will be executed.
var x = 1;
var y = "one";
switch(y) {
case 1:
// "y" is not 1.
break;
case "one":
// "y" is "one", so this will be exectuted.
break;
}
Therefore, we need to define when the button is "good" or "bad". You could do this by using the literal value, like:
var myMark = $(this).val();
switch(myMark) {
case "Select bad points":
$(this).val("Select good points");
break;
case 'Select good points':
$(this).val("Select bad points");
break;
}
$(".btn-change").on("click", function() {
var nextMark = $(this);
alert("you pressed the " + nextMark.val() + " button");
/* Optional method: */
// if (nextMark.val() == "Select good points") {
// nextMark.val("Select bad points");
// } else {
// nextMark.val("Select good points");
// }
var myMark = $(this).val(); /* or var myMark = nextMark.val(); */
switch(myMark) {
case "Select bad points":
$(this).val("Select good points");
break;
case 'Select good points':
$(this).val("Select bad points");
break;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- jQuery included in this example to make it work -->
<div>
<input class="btn-change" type="button" value="Select good points" />
</div>

javascript - How to show value from object by matching user input to its key?

I want to make conversion tool which converts one code (user input) to another (predefined). I decided to use Javascript object as a container for codes, and my function will take user input which is actually a key from a javascript object, match it to the one in Code container and if the match is found, the function will display value to the alert box.
I made one code, but it does not work. I tried to find the solution but for now, I failed.
Here is my code:
$(document).ready(function() {
$("#convert").click(function(){
var GardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"995331",
"A2" :"995332",
"A2A" :"995333",
"A3" :"995334",
"A3A" :"995335",
"A3B" :"995336",
"A4" :"995337",
"A4A" :"995338",
"A4B" :"995339",
"A4C" :"995340",
"A4D" :"995341",
"A4E" :"995342",
"A5" :"995343",
"A5A" :"995344",
"A5B" :"995345",
"A5C" :"995346",
"A6" :"995347",
};
var userInput = $("#userInput").val; /*for example 'A1'*/
if (userInput in GardinerToUnicodeCodePoint) {
alert(/*value of key 'userInput' -> 995328*/);
} else {
alert("No code found!");
}
});
});
You can use [] after calling the object to get the key value pair:
GardinerToUnicodeCodePoint[userInput]
Change your code to:
var userInput = $("#userInput").val; /*for example 'A1'*/
if (userInput in GardinerToUnicodeCodePoint) {
alert(GardinerToUnicodeCodePoint[userInput]);
} else {
alert("No code found!");
}
See jsfiddle: https://jsfiddle.net/wy70s3gj/
function getReturnCodeUsingKey(keyFromUserInput)
{
var GardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"etc"
};
returnVal = GardinerToUnicodeCodePoint[keyFromUserInput];
return returnVal ? returnVal : "error: no match found";
}
Pass that function your string input from the user, and it'll return what you want I think.
So, you're full solution would look like this:
$(document).ready(function() {
$("#convert").click(function(){
var userInput = $("#userInput").val(); /*for example 'A1'*/
// a call to our new function keeping responsibilities seperated
return getReturnCodeUsingKey(userInput);
});
});
function getReturnCodeUsingKey(keyFromUserInput)
{
var GardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"995331",
"A2" :"995332",
"A2A" :"995333",
"A3" :"995334",
"A3A" :"995335",
"A3B" :"995336",
"A4" :"995337",
"A4A" :"995338",
"A4B" :"995339",
"A4C" :"995340",
"A4D" :"995341",
"A4E" :"995342",
"A5" :"995343",
"A5A" :"995344",
"A5B" :"995345",
"A5C" :"995346",
"A6" :"995347",
};
// set a variable to hold the return of the object query
returnVal = GardinerToUnicodeCodePoint[keyFromUserInput];
//return valid value from object, or string if undefined
return returnVal ? returnVal : "error: no match found";
}
The issue here as expresed in the comments by #epascarello is that you should use $("#userInput").val(); with the parenthesis
Code example:
$('#convert').click(function() {
var GardinerToUnicodeCodePoint = {
A1: '995328',
A1A: '995329',
A1B: '995330',
A1C: '995331',
A2: '995332',
A2A: '995333',
A3: '995334',
A3A: '995335',
A3B: '995336',
A4: '995337',
A4A: '995338',
A4B: '995339',
A4C: '995340',
A4D: '995341',
A4E: '995342',
A5: '995343',
A5A: '995344',
A5B: '995345',
A5C: '995346',
A6: '995347'
};
var userInput = $('#userInput').val();
var result = userInput in GardinerToUnicodeCodePoint
? 'Value of key \'userInput\' -> ' + userInput
: 'No code found!';
console.log(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="userInput">
<button id="convert">Submit</button>

JavaScript - Adding an object to the end of an array through a input field

I am trying to dynamically add an object with values from an input field to the end of an array using JavaScript. The only catch is that I'm trying to do it with an input field. Here's what I want to happen:
The user types in something in a text field
My program already adds a unique ID for it
Add it to the end of an array in the form of a object
Keep on adding objects to that array
This is what I want in my JSON file:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, {
"id": 1,
"description": "Task #2 Description"
}, {
"id": 3,
"description": "Task #3 Description"
}]
}
What I am currently getting is:
{
"list": [{
"id": 0,
"description": "Task #1 Description"
}, ]
}
Every time I add a new Task, it replaces the one that is already there.
Here is my JavaScript code:
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.onclick = function() {
id = indentification++;
description = content.value;
var task = {
list: []
}
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
I would really appreciate it if anyone could help me out. I've spent hours trying to figure it out. Thanks!
The problem is here:
var task = {
list: []
}
task.list.push({id, description});
Each time you do this your list become empty then add new item.
change to this
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
var task = {
list: []
}
submit.onclick = function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8"); // what're you doing here, browser do not allow write file to disk
}
There are a couple of things that you need to consider here:
Form submit must be refreshing the page and resetting your global variables. Thus you need to prevent default action on click of submit.
(as mentioned in earlier answers) The list is being initiated on every click. You will need to initialize the variable task outside the onClick function
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
//initialize outside the on click function
var task = {
list: []
}
submit.onclick = function(e) {
//This prevents page refresh on form submission and preserves the global variable states
e.preventDefault();
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}
This should hopefully solve your problem.
// This is the counter
var indentification = 0;
// This is the submit button
var submit = document.getElementById("submit");
// This is the text field
var content = document.getElementById("text");
submit.addEventHandler("click", function() {
id = indentification++;
description = content.value;
task.list.push({id, description});
var jsonifyTask = JSON.stringify(task);
fs.writeFile("tasks.json", jsonifyTask, "utf8");
}

How to replace text based on counter value?

Call to the count function made by two group of checkboxes. First group represents categories, when clicked subjects for that category will be listed out.
html: id: counter displays count value. id: select replaces text acordingly
<div class="small-8 text-left columns" style="left:-30px;">
<span id="counter"><span id="count">0</span></span>
<span id="select">Select Subjects</span>
</div>
script:(categories group) To pass value for the subjects to be fetched by ajax. updateCount();is the count function call.
$("input[type=checkbox][id^=level]").change(function() {
var selectedval = $(this).val();
if($(this).is(":checked")) {
var selectedtext = $(this).next().text();
sendtobox(selectedval, $("#slider1").val(),"regis");
} else {
$("th."+selectedval).remove();
updateCount();
}
});
(subjects group)
$(document).on('change', '[id^=sub][type=checkbox]', updateCount);
count function:
function updateCount () {
$('#count').text($('[id^=sub][type=checkbox]:checked').length);
}
script to replace text:
$(".close-reveal-modal").on("click",function()
{
document.getElementById("select").innerHTML = "Select subject";
var str = document.getElementById("select").innerHTML;
var res = str.replace("Select subject", "Selected Subject");
document.getElementById("select").innerHTML = res;
});
Now I can replace text and the count works just fine! My problem is it doesn't obey the English grammar!
If 0 item/subjects returned, the text should be 0 Selected Subjects and if more than 1 is checked, it should say the same. See the (s) must be added in 'subject' word.
My problem is , I couldn't identify number of counts to replace this text.
I want someting like this:
if ($("#count") >1 || ($("#count")==0))
{
var res = str.replace("Select subject", "**Selected Subjects"**);
document.getElementById("select").innerHTML = res;
}
else
{
var res = str.replace("Select subject", "**Selected Subject"**);
document.getElementById("select").innerHTML = res;
}
I tried to alert $('#count').length , it red like this each time the checkbox checked:
1 1 1 1
What I'm expecting is
1 -when clicked once
2 - when clicked twice
This way would be easier for me to replace text indeed!
it sounds like you want the TEXT of the span with id 'count' for that comparison:
if ($("#count").text() == "1") {
// singular
}
else {
// plural
}

Categories

Resources