Updated HTML from JavaScript variable - javascript

im trying to build a form with a few number type inputs that the users picks and one checkbox.
im not using php its all java cause im trying to count a bill using his inputs and print out the result.
how do i print those variables? document.write wont do cause its immidetly prints the var without the calculation.
here is some of the script (which is nothing):
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
var shutter_price
shutter_price = ($('#shutter').val())*200;
if (shutter != '0' )
write(shutter_price);
});
and the form's input:
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter">
any suggestions?

Instead of document.write it would be better to update or add an element on the page.
For example, modifying your provided code and markup:
Javascript (jQuery)
$(document).ready(function(e) {
$('.content_window').css('height','900');
$('#top').css('float','none');
$('#shutter').on("change", function(e) {
var shutter_price = $(this).val()*200;
if (shutter_price >= 0) {
$('#shutter-result').text(shutter_price);
}
});
});
HTML
<label for="shutter">shutter </label>
<input style="margin-right:98px" name="shutter" type="number" id="shutter" min="0" step="1" pattern="\d+" />
<div id="shutter-result"></div>
JSFiddle

I think you can create a div on your HTML,
and use: $('#id_of_div_where_you_want_to_write').html("text you want to write");
p.s. This is javascript
javascript != java o/
Hope it helps bro!

i've typed the whole calculation.
i have a submmision button which by clicking needs to retrive the sum.
it doesnt work... im pretty new at javascript so i cant really tell where is the problem.
here is the code:
$('#home_price').submit(function(){
var shutter_price, lights_price, socket_price, screen10_price, screen7_price, dimmer_price, x
var total_price = 3000;
shutter_price = ($('#shutter').val())*200;
light_price = ($('#lights').val())*200;
socket_price = ($('#socket').val())*200;
screen10_price = ($('#screen10').val())*700;
screen7_price = ($('#screen7').val())*200;
dimmer_price = ($('#dimmer').val())*400;
if($('#boiler').is(":checked")==true){
total_price+=600;
x+=1;
}
x+=($('#shutter').val())*2+($('#lights').val())+($('#socket').val());
Math.floor(x);
x+=1;
total_price = total_price + shutter_price + light_price + socket_price + screen10_price + screen7_price + dimmer_price + x*400;
$('#home_pricing').val()=total_price;
if($('#home_pricing').val() < 6000)
alert('the solution invalid');
else
alert(" total: " + $('#home_pricing').val());
});
});
and a piece of the html code:
<label for="screen7"> 7inch screen </label>
<input style="margin-right:70px" name="screen7" type="number" id="screen7"> <br><br>
<label for="dimmer"> dimmer</label>
<input style="margin-right:174px" name="dimmer" type="number" id="dimmer"> <br><br>
<label for="boiler"> bolier </label>
<input style="margin-right:148px" type="checkbox" name="boiler" id="boiler" > <br><br>
<div>
<input type="submit" name=" home_pricing " id="home_pricing" value=" calculate " >
</div>
</form>
any suggestion of how to make the computation and retrive an alert window or other sort of window with the answer?
tnx

I know you did not say that you are using jquery, but I would highly recommenced it, because it makes javascript a lot easier. If you need to display this value to the user then you can use jquery's html function. Here is the link, https://api.jquery.com/html/. I would just write the value to a div that's is suppose to display the answer.
Let me know if you need it, and I can give you a quick plunker.

Related

parseInt returns NaN when it should be a number?

I have the following code:
$(function() {
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button");
$radioOptions.on("change",function(){
$formButton.removeAttr("disabled");
var chosenField = $(this).data("field"),
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
console.log("1 =" + answer_1);
console.log("2 =" + answer_2);
console.log("3 =" + answer_3);
//Additional code not related to question
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="web-app-item-data" data-item-name="Test" data-answer-1="0" data-answer-2="0" data-answer-3="0"></div>
<form id="pollAnswers">
<div class="answers">
<input type="radio" name="radioChoice" data-field="CAT_Custom_2"> Answer 1<br>
<input type="radio" name="radioChoice" data-field="CAT_Custom_4"> Answer 2<br>
<input type="radio" name="radioChoice" data-field="CAT_Custom_6"> Answer 3<br>
</div>
<button type="submit" disabled>Submit</button>
</form>
When you run the code you will see in your console that Answers 1, 2 and 3 all return NaN.
Update:
As Charlie H pointed out in a comment, if I remove parseInt it returns undefined.
I don't see the error in the code for why it isn't pulling the data attribute values from the div.
How do I solve this issue?
jQuery 2.1.3 does not appear to recognize data- attributes that contain a name-segment that consists only of numbers. For instance, these work:
data-answer as .data()["answer"]
data-foo as .data()["foo"]
data-foo-bar as .data()["fooBar"]
These do not:
data-answer-1
data-foo-bar-3
jQuery 3 appear to behave more as expected.
The data function from jquery does not seem to be taking attributes into account which have a number in the attribute name. "number-1" is not working but "number-one" does. This might help you as a quick fix.
$(function() {
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button");
$radioOptions.on("change",function(){
$formButton.removeAttr("disabled");
var chosenField = $(this).data("field"),
answer_1 = parseInt($existingDataWrapper.data("answer-one")),
answer_2 = parseInt($existingDataWrapper.data("answer-two")),
answer_3 = parseInt($existingDataWrapper.data("answer-three"));
console.log("1 =" + answer_1);
console.log("2 =" + answer_2);
console.log("3 =" + answer_3);
//Additional code not related to question
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="web-app-item-data" data-item-name="Test" data-answer-one="0" data-answer-two="0" data-answer-three="0"></div>
<form id="pollAnswers">
<div class="answers">
<input type="radio" name="radioChoice" data-field="CAT_Custom_2"> Answer 1<br>
<input type="radio" name="radioChoice" data-field="CAT_Custom_4"> Answer 2<br>
<input type="radio" name="radioChoice" data-field="CAT_Custom_6"> Answer 3<br>
</div>
<button type="submit" disabled>Submit</button>
</form>
Before jQuery 3.0.0, jQuery attempts to retrieve the rest of the data- attribute as camelCase. In other words:
data-answer-1 becomes camelized to data-answer1 and attempts to retrieve said attribute (because it fails to normalize it back to data-answer-1), which of course there isn't so it returns undefined. Any data- attributes that hold more than one dash and aren't camelized properly won't be obtainable through the jQuery data methods as they become camelized before actually being retrieved. This includes data- attributes that don't start with a letter after the second dash.
Basically, jQuery does:
var key = jQuery.camelCase(key);
//... some time later
var attrName = "data-" + key.replace(/[A-Z]/g, "-$1" ).toLowerCase();
// back to normal or is it...?
elem.getAttribute(attrName); //might not exist.
This is already fixed on version 3.0.0 as per this issue. Here's the commit that fixed it.
Jquery allows only one "-" in data attributes in versions higher than 1. Your code works very well for all JQuery 1.x versions.
You can read an attribute using the attr() function. However, as others have suggested, jQuery doesn't read attribute names with numbers in them.
See the code for solution.
$(function() {
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button");
$radioOptions.on("change",function(){
$formButton.removeAttr("disabled");
var chosenField = $(this).data("field"),
answer_1 = parseInt($existingDataWrapper.attr("data-answer-1")),
answer_2 = parseInt($existingDataWrapper.attr("data-answer-2")),
answer_3 = parseInt($existingDataWrapper.attr("data-answer-3"));
console.log("1 =" + answer_1);
console.log("2 =" + answer_2);
console.log("3 =" + answer_3);
//Additional code not related to question
});
});

Can't get if/else function to work with radio buttons

I have looked all over this site (and Google) for an answer to my problem but I can only seem to find bits and pieces, nothing specific.
I am primarily playing around with JavaScript and HTML but am not trying to use jquery right now.
So, with that said, this is what I'm trying to do: I would like the user to enter two numbers, select an operation (add, subtract, multiply, divide) out of a list of four radio buttons, and then click a button which is linked to a function that does the math and then presents it in a text box on the page. How would I do this using only HTML and JavaScript? I have gotten everything to work up until the point I add the radio buttons.
The code is as follows:
<script>
function operationForm (form) {
var x = document.operationForm.getElementById("numberOne");
var y = document.operationForm.getElementById("numberTwo");
var operation;
var answer;
if (document.operationForm.addSelect.checked === true) {
answer = x + y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.subtractSelect.checked === true) {
answer = x - y;
document.operationForm.answerBox.value = answer;
} else if (document.operationForm.multiplySelect.checked === true) {
answer = x * y;
document.operationForm.answerBox.value = answer;
} else(document.operationForm.divideSelect.checked === true) {
answer = x / y;
document.operationForm.answerBox.value = answer;
}
}
</script>
<h1>Let's calculate!</h1>
<form name="operationForm">
<p>
<label>Enter two numbers, select an operation, and then click the button below.
<p>
<label>Number One:
<input type="text" name='numbers' id="numberOne">
<br>
<br>Number Two:
<input type="text" name='numbers' id="numberTwo">
<p>
<input type="radio" name="operations" id="addSelect" value=''>Add
<input type="radio" name="operations" id="subtractSelect" value=''>Subtract
<input type="radio" name="operations" id="multiplySelect" value=''>Multiply
<input type="radio" name="operations" id="divideSelect" value=''>Divide
<label>
<p>
<input type="button" value=" Calculate " onClick='operationForm(form);'>
<p>
<label>Your answer is:
<input type="text" name="answerBox">
If anyone has any fixes or can point me in the right direction of the correct syntax for handling radio buttons, functions linking to them, and onClick events linking to those functions, it would be extremely appreciated.
Consider replacing the <input type="button" value=" Calculate " onClick='operationForm(form);'> with <input type="button" value=" Calculate " onClick='operationForm();'>. Next change the function operationForm to accept no parameters. Then add id to your input answer box. Next for each if statement in the function use the elementById function to get the radios and the answerBox. For example, the first if should be
if (document.getElementById("addSelect").checked) {
answer = x + y;
document.getElementById("answerBox").value = answer;
}
This works:
JavaScript:
<script type="text/javascript">
function operationForm(){
var form = document.forms['operation_form'];
var x = form['numberOne'].value*1;
var y = form['numberTwo'].value*1;
var operation = null;
var answer = null;
if (form['addSelect'].checked == true) {
answer = x + y;
} else if (form['subtractSelect'].checked == true) {
answer = x - y;
} else if (form['multiplySelect'].checked == true) {
answer = x * y;
} else if (form['divideSelect'].checked == true) {
answer = x / y;
}
form['answerBox'].value = answer;
}
</script>
HTML:
<form name="operation_form">
<label>Enter two numbers, select an operation, and then click the button below.</label>
<br/>
<label>Number One:</label><input type="number" name='numberOne' />
<br/>
<br/>Number Two:</label><input type="number" name='numberTwo' />
<br/>
<input type="radio" name="operations" id="addSelect" value='' />Add
<input type="radio" name="operations" id="subtractSelect" value='' />Subtract
<input type="radio" name="operations" id="multiplySelect" value='' />Multiply
<input type="radio" name="operations" id="divideSelect" value='' />Divide
<br/>
<input type="button" value=" Calculate " onclick="operationForm();" />
<br/>
<label>Your answer is:</label><input type="text" name="answerBox">
</form>
Fixes between this and your example:
There are a ton of things wrong with the code you provided. I will update this answer shortly with as many as I can remember.
Update:
Please remember this is meant to be helpful and not punishing. So keep in mind that while listening to the attached feedback, I want you to learn this stuff.
Notes on your HTML:
1.) The biggest problem is none of the <label> elements have closing</label> tags.
Although, none of your html elements have any closing tags.
This will group all of the elements inside one big parent <label>.
So when the browser auto-closes the unclosed tags at the end of the document, this causes a hodgepodge of mixed up child elements. Close your elements.
2.) The first two text boxes have the same name="numbers" attribute. You can only do that with radio type inputs.
3.) Your <form> name="" attribute can NOT have the same name as the JavaScript function you are trying to call. They are stored in the same browser namespace so it causes an error.
Notes on your JavaScript:
1.) Your checked === true is an exact comparison. This will almost never evaluate to be truthful. Use checked == true, or better yet, just use if( my_element.checked ){}. Sometimes .checked will equal a string like this: .checked = 'checked'. So even though 'checked'==true it will never be truthful for 'checked'===true. The === means Exactly Equal. So only true===true.
2.) Your var x = document.opera.. ... .mberOne"); will store the whole <input> element into the x variable. You need to have ...mberOne").value; so just the value of the <input> is stored, not the whole html element.
3.) The only object that has a getElementById() method is the document. You can't use that from a document form object.
4.) You have to convert your x any y input values to numbers. If not, 5 + 5 will give you 55 instead of 10 because they are treated as strings. I multiplied them by * 1 to do that. I also changed the <input type='text' attribute to type='number' just to be safe.
5.) You can assign your answerBox.value just one time at the end of the function instead of doing it once per if(){} bracket. It will work the same but it's just much more readable.
6.) I used the syntax of form['numberOne'] instead of form.numberOne but they both work the same. It is referencing the element name (not necessarily the id) as it exists inside the form. <form> is the only object that lets you do this, whereas a <div> or <p> does not.

second javascript not working on my contact form

Ok, all, I have a few questions.
How can I have my total have a $ and how can I move up next to the word Total: ( so it will be side by side)
Once I get a total price, is there a way where I can divide it by 2 to get 1/2 of the price into another field called 'deposit' before copying that to add to another field called 'balance':
I cannot get the date fields to copy
To note this is where I found how to add up the radio buttons ( Here)
This is what I have so far.
This is my form:
Session Date: <input type="text" name="field1" id="f1" />
Session Type payment :
<input type="radio" name="sessiontypepayment" id="sessiontypepayment1" value="100.00" onclick="FnCalculate(this,'extrapeople');"> Mini Session $100.00
<input type="radio" name="sessiontypepayment" id="sessiontypepayment2" value="250.00" onclick="FnCalculate(this,'extrapeople');"> Full Session $250.00
Extra people :
<input type="radio" name="extrapeople" id="extrapeople1" value="25.00" onclick="FnCalculate(this,'sessiontypepayment');"> 1 person $25.00
<input type="radio" name="extrapeople" id="extrapeople2" value="50.00" onclick="FnCalculate(this,'sessiontypepayment');"> 2 people $50.00
<input type="radio" name="extrapeople" id="extrapeople3" value="75.00" onclick="FnCalculate(this,'sessiontypepayment');"> 3 people $75.00
<input type="radio" name="extrapeople" id="extrapeople4" value="100.00" onclick="FnCalculate(this,'sessiontypepayment');"> 4 people $100.00
Total Amount: <div id="total"></div>
Deposit Amount:
Balance Amount:
balance due BY: <input type="text" name="field2" id="f2" />
This is my script what I have so far.
<script type="text/javascript">
$(document).ready(function(){
$("#f1").keyup(function(){
var f2Text = $('#f2').val() + $(this).val();
$('#f2').val(f2Text );
});
});
</script>
<script>
function FnCalculate(id,name)
{
var total=0;
if(document.getElementById(name+"1").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
if(document.getElementById(name+"2").checked == true)
{
total = parseInt(document.getElementById(name+"1").value);
}
total = total + parseInt(id.value);
document.getElementById("total").innerHTML = total;
}
</script>
I would really love help on this please.
First, get rid of all the onclick="FnCalculate(this,'xx');" bits on your inputs.
Then replace your <script>s with this:
<script type="text/javascript">
$(document).ready(function() {
$("#f1").keyup(function() {
$('#f2').val($(this).val());
});
var inputs = $('input[name="sessiontypepayment"], input[name="extrapeople"]');
$(inputs).click(function() {
var total = 0;
$(inputs).filter(':checked').each(function() {
total = total + parseInt($(this).val());
})
$('#total').html('$' + total);
$('#deposit').html('$' + (total / 2));
});
});
</script>
Unsure what you mean by "how can I move up next to the word Total" but I suspect changing <div id="total"></div> to <span id="total"></span> will solve your problem. Either that, or apply some css to the div:
#total {
display: inline;
}
I added the calculation for the deposit, you'll need to add <div id="deposit"></div> to your page somewhere...
You will need jquery. Add this in between <head>...</head>:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
First, you should have your defaults set to checked='checked' for HTML radio buttons that you want checked initially. I would put default text into <div id='total'>$125.00</div>, as well. You might as well use jQuery for what it's made for and not put Events into your HTML at all. .val() returns a String. To cast a String to an integer put + in front of it. To cast to a floating point Number use parseFloat().
$(function(){
$('#f1,[name=sessiontypepayment],[name=extrapeople]').change(function(){
$('#total').text('$'+(parseFloat($('[name=sessiontypepayment]:checked').val())+parseFloat($('[name=extrapeople]:checked').val())).toFixed(2));
$('#f2').val($('#f1').val());
});
});
To divide by 2 it's /2
As a newbie you should get into the practice of using external <script src so it will get cached into your Browser Memory, for faster load time when your Client revisits your site.

How to copy and output text from another textbox with Javascript?

<input type="hidden" id="prevTicketNo" value="6"/>
<script>
var ticketNo = document.getElementById(prevTicketNo).value +1;
document.getElementById('currentTicketNo').value = ticketNo;
</script>
<input id="currentTicketNo" value=""/>
What I am trying to do:
The prevTicketNo is a value captured from somewhere else. I need that to load as a hidden field so I used type="hidden". Once the value in this textbox is loaded, I need to +1 so that the number increases for my current ticket.
Is the right approach?
You must change the value of the first input to integer.
var ticketNo =parseInt((document.getElementById('prevTicketNo').value),10)+1;
document.getElementById('currentTicketNo').value = ticketNo;
JSBin
Javascript:
var hiddenVal = document.getElementById("prevTicketNo");
var newTicketNo = Number(hiddenVal.value) + 1;
alert(newTicketNo);
HTML:
<input type="hidden" id="prevTicketNo" value="6"/>
If you can get the previous ticket number and output it into a hidden field (obviously via some kind of server side script), why can't you just output it directly into your text input?
eg. In PHP write this:
<input id="currentTicketNo" value="<?php echo $prevTicketNo + 1; ?>" />

Using document.writeln with input form in Javascript

I'm trying to input a form with Javascript. On the form, if the dropdown selection is a certain selection then specific form fields will appear below.
Here is the code I currently have, but it doesn't seem to work, I am guessing document.writeln is not the proper method. If I add an alert to see if it is pulling the selection it works, so something with adding the form in is failing. After the document.writeln the alert doesn't even come up anymore?
<script language="javascript">
var HelpTopic = document.getElementById('type');
HelpTopic.onchange=function() {
if(HelpTopic.value == "Analytics") {
alert("Congrats");
document.writeln('\<li\>
\<label for\=\"confirm\"\>Input name*\<\/label\>
\<input type\=\"text\" name\=\"inputs\" id\=\"names\" required \/\>
\<\/li\>');
} else {
alert("Fails");
}
}
</script>
You can't span a string over multiple lines in JS. You need something like this:
document.writeln('\<li\>' +
'\<label for\=\"confirm\"\>Input name*\<\/label\>' +
'\<input type\=\"text\" name\=\"inputs\" id\=\"names\" required \/\>' +
'\<\/li\>');
EDIT: You don't need so much escaping. This will work just as well:
document.writeln(
'<li>' +
'<label for="confirm">Input name*</label> ' +
'<input type="text" name="inputs" id="names" required />' +
'</li>');
To properly add list item to some list have such code instead:
var oList = document.getElementById("MyList");
var oItem = document.createElement("li");
oItem.innerHTML = "<label for='confirm'>Input name*</label><input type='text' name='inputs' required />";
oList.appendChild(oItem);
This will add item to list with ID MyList.
just a quick note, multi line strings are supported in javascript like this
'<li>\
<label for="confirm">Input name*</label>\
<input type="text" name="inputs" id="names" required />\
</li>'
I agree with Shadow Wizard, that would be the best way to append a list
The way you're trying to dynamically modify the "onChange" (missing capital C) seems to have trouble with Chrome
Also, you cant split a string over multiple lines the way you did
The following code should work, notice I added "onChange=myfunc();" to the select:
<select id=type onChange=myfunc();>";
<option value=Other>Other</option>
<option value=Analytics>Analytics</option>
</select>
<script language="javascript">
function myfunc()
{
var HelpTopic = document.getElementById('type');
if(HelpTopic.value == "Analytics") {
alert("Congrats");
document.write('<li><label for="confirm">Input name*</label><input type="text" name="inputs" id="names" required></li>');
} else {
alert("Fails");
}
}
</script>

Categories

Resources