Update total price? - javascript

I want a price to update when I click a button, that's all I want it to do, but everytime I try to call the value of my var, it returns "NotANumber/NaN" value, I've looked around for a little while but google get's a little bit confused and throws be tutorials about finding defined numbers, etc.
I am new to JavaScript, however. So it is probably me.
If anybody could help me out I'd be really grateful.
total price:
<span id="totalpriceex">0</span>
JavaScript:
<script type="text/javascript">
function incrementquan'.$row["pid"].'(){
var input = document.getElementById("quan'.$row["pid"].'");
input.value = parseInt(input.value) + 1;
var element = document.getElementById("price'.$row['pid'].'");
element.innerHTML = (" £" + (input.value * '.$row['pprice'].').toFixed(2));
var totalis = document.getElementById("totalprice");
totalis.value = parseInt(totalis.value);
totalis.innerHTML = (totalis.value + '.$row["pprice"].');
var totalpriceex = parseInt(totalpriceex.value);
totalpriceex.innerHTML = (totalis.value + '.$row["pprice"].'.toFixed(2))
var price=document.getElementById("totalpriceex");
price.value=price.value + '.$row["pprice"].'.toFixed(2);
}
I'm stuck! if you need anything else please leave a comment! Need this fixed as soon as I can, I'll keep trying in the mean time.

you can call value method on form elements only...other elements you need to get value using textContent method
for form elements
$("input").val();
for other elements
$("span").text()

Related

Adding clickable buttons or links for side bar

I'm having trouble adding links or buttons to my side bar dynamically. I'm trying to use JavaScript to add the appropriate amount of elements or buttons(I don't know what is better). In essence this is used to make a JS quiz website where each of the buttons in the sidebar will jump you to the question(to make it more clear: Question 4 takes you to 4th question and so on)
This is my side bar:
<div id="mySidenav" class="sidenav">
×
Question
</div>
My JS trying to make the elements but failing to do so:
//add question numbers to the side bar
function questionNav(){
for(var i = 0; i < numberOfQuestions; i++){
document.getElementById("mySidenav").innerHTML = "Question " + (i+1) + "<br/>";
//var newSideBarElm = "Question " + (i+1) + "<br/>";
//document.getElementById("mySidenav").insertAdjacentHTML = ('beforeend',newSideBarElm);
}
}
I've been trying numerous different methods but I can't get it to work and would greatly appreciate if someone was able to help me.
Here is the full code of the site in case you would like to see how I'm doing everything else: https://pastebin.com/hrSADLQy
So assuming that I understand your question correctly, what you are currently doing is targeting the div with the id 'mySideNav' and overwriting its content by assigning a new value to its innerHTML attribute. What you should be doing instead is
Create a new anchor element
Use the innerHTML attribute to insert your desired value (i.e "Question N")
Append your newly created element to your 'mySideNav' div element.
I wrote a small demo for you to see my answer in action, but will post my code below this answer for you to see as well.
// Grab and Store Element to append questions to
var mySideNav = document.getElementById('mySidenav');
// Designate number of questions
var numberOfQuestions = 10;
// Loop as many times as there are questions
for (let i = 0; i < numberOfQuestions; i++) {
// Step 1: Create a new anchor element
let newQuestion = document.createElement('a');
// Assign href to whatever you want
newQuestion.href = '#';
// Step 2: Use the innerHTML attribute to insert your desired value
newQuestion.innerHTML = 'Question ' + i + '<br>';
// Step 3: Append your newly created element to your 'mySideNav' div element.
mySideNav.appendChild(newQuestion);
}
I hope this helps!
According to your question and the code you provided i think you need to define a div with an onclick() property to make the corresponding question visible. That could be something like this (assuming you can access the number of questions inside this function):
function questionNav(){
for(var i = 0; i < numberOfQuestions; i++){
document.getElementById("mySidenav").innerHTML += "<div style='cursor:pointer' onclick=navigateToQuestion(" + (i+1) + ")/> Question " + (i+1) + "</div>";
}
}
And then define a the onclick function "navigateToQuestion" to show the question that is passed as parameter, maybe could be somethink like this:
function navigateToQuestion(question){
document.getElementById("question_" + currentQuestionInView).style.display = "none";
currentQuestionInView = question;
document.getElementById("question_" + question).style.display = "block";
}
Haven't tested the code but i think it should work.
Hope you get your problem solved :)

For every textarea i create, i want it to have its 'personal word count' on it.

The code below is to appear additional 2 textbox and 1 textarea everytime i click a button.
var x=1;
var count=0;
$('body').on('click','#add',function()
{
if(count < 6)
{
$('#div').append("<div class='line'><input type='text' name = 'txta"+x+ "' id='txta"+ x +"'><span class =wordtab></span> <textarea rows='9' onkeyup='countChar2(this)' cols='50' name = 'txtc"+x+ "' id='txtc"+ x +"'></textarea> <span class =wordtab></span><input style = 'width:50px' type='text' name = 'txtb"+x+"' id='txtb"+ x +"'><span class =wordtab></span><button class='delete' value ='Delete Row'>Delete Row</button></div><div style='margin-left: 750px' id='charNum" + x + "'></div>");
count++;
x++;
}
else
alert("Maximum 6 Skills");
});
$('body').on('click','.delete',function()
{
$(this).closest('.line').remove();
count--;
});
The below function is the code that i currently have (which i know its wrong) to put in a counter for every textarea that i added in.
function countChar2(val)
{
var len = val.value.length;
if (len >= 200)
{
val.value = val.value.substring(0, 500);
}
else
{
var id = "charNum" + x;
$(id).text((200 - len)+" words left");
}
};
So my goal is that everytime i click on the add row and start typing on the textarea, it will show the word count for that particular texarea just right below the textarea box.
To get a unique counter added to each textarea, you could append another div to the textarea with a specific class e.g.
Set the HTML structure to something such as:
<textarea></textarea><div class='text-count-area'>Word Count: 0</div>
Add the following JS at the point where each textarea is added e.g. just before 'count++' in your original code (note: this is not the most efficient way of doing this, but this will work easily with your current code):
// Bind the text area to the keyup event
$("textarea").on('keyup', function(val) {
// Simple word count
var words = this.value.match(/\S+/g).length;
// Write the word count to the immediate text-count-area div afterwards
$(this).next(".text-count-area").text("Text count" + words);
});
The word count is kept simple here for readability, but the logic from other answers (highlighted in the comments) could be implemented at this stage.
A JS Fiddle demo of this working is here.
Let see your example:
You add each div by .append method, it's correct
You count input symbols by onkeyup event, it's correct too
All you need is update your countChar2 function because this function has wrong body in that lines:
var id = "charNum" + x;
$(id).text((200 - len)+" words left");
First of all: try to debug your code via developer tools in your favorite browser with breaks in that lines. This step can give your much more and quickly info than posting question in stackoverflow :)
For onkeyup event you should use link to this object instead of id inside your function:
$(val).parent().find('.words-left').val((200 - len));
This line uses val as a link to textarea object in just appended line. .parent() gives you access to wrapper and find() finds input for words left field. (I've added '.words-left' class to your input, see my fiddler bellow). And this code works in stage of your just added line.
Your code of $('body').click() should be executed, when document is fully loaded and DOM ready. But all your ids that you will create in future doesn't appends that DOM. That's why your delete function works properly - that function uses class selector instead of id.
Proposed by me code doesn't uses id selector because it is not needed. All that needs to me - link to current object in new line, val - what I need for that operation.
BTW: When you implement function that works with objects, such as onkeyup='countChar2(this)', better way to use object as passed variable - var countChar = function(obj) {. Because val is using for scalar values in common way.
You can check my code here https://jsfiddle.net/jo0cd3yr/1/

Add HTML Value To JavaScript Variable

Ok.. So i have a html element that displays a current value, value is changed via range slider, i change the value of the html element using javascript with the following code:
hex_out = document.querySelector('#hex');
hex_out.value=rangeValue;
Which the above works fine, but recently I've needed to be able to add a bit of html code into hex_out.value
for example if i try
hex_out.value="<font color='red'>"+rangeValue+"</font>"
it will change hex_out.value to the code shown below
<font color='red'>Range slider value</font>"
which is obviously not what i'm trying to accomplish. How would i add html code to hex_out.value and have it display correctly?
Before anyone trys to say "This is a duplicate question", realize i've tried nearly ALL solutions shown on stack overflow with no luck
You'll need to modify the color via the element's style property. Try the following:
hex_out.style.color = 'red';
If you need to add any HTML, then (assuming that the hex_out element is a container element, and not an <input> tag), you can assign the HTML to its innerHTML property like so:
hex_out.innerHTML = '<strong>This is a <em>formatted</em> value.</strong>';
Another edit: It looks like you're using an <output> element, which doesn't accept child elements as far as I know. In this case, you'll likely want to use a regular <div> or <span> tag instead of <output> and then update its value manually as your sliders move using the innerHTML property described above.
I think you are looking for something like this:
var hex_out = document.querySelector('#hex'),
rangeValue = document.querySelector('#val');
rangeValue .addEventListener('input', function () {
hex_out.innerHTML = "<font color='red'>"+rangeValue .value+"</font>";
}, false);
<input type=range id=val>
<span id=hex>50</span>
Your difficulty arose because you put an obsolete font tag in the output tag which only accepts "phrasing content". The font tag is not supported in HTML5 and not on the list of phrasing content elements.
As #Mark said, a simple div will do if you require HTML to be rendered.
The example you gave is the thing normally expecting from javascript. I consider you want to change html of an existing element not value. If it is you can use below code:
hex_out. innerHTML ="<font color='red'>"+rangeValue+"</font>"
Existing fiddle link JSFiddle
Tested and works:
function setColor() { debugger;
Rval = parseFloat((r_out.value / 255.00).toFixed(3));
Gval = parseFloat((g_out.value / 255.00).toFixed(3));
Bval = parseFloat((b_out.value / 255.00).toFixed(3));
hex = "R: " + Rval + " " + "G: " + Gval + " " + "B: " + Bval;
var r_hex = parseInt(r.value, 10).toString(16),
g_hex = parseInt(g.value, 10).toString(16),
b_hex = parseInt(b.value, 10).toString(16),
hex1 = "#" + pad(r_hex) + pad(g_hex) + pad(b_hex);
body.style.backgroundColor = hex1;
hex_out.innerHtml = hex + [
'<br/><font size="1px">GSC RGB Selector</font>'
].join('#hex');
}

Using On Blur to Call a Function

I am trying to have a web page update a value when the text field loses focus. I have tried a number of different suggested variations for the onblur event but nothing seems to work as expected. Currently I have the onblur in the html code on line 59
<input name="qty1" id="qty1" size="8" value="0" onBlur="productCost()" />
and I have tried to make the correction in the script as well.
function productCosts()
{
var totalMap = document.getElementById("qty1").onblur();
totalMap.value = ("qty1") * ("price1");
//$("#cost1").html (totalMap.toFixed(2));
alert(totalMap)
//var totalPlanner = ('qty2') * ('price2');
//var totalHiker = ('qty3') * ('price3');
}
I have created a fiddle to show the entire program. http://jsfiddle.net/Jn6LQ/ Any help would be really greatly appreciated.
It's easy with jQuery
$('#qty1').bind('blur', productCosts)
or with JS
document.getElementById('qty1').addEventListener('blur', productCosts)
Note: In the below, $ is not jQuery, the OP is using it as a shortcut for getElementById.
The line
totalMap.value = ("qty1") * ("price1");
multiplies the string "qty1" with the string "price1". Perhaps you meant to look up the elements, and then get their values:
totalMap.value = $("qty1").value * $("price1").value;
Separately, using onXyz attributes is usually not best practice. Instead:
$("qty1").onblur = productCosts;
$("price1").onblur = productCosts;
function productCosts() {
var value = $("qty1").value * $("price1").value;
$("cost1").innerHTML = value.toFixed(2);
}
(There I'm assuming the price can be changed as well, but that may not be the case on your page.)
Looking at the fiddle, though, you have a much bigger problem: You want to do that for multiple lines. Using id values to do that is going to make for gainly, over-large code. Instead, use a class on each input, and then relate it to the other inputs in the row using the fact they're all in the same row.
function productCosts() {
var row = this.parentNode.parentNode,
qty = row.querySelector(".qty"),
price = row.querySelector(".price"),
cost = row.querySelector(".cost"),
value = qty.value * price.value;
cost.innerHTML = value.toFixed(2);
}
var list, i;
list = document.querySelectorAll(".qty, .price");
for (i = 0; i < list.length; ++i) {
list[i].onblur = productCosts;
}
jQuery.blur() looks like what you're looking for:
$('#qty1').blur(function(){
alert('here');
});

How to provide elements/tags dynamically inside the find() in jquery

I have created several div with id's such as window1, window2 and so on. Now all I want to is find the tag from these above created divs. I am doing this inside the for loop but it is not working for me. Here is what I am doing
for(connectWindow=1;connectWindow<=xmlLength;connectWindow++)
{
//look for the to tag inside the html
var windo = "window"+connectWindow;
var to = "to"+connectWindow;
alert("Making connections" + windo +to)
//$("div#windo").find('strong#to')(function())
$("div#windo").find('p#to').each(function(){
alert("####################");
var name = $(this).text();
//display_function(name,country);
alert("Name is :::"+name);
});
}
Please let me know where I am going wrong. Also please let me know if there is any solution in JavaScript either.
Thanks !
You need to do it like this
$("div#" + windo).find('p#' + to).each(function(){ // <-- this uses your variable
alert("####################");
var name = $(this).text();
//display_function(name,country);
alert("Name is :::"+name);
});
Your code looks for an id="window" and id="to" instead of your variable
$("div#windo").find('p#to')
You really can just do it by ID since you are using the #(id selector)
$("#" + windo).find('#' + to)
Well, you need to actually use the variables:
$("div#" + windo).find('p#' + to).each(function(){
By the way - jQuery is written in JavaScript. If you're using jQuery, you're using JavaScript.

Categories

Resources