Document.write issues - javascript

I am making a page where users can answer questions (using radio buttons) about a product they are selling back. When they hit a button at the bottom of the page, a price quote will pop up. I have written a javascript function to be performed when the user hits the button. It calculates the price and displays it using document.write, but whenever the user hits the button, it opens up a new page and displays what I told it to.
function getQuote(){
document.write("Your Quote Is: $", price, ".00");
}
And here is the code for the button:
<button type="button" onclick='getQuote()'>Display Quote</button>
But when I push the button, a new page shows up and it shows the quote with only the formatting I put into the document.write phrase.
I have tried using .innerHTML to send the document.write to another part of the page, but the same problem persists.
What can I do to make sure that the quote shows up on the page, where I want it to?

There is no issue with document.write, it is doing exactly what it is supposed to do:
Overwrite the page with the new content.
If you do not want to do that, then you have to give it some context to write to.
For example:
function getQuote(){
var textArea = document.getElementById('textArea');
textArea.innerHTML = "Your Quote Is: $", price, ".00";
}
Which puts whatever your text is into a DOM element with id="textArea"

You should reference the element, and set its content instead of using document.write.
<button type="button" onclick='getQuote.call(this)'>Display Quote</button>
function getQuote(){
this.firstChild.data = "Your Quote Is: $" + price + ".00";
}
If you want to write to a different element, you should select that element, and likely use the same technique.

After your document has been full rendered and closed, using document.write() will clear your current document and start a new one, wiping out all previous content.
The put content into the existing document you need to use DOM manipulation functions, not document.write(). If, what you're trying to do is to change the text of your button, you can do so like this (assuming price is a global variable that contains the price):
<button type="button" onclick='getQuote(this)'>Display Quote</button>
function getQuote(obj) {
obj.innerHTML = "Your Quote Is: $" + price + ".00";
}
If you want to put the price into some other object on the page, then you give that object an id and you can get that object and set the price into it like this:
<button type="button" onclick='getQuote()'>Display Quote</button>
<div id="quotedPrice"></div>
function getQuote() {       
document.getElementById("quotedPrice").innerHTML = "Your Quote Is: $" + price + ".00";   
}
You can see both forums of these work here: http://jsfiddle.net/jfriend00/ED5V9/

Related

Get value from javascript to html page without ajax

I am using Javascript and jquery. Right now i am getting one value from html to javascript. And after that again i am append this value in html page.
HTML:
<button data-uri="999999" class="priceInCombo waves-effect waves-light btn modal-trigger red darken-1">Buy Now</button>
JAVA SCRIPT:
$('.priceInCombo').click(function () {
var currntTabPrice = $(this).data('uri');
$(".qq").text(currntTabPrice);
});
After that append this value in class(qq) in same page.
<div class="qq">
</div>
But i want to plus some digit like 30. How to add 30 in class(qq) value.
If you open in console then you can see.
I want to add some value after append the java script value. But i don't know how to add value after the append javascript value.
You should be sure that you are retriving a number (integer/float)
var price = parseFloat($(".qq").html());
after that make the sum (or anything else) and replace the value
price += 30M
$(".qq").html(price);

How do I create another window on top of a page using Javascript?

I'm alittle confused about how to create a page on top of a page. Basically I want to have the page open with: Hi ________.
Then, when the user types the name in and presses enter, the name is then saved so that the page now writes "Hi [insert name here]!.
I'm not sure what is the best course of action. Should I should use a prompt, or an input text box? How would I be able to save the name provided? I'm not even sure if there is such an effect?
I know how to create a text input box, and how to make the form press enter with just the keyboard, but I don't know how to put the effect on top. How I can make a window on top of a window?
So the website prompts the user to
<p>Enter your name</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
After, the page fills in the name, the name will be inserted into the script. So the page will display the name entered. For example, "Hi Sam." in the regular
page. Would I use a version of this?
<script>
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
</script>
Let me know if this sounds too confusing. I can try to elaborate further. I've tried looking for a similar question on stackoverflow before, and I don't see one just like this yet.
Since you have not mentioned any framework like angular or jquery in your post I guess you are fairly new to creating "dynamic" web pages with JavaScript. You can do these things with "pure JavaScript" but in general you will need to write more code. Your actual example, however, can be made to work with relatively little changes and not too much effort, like this:
function myFunction() {
var x = document.getElementById("myText").value;
document.getElementById("demo").innerHTML = x;
}
<input type="text" id="myText" placeholder="Please enter your name">
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>
In this example no extra window was applied. If you want a modal dialog you could use the JavaScript window-method prompt()
var name = prompt("Please enter your name here", "suggested name");
instead of the above input field:
function myFunction() {
var x = prompt("Please enter your name here", "suggested name");
document.getElementById("demo").innerHTML = x;
}
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>
You want to open a new window? Try this:
var theName = prompt("What is your name?");
var w = window.open("", "", "width=500, height=300");
w.document.body.innerHTML = "Hello "+theName+"!";
Then, when the user types the name in and presses enter, the name is
then saved so that the page now writes "Hi [insert name here]!.
If you just want to save the data for the current session then you can save the data into a Javascript variable.
I'm not sure what is the best course of action. Should I should use a
prompt, or an input text box? How would I be able to save the name
provided? I'm not even sure if there is such an effect?
Any of them would work, any field that can take a value.
I know how to create a text input box, and how to make the form press
enter with just the keyboard, but I don't know how to put the effect
on top. How I can make a window on top of a window?
The term a window on top of a window isn't really accurate terminology. But I think I see what you mean. You can just use hide and show to hide the text field and then insert the name into a span.
I've made a fiddle so you can see what I mean
https://jsfiddle.net/xo5vt07s/6/
$(document).ready(function () {
$("#name").keypress(
function (event) {
if (event.which == 13) {
var usersName = document.getElementById("name");
var displayBox = document.getElementById("displayName");
usersName.style.display = "none";
displayBox.innerHTML = usersName.value + "!";
displayBox.style.display = "inline";
alert("Test")
}
}
);
});

Pass Selected Radio Value to PHP using onclick, then opening php file to use value in SQL query

I am pretty new to coding php and javascript but have manged to scrape my way through so far. However, I have hit a wall. I'm not 100% sure that what I'm trying to do can be done, or that I'm even attempting it in an effective way.
I have a dynamically filled table, made of rows from a SQL statement using php. On each row is a radio button, each one given a unique value based on the row number (a unique value in one of the database columns). I am attempting to program a button that enables the user to pass a selected radio button value to a separate php enabled page that will allow the user to edit the row information using the unique row value. Also, i used the confirm option, because I would also like to add an if else statement that allows the user to cancel, if the wrong row was selected (I haven't attempted that yet because I haven't been able to get the value to pass).
Page button
<input type="button" id="edit_order_button" value="Edit Order"></input>
JQuery page
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
var r = confirm("Confirm Order Number to edit: " + selected);
$.post("php/editOrder.php", {
selected1: selected
}, function(data,status) {
//alert("Data: " + data + "\nStatus: " + status);
window.open("php/editOrder.php","Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
});
});
});
PHP end destination
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
require('config.php');
$selected2= isset($_POST['selected1']) ? $_POST['selected1'] : ''; // Fetching Values from URL
echo "Selected Row number is ".$selected2.".";
mysqli_close($connection); // Connection Closed.
?>
I have tried a few things but have so far been unsuccessful in getting the new window to load with the value of the radio button passed. Currently, the window loads, but the new window only displays the echo text, no variable. When I run with the alert popup, the data shows me the value of the selected row but it does not seem to be posting to the new page prior to the window.open command. Any tips would be appreciated, or if i'm approaching the problem from a wrong angle, any insights would also be great. I have also tried debugging, thinking I was missing a parentheses or semicolon but I wasn't able to find anything. Thanks
Looks to me like you can get rid of the post statement altogether and just pass the selection to the newly opened window.
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
// only open window if order okayed
if ( confirm("Confirm Order Number to edit: " + selected) ) {
window.open("php/editOrder.php?selected1=" + selected,"Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
}
});
});
php/editOrder.php:
$selected2 = $_GET['selected1'];
echo "Selected Row number is $selected2.";

Creating Ask Function in Javascript

I'm pretty new to Javascript, so I figured I'd start on a Text Based Game to start out. What I need to do, is to be able to detect when the game is waiting for a command, and when the game is waiting for an answer. Here's what I've got.
var textIn = document.getElementById('input-textbox');
var textOut = document.getElementById("output-textbox");
function process(input) {
var command = input.split(" ")[0];
if(command == "help") {
return "Help dialog";
}else{
return "Unknown command: " + input + ". Please type /help for a list of commands.";
}
}
function go() {
var input = textIn.value;
textIn.value = "";
output(process(input));
}
function output(text){
textOut.value += text + "\n";
}
function createPlayer(){
output("Please Type Your Name")
// Wait for player response and set it as a variable.
}
createPlayer();
What would be the best way to implement this?
You have a few options, you could use onclick and have a button that the user clicks and then call your functionality to fill in the answer for your HTML answer (id="output-textbox" in your example)<-- My vote *.
... or you could choose to check on which element is focused or if tab/enter is hit while in the input box and then put your answer field after the tab/enter is hit. I think the latter method, you should have a HTML5 placeholder attribute to say "hit tab{enter} when finished" or something along those lines and then check for the tab while focused on the element -- this could be accomplished with jQuery selectors or override the current focus method for that input element or potentially use document.activeElement to see what is focused on and then if it is the answer that is focused on and the input isn't blank fill it in, etc, etc, etc.
*If you are new to Javascript, I say have two buttons (one labeled 'answer' and one labeled 'clear'), and then use the onclick attribute for HTML button elements to call a Javascript method easily. This will get you started and be more straightforward, double check what you have works for DOM manipulation and move forward to having less buttons and more sleek DOM manipulation.
Good luck!
A very simple implementation is to use a form with a submit listener that cancels submission if all goes to plan. A user can enter text into the input and see the result in the textarea.
The textarea is disabled so users can't enter text into it but script can. Users can enter input then just press enter, or tab to the submit button and press enter, or click the submit button. The script runs on submit, and cancels it so they stay on the same page.
If scripting is disabled, the form will submit and you can handle things at the server.
<form onsubmit="go(); return false;">
<input id="input-textbox">
<textarea id="output-textbox" rows="20" cols="50" disabled></textarea>
<input type="submit" value="Ask question">
</form>

jQuery table and storing values issue

So I'm working on a JS project for school where I have a form in which the user enters the amount of forces in a problem, once entered a loop will created new fields per force. I have that part down, but I am having an issue with storing the text input from each of these new fields. I am using the .on function where the user has to click a button and then based on the id of the button clicked a number for the force array is created. The input is then suppose to be read into the array, but its just not working and its driving me nuts. Any ideas? Thanks in advance.
function forceRecording(numofforces){
for(var i =0; i<numofforces; i++){
$('#button1').after("<tr><td>Force DFO " + i +":</td><td><form><input type='text' name='lengthMeasure_'/></form></td><td><div class='button' id='lengthButton_"+i+"'>Add!</div></td></tr>")
$('#button2').after("<tr><td>Force " + i +":</td><td><form><input type='text' name='forceMeasure_'/></form></td><td><div class='button' id='forceButton_"+i+"'>Add!</div></td></tr>")
}
};
$("button[id^='forceButton']").on("click",function(){
var num = parseInt($(this).attr("id").split("_")[1]);
forces[num] = $('input[id=forceMeasure_'+num+']').val();
$('#button1').after('<td>'+forces[num]+'</td>');
});
As you can see I'm adding another column in my table temporarily just to check if the force is actually point into the array but when I run this, nothing new pops up.
I am pretty sure you would have solved this issue by now. But I just happened to come across this post and thought that an answer could help future readers.
There were three issues in your code which prevented it from working and they are as follows:
$("button[id^='forceButton']") is used instead of $(".button[id^='forceButton']"). Note the . before button. Without the . jQuery would look for a button tag with id like forceButton whereas the tag in question was a div with class as button.
$('input[id=forceMeasure_'+num+']').val(); is used to get the text box value but your input field doesn't have any id. It only has a name, so instead use $('input[name=forceMeasure_' + num + ']').val();.
The input field is set as <input type='text' name='forceMeasure_'/>. Note that the count part after the forceMeasure_ is missing. It should have been <input type='text' name='forceMeasure_" + i + "'/>.
Making all the three changes as mentioned above, the code works fine.
Click here for a sample demo of the working code.

Categories