JS Variable not Posting - javascript

I have this JavaScript code that changes a field value and works ok for HTML output.
<script>
var basePrice = 10;
$(".vars").change(function() {
newPrice = basePrice;
$('.vars option:selected').each(function() {
newPrice += $(this).data('price')
});
$('#item-price').html(newPrice);
});
</script>
I also have a form that posts data to another php page which also works ok, only the #item-price var isn't posting. I'm nearly sure I have the field named correctly as below.
<input type="hidden" name="product_amount" id="item-price" value="">
Can anyone help?

input fields don't use .html() they use .val()
$('#item-price').val(newPrice);
Also, you may want to init that newPrice var...
var newPrice = basePrice;
Additionally, as Brent mentioned, you may want to use parseInt() or parseFloat() to convert the string data value to a usable number.
newPrice += parseFloat($(this).data('price'));

Related

Count form inputs

I have this page (things which I need are at the bottom) and I need to count values from input (type numbers; it's quantity of product) and print value for each product (there are 4 products) and then all values together. Now I'm trying code for count value for each product. I have this Fiddle (code at the end of this post) code, but at my web it doesn't work. And question is why? And next question, after I will have values for each product, how can I pick them from and adding together?
HTML
<input type="number" value="10" class="number rowModre" min="0" name="pocetModre" id="pocetModre">
<div class="cena" id="cenaModre"></div>
JS
var string = $('#pocetModre').val();
$('#cenaModre').html(string);
Thank you very much.
Your question is not quite clear but i guess you are looking for something like this:
http://jsfiddle.net/akpn3/522/
var total = 0;
$(".number").each(function () {
$(".listprice").append("US $" + $(this).val() +"</br>");
total = total + parseInt($(this).val());
});
$(".listprice").append("Total : US $" + total);

How do you return data from javascript into a html form?

I was wondering if anyone can help? What I am trying to do is retrieve the word count from javascript code into a form and then pass it into php along with the rest of the form which will check that the word count is a certain length or else it won't be submitted.
The javascript is as follows.
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
My problem is returning wordCount into a hidden field in a form. I am not too good with javascript and am not sure how to modify this code to make it work. The rest I can figure out but am stuck here. Thank you for your help, it is greatly appreciated.
$('#wordCount').val(wordCount);
$('#totalChars').val(totalChars);
$('#charCount').val(charCount);
$('#charCountNoSpace').val(charCountNoSpace);
Use .val() instead of .html(), because .val() refers to the value of an input field.
Your HTML inside the form should include a hidden input field:
<input type="hidden" id="word_count" name="word_count" value="0" />
Then inside your JS:
$('#word_count').val(wordCount);
All together embedded inside your function:
counter = function() {
var value = $('#msg').val();
if (value.length == 0) {
$('#wordCount').html(0);
$('#totalChars').html(0);
$('#charCount').html(0);
$('#charCountNoSpace').html(0);
return;
}
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
var totalChars = value.length;
var charCount = value.trim().length;
var charCountNoSpace = value.replace(regex, '').length;
$('#wordCount').html(wordCount);
$('#word_count').val(wordCount);
$('#totalChars').html(totalChars);
$('#charCount').html(charCount);
$('#charCountNoSpace').html(charCountNoSpace);
};
$(document).ready(function() {
$('#count').click(counter);
$('#msg').change(counter);
$('#msg').keydown(counter);
$('#msg').keypress(counter);
$('#msg').keyup(counter);
$('#msg').blur(counter);
$('#msg').focus(counter);
});
If you have INPUT fields in your form, use val()
$('#wordCount').val(wordCount)
That would work for a field like this:
Be aware that there's a difference between "id" and "class". jQuery allows you to select elements based on their properties. The "id" property gets selected with "#", just like you'd do it in CSS. So make sure you have that "id='wordCount'" defined in your hidden field.
Have a look at this http://www.hscripts.com/scripts/JavaScript/word-count.php
There are plenty of examples online, just google "javascript count words in textbox"
Some imporntant notes:
A very long string with no spaces is still 1 word so don't forget to set the max length for fields
If you are doing this as a sort of validation be aware of the fact that you can not trust a form field because it can be easily manipulated, so don't forget to check the word count on the server side after the form is submitted.
The Code that you are showing is not just javascript it also includes jquery, please make sure you included jquery
<script src = "http://code.jquery.com/jquery-1.11.1.min.js"></script>
$('#field').val('asdf'); //Sets Value of a input type="text"
$('#field').html('sadf'); //Sets the html of a div
Using javascript you use either value for a input or innerHtml for a div or other text based element
document.getElementById('field').value = 'asdfsadf';
document.getElementById('field').innerHtml= 'asdfsadf';
Also instead of using a form submit consider using jquery $.ajax(there is nothing wrong with form submits but there are benefits to knowing jquery as well such as you came make async requests
http://api.jquery.com/jquery.ajax/
You will want to use a hidden field such as the following and have it in the form
<form id="myform" action='posttome.php'>
<input type="hidden" id="wordCount"/>
<input type="submit" value="sbumit"> //Submits Form
</form>
Then set its value by using of of three methods, a an elements html, an elements value, or a javascript variable $('#wordCount').val()
$('#wordCount').val($('#wordCountSoruceDiv').html()); // Sets the value to another divs html
$('#wordCount').val($('#wordCountSourceInput').val()); // Sets the value to another inputs value
$('#wordCount').val(wordCountVariable); // Sets the value to a variable

How to concatenate a JS variable in an HTML script?

Can I do something like this?
var counter = SomeJSFunctionThatReturnsAvalue();
<tr><td> <input type="file" name="file-upload"+"_counter" id="file-upload" /></tr></td>
Can I do that? I need to append an underscore and an incremented number to the name.
Also, an off-topic question - that function above returns the value of an input type, for example:
<input type="hidden" name="hidden-input-type" value="2" />
Is the value "2" a number that I can use for math operations? If not, how can I make it one?
Here you go fella.
<head>
<script>
function test($count) {
document.getElementById("test1").setAttribute("name","file-upload_" + $count);
}
</script>
</head>
<body>
<p>some content</p>
<input id="test1" type="file" name="file-upload" id="file-upload" value="2"/>
<p>some other content</p>
<script>test(1);</script>
</body>
Your SomeJSFunctionThatReturnsAvalue(); would pass it to test() function.
to get the value of "2" from your second question for use in a math function, just do:
var value = document.getElementById("test1").getAttribute("value");
document.write(parseInt(value, 10) + 3);
which returns 5.
To append the return value of your function to the name of the input tag, you can assign it to the name attribute of the input.
var counter = SomeJSFunctionThatReturnsAvalue();
var fileUpload = document.getElementById('file-upload');
fileUpload.name = fileUpload.name + "_" + counter;
You can get the type of a variable by using "typeof"
typeof myValue; // "string"
You can change this to an integer by using the parseInt() function.
var intValue = parseInt(myValue, 10);
You can change the name using .setAttribute("name", theNameUwantToChangeTo);:
function changeName(number){
var ele = document.getElementById("file-upload");
ele.setAttribute("name", b.getAttribute("name")+ "_" + number);
}
changeName(number);
To get the value, just .value:
function getV(){
return document.getElementById("file-upload").value;
}
var number = getV();
In case it does not return int, use parseInt()
function getV(){
return parseInt(document.getElementById("file-upload").value);
}
var number = getV();
Maybe you would benefit from looking into Angular.js or Ember.js if you are trying to do things like this. They can do data binding so that you can make readable and dynamic code just like what you are trying to create in your question.
If not that^ then this:
I saw you mentioned in a comment that you are dynamically creating the list. That is where you should be assigning the correct name with the counter (assuming there's no desire for counter to change dynamically. If there is a dynamic change then tell us what events are doing the change) Could you show us the code that is doing that please?

Dynamically loaded form won't update correctly

I have a form which is loaded into the page using .load(). I want to update the form with the HTML I compute in str, but my code isn't updating the form correctly. Why?
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
});
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
}
You have to put the form modification in the load completion function like this:
if($(this).is('.step3')){
//Splits the comma seperated values into input fields
var active_fields = ($('#templateFields').val()).split(',');
$('#loadedcontent').load('template.html #step3',function(){
$('#steps').text('Step Three');
$('#start.btn').text('Save Template & Values').removeClass('step3').addClass('step4');
str = "";
for(var i = 0; i<active_fields.length; i++){
str += '<label>'+active_fields[i]+'</label><input name="'+active_fields[i]+'" type="text" class="span3">';
}
$('form#values.well').html(str);
});
}
The way you were doing it, your code to modify the form was running before the form finished loading so it wouldn't find the content and thus couldn't modify it.
Sorry, I figured i couldnt nest a form within a form. I think thats why it didnt work

Javascript Multiplication and Totals

I have several fields that people will put in loan totals... We'll say loan1 and loan2 just to keep it simple.
window.addEvent('domready', function() {
$('loan1').addEvent('change', rekenen1);
$('loan2').addEvent('change', rekenen1);
});
function rekenen1(){
$('subtotal').value = Number($('loan1').value) + Number($('loan2').value) ;
}
When they enter the data I have it create a subtotal of all the loans. Now I want to make a grand total by taking 1% of the subtotal and adding 295 for the grand total. I need help making this into javascript.
So the equation:
loan1 + loan2 = subtotal
(subtotal*.01)+295=Grandtotal
Thank you for your help!
Provided you have a field with id grandtotal you can just add a line to you rekenen1 function:
function rekenen1(){
var subtotal = Number($('#loan1').val()) + Number($('#loan2').val());
$('#subtotal').val(subtotal);
$('#grandtotal').val(subtotal*0.01+295);
}
Edit:
I gone without saying that the addEvent have to change too:
$().ready(function() {
$('#loan1').addEvent('change', rekenen1);
$('#loan2').addEvent('change', rekenen1);
});
Changed rekenen1 function to use the jquery val function too
changed the event

Categories

Resources