Javascript popup/alert [closed] - javascript

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 have a form that I would like the user to confirm their order is correct. I get two pop ups this way and only want one that summarises the order and prompts for confirmation with a message.
When the user clicks ok, the popup closes and returns to form for submission (there is a submit button). However, if the user clicks cancel then the form resets and popup closes.
Any help is appreciated. Thank you
Note: This is part of an assessment and required to be done this way even though there are better ways.
// JavaScript Document
function display() {
var x=document.confirm.qty.value;
var y=document.confirm.price.value;
var z=document.confirm.total.value;
alert("Quantity:"+x+" \n "+"Price Each:"+y+" \n "+"Total Price:"+z );
if(confirm('Confirm your order?'));
}

You are actually looking for window.confirm(). That is the dialog that displays two buttons: OK and Cancel. It also returns a boolean value indicating whether OK or Cancel was selected.
Assuming that your display function is an onSubmit handler, you could rewrite it like so:
function display(event) {
var x = document.querySelector('[name="qty"]'),
y = document.querySelector('[name="price"]'),
z = document.querySelector('[name="total"]');
// Simplified string creation with ES6 String Interpolation
var confirm = window.confirm(`
Quantity: ${x.value}
Price Each: ${y.value}
Total Price: ${z.value}
`);
if (confirm == true) {
// All OK
return;
} else {
// Blocking default `submit` event
event.preventDefault();
// Resetting form
x.value = null;
y.value = null;
z.value = null;
return;
}
}
Do not forget to pass in the event to the callback:
<form onsubmit="display(event);">

It should be
return confirm('...
Further make sure the onclick is has return in front of your method name in HTML.

Popups are quite uncommon for this use-case. Create a div which overlays the whole site (makes all other things unclickable). In that div create another one which is centered where you ask for the confirmation.

I think you want something like this:
function display()
{
var x = document.getElementById('qty').value;
var y = document.getElementById('price').value;
var z = document.getElementById('total').value;
var result = confirm('Quantity:' + x + '\nPrice Each: ' + y + '\nTotal Price: ' + z + '\n\nConfirm your order?');
if(result)
{
// user has pressed OK
}
else
{
// user has pressed cancel
}
}

Related

How to call querySelector for different class? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Need to make a webpart which gets data from API in JSON format. I generate a table from JSON with projects number. Then I change each td to link with class="project_number".
Now each position has it's specific class. No I need each link to direct to project details ot url like: https://XXX.azurewebsites.net/api/protocollines?protocolNo=PR0002
I don't know what parameter should I place in querySelector to have addEventListener for each link.
document.querySelector("???").addEventListener('click', *function*);
function changeToLink(){
var tableCells = Array.from(document.getElementsByTagName('td'));
var i;
var proNo = "PR0";
for (i=0; i<tableCells.length; i++ && isContains == true) {
var proFromArray = tableCells[i].innerHTML;
var isContains = proFromArray.includes(proNo);
if(isContains == true){
var tdElement = document.getElementsByTagName('td')[i];
console.log('Profrom: ' + proFromArray);
tdElement.innerHTML = `<a class="${proFromArray}" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
}
}
}
document.querySelector(`??`).addEventListener('click', *function*);
There's a few ways to do this.
Option 1
You could create the anchor elements using JS, and add the onclick event when you create each one, like:
// inside the if(isContains == true){
var a = document.createElement('a');
a.className = proFromArray;
a.href = `https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}`;
a.textContent = proFromArray;
a.onclick = this.getJsonData;
I created a Fiddle to demonstrate how it works: https://jsfiddle.net/brettnolf/f3xd7ag1/
Option 2
Now, if you need to create it in the form of a string and later call querySelector on what you created, you could add the same class to each anchor tag:
tdElement.innerHTML = `<a class="${proFromArray} pro-elem" href='https://XXX.azurewebsites.net/api/protocollines?protocolNo=${proFromArray}'>${proFromArray}</a>`
Then add the event listener, like:
var pros = document.querySelectorAll('.pro-elem')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
Option 3
If both of those solutions are out of the question, you could use a query selector wildcard and add the event listener similar to the above:
var pros = document.querySelectorAll('[class^=PR0]')
// or if you wanted to be really specific:
// document.querySelectorAll('td a[class^=PR0]')
for (var i = 0; i < pros.length; i++) {
pros[i].addEventListener(this.getJsonData);
}
You can see this last solution in action if you pull up Chrome dev tools here https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll and enter document.querySelectorAll('[class^=title]') in the Console.
Note that the last two options will only work after the elements have been added to the DOM. In the first option, you add the listener when you create the element, so you do it on the fly.

Textarea and radio buttons visibility issues

So what I'm trying to do is basically check if the response from the server contains alternatives. If it does then it should print the alternatives out , hide the text area where I would answer the question if the question did not contain alternatives and show the radio buttons. Problem is, it prints out the response, but never hides/shows the text area or the radio buttons.
I tried putting the code for the visibility in a button to see if it works on click, and it does, but it does not work when I put the same code in the if statement.
Also, another problem is that instead of printing out the actual alternatives, it just prints out Object object, but when I try to print out the question, it prints it out correctly.
HideAllRadios and ShowArea functions are basically the same as what's in the if statement, but reversed.
Here is the code:
QuestionReq.onreadystatechange = function(){
if(QuestionReq.readyState === 4 && QuestionReq.status === 200) {
response = JSON.parse(QuestionReq.responseText);
console.log(response);
questionLink.innerText = response.question;
url = response.nextURL;
// questAltLink.innerText = response.alternatives;
if(response.alternatives !=null){
questAltLink.innerText = response.alternatives;
AnswerArea.style.visibility = "hidden";
RadioArea.style.visibility = "visible";
}
HideAllRadios();
ShowArea();
}
Here is how they are declared:
var questions = function () {
var AnswerArea = document.getElementById("AnswerArea");
var RadioArea = document.getElementById("radioplace");

Javascript word count price calculator

Everything works fine, except the problem with a pricing plan selection. What I want is that whenever user clicks on a specified price (even while the text is already present in textarea), it should immediately update the final Price. But it won't change at first click.
I should click twice on it instead. Any one got an idea what's wrong ?
So here how it looks like:
And here comes the javascript code:
function __textCalculatorCounter(){
var value = $('#calculateText').val();
var spanWords = $('#calculatedWordsTotal'),
spanChars = $('#calculatedCharsTotal'),
spanPrice = $('#calculatedPriceTotal');
if (value.length == 0) {
spanWords.html(0);
spanChars.html(0);
return;
}
var selectedPricing = $("input[name=calculatePrice]:checked").val();
var wordCount = value.trim().replace(/\s+/gi, ' ').split(' ').length;
var totalChars = value.length;
var totalPrice = (wordCount * parseFloat(Math.round(selectedPricing * 100) / 100));
spanWords.html(wordCount);
spanChars.html(totalChars);
spanPrice.html(totalPrice.toFixed(2));
}
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(__textCalculatorCounter);
textblock.keydown(__textCalculatorCounter);
textblock.keypress(__textCalculatorCounter);
textblock.keyup(__textCalculatorCounter);
textblock.blur(__textCalculatorCounter);
textblock.focus(__textCalculatorCounter);
$('label', '#pricesGroup').click(__textCalculatorCounter);
}
==== UPDATED ====
I don't know why, but it works fine in jsfiddle... it's exactly the same code extracted from html and javascript.
JSFIDDLE
So, since no one had an answer, I post mine, which solved the issue.
The problem is in Twitter's Bootstrap 3 radio button styles which is actually common issue when using along with javascript.
I've changed a click handler for radio buttons:
function _initTextCalculator(){
var textblock = $('#calculateText');
textblock.change(_textCalculatorTrigger);
textblock.keydown(_textCalculatorTrigger);
textblock.keypress(_textCalculatorTrigger);
textblock.keyup(_textCalculatorTrigger);
textblock.blur(_textCalculatorTrigger);
textblock.focus(_textCalculatorTrigger);
// Fixing bootstrap 3 radio buttons
$("#pricesGroup label").on('click', function(){
// Once clicked, mark current radio as checked
$('input:radio', this).prop("checked", true);
// Then call a function to calculate the price
_textCalculatorTrigger();
});
}
As it already commented, it assigns a property "checked" to radio button first once it's parent label tag is clicked, and then it calls a function to calculate the price.
Thanks to everyone

Automatically change a value in a form field

I have a webpage where people enter information (name, job title, address, etc.) and it auto creates a business card for them. I currently have some jQuery that uses .change and looks at a field when a user changes it.
It looks for issues with what they enter, because some things must be in a certain format (ex- They enter the word "Avenue" and it won't let them add the item to their cart until they change it to Ave.)
I am trying to find some way to do this on the fly automatically with JS/jQuery, but I'm not sure what to do. What I would like is for the field to update itself, so if the user puts in "Avenue" it would auto update to "Ave." after the user tabs / exits the field.
Any idea on what JS and/or jQuery can be used to do this?
Here is my current code:
var x = "Clean";
var xD = " ";
$('#cartText4046').change(function () {
if ($(this).val().indexOf("Avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
} else if ($(this).val().indexOf("avenue") > -1) {
x = "Please use Ave. instead of Avenue.";
... Additional rules here, omitted for space.
} else {
x = "Clean";
}
if (x != "Clean") {
$('#cartText4046').addClass("invalid");
xD = x;
} else if (x == "Clean") {
$('#cartText4046').removeClass("invalid");
xD = " ";
}
if (x != "Clean") {
$('.betabutton').html('<span id="addToBaskettext">To add this to the Basket,
please fix the following issue(s):<br><br> ' +xD'</span>');
$('.betabutton').addClass("invalidBtn");
} else if (x == "Clean") {
$('.betabutton').html('<a id="addToBasket" href="#" onclick="actionPageSubmit();return false;"><span id="addToBaskettext">Add to Basket</span></a>');
$('.betabutton').removeClass("invalidBtn");
}
Here is a working sample of what you may be looking for.
$("#textbox").on("change", function() {
$(this).val(function(index, value) {
return value.replace('Avenue', 'Ave.');
});
});
http://jsfiddle.net/decx8sw9/
If you really wanted it to do it after the user has finished making changes ("after the user tabs / exits the field.") you might want to bind to blur (fires when focus is lost/shifted to some other element)...
$('#cartText4046').on( "blur", function() {
$(this).val(function(index, value) {
value = value.replace('Avenue', 'Ave.');
// keep going ... value = value.replace('Street', 'St.') ..
return value;
});
EDIT: I reread the question, and now see that you wanted the correction to happen after the user exits the field. This answer provides inline autocorrection while the user types. I will leave it in case you find it useful after all.
You can lift the code from the jQuery Autocorrect Plugin: jsfiddle.
$("#textbox").autocorrect({
corrections: {
Avenue: "Ave.",
"...": "someWord"
}
});

Down Slider from the list [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am a newbie on Appcelerator Titanium and practicing by developing some mobile apps and came across a situation and need some help.
I have a list of items, which displays from a table and on clicking any item, there should be a bigger space below slides down from clicked item for some entry fields. I am attaching a sample, basically from fig 1, when touched (ofcourse in mobile) it should expand like in fig 2.
Thanks.
This is a bit tricky with Titanum. As it looks it's a row-based approach. So first you should decide to use a TableView
var tableView = Ti.UI.createTableView({
width: Ti.UI.FILL,
height: Ti.UI.FILL,
});
Then you need to add the rows from the left screen. These are simple rows.
var rows = [];
for (var i = 0; i<data.length; i++) {
var row = Ti.UI.createTableViewRow(...);
// do some layout, add some views here
rows.push(row);
}
// add to table view
tableView.data = [rows];
Then you need to apply a 'click' listener.
var isOpen = false; // is already one element clicked and opened?
var whichIsOpen = undefined; // if yes, which one (index of clicked element)?
tableView.addEventListener('click', function(e){
if(isOpen && e.index === whichIsOpen) {
tableView.deleteRow(whichIsOpen+1);
isOpen = false;
return;
}
if(isOpen && e.index === whichIsOpen + 1) {
return;
}
tableView.deleteRow(whichIsOpen+1);
var specialRow = Ti.UI.createTableViewRow(...); // row which contains the elements of the right screen
var newIndex = e.index > whichIsOpen ? e.index : e.index + 1; // because removed one
tableView.insertRowAfter(newIndex-1, specialRow);
whichIsOpen = newIndex;
})
In this solution you can only open one element at the same time. I typed this from my head, i didn't test. So it's up to you!

Categories