How do I take the result from "#sum" and have it auto duplicated in a textfield so that when I submit a form, the value gets sent also?
<script>
$(document).ready(function() {
$(":text").each(function() {
$(this).keyup(function() {
calculateSum();
});
});
});
function calculateSum() {
var sum=0;
$(":text").each(function() {
if(!isNaN(this.value) && this.value.length!=0 {
sum+=parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(0));
$("#myTextField").val(sum.toFixed(0)); //adding to text field
}
</script>
Is there a quick fix to this?
This is where the actual value updates on the HTML page.
<span id="sum">0</span>
It is not adding right. If I type in 500 in one of the fields it now takes the first number and repeats, so if I type 500 it outputs as 555
any help?
Your issue is is that ":text" is selecting myTextField. So your final value is being added back in.
5 = 5; 50 + 5 = 55; 500 + 55 = 555; You can try using the not selector.
$(":text:not('#myTextField')")
http://jsfiddle.net/RhRbR/
$(":text:not(#myTextField)").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum+=parseFloat(this.value);
}
})
The fiddle can show you the way.
Related
Hello guys J have problem at Javascript. This is the code,
function reply_click(clicked_id) {
var la = <? php echo json_encode($logOptions_id); ?> ;
var mood = clicked_id;
$.post('msg.php', {
myne: la,
mood: mood
}, function (data) {
$('#nov').html(data);
});
$('#postDiv').on('keydown', '#textarea', function (e) {
if ((e.which == 13) && !event.shiftKey) {
var textarea = $("#textarea").val();
$.post('pst.php', {
mibe: la,
voot: mood,
pst: textarea
}, function (data) {
var textarea = $("#textarea").val('');
});
}
});
}
The problem is when I clicked on item I get clicked_id, after post message, its ok, but then once again I clicking the item, I get second id, and after post enter button it post in to database difference id from first item and second, seems duplicating values, how many times I click on different items , getting different ids and this problem is spamming my DB.
Every time you click the button, you add another keydown binding to #textarea. So if you click the button 5 times, then when you press Enter the keydown binding will be run 5 times.
You should move $('#postDiv').on('keydown', '#textarea', ...) outside the function, and just do it once in the document ready handler.
I'm just looking for a bit of help on the best way to do this..
So I have a sample SQL Database:
Now from that DB I have a PHP page to show checkboxes ticked if there is a "1" in the corresponding checkbox field.
What I would now like to do is:
Once both checkboxes are ticked, I would like to display a 5 second timer or a message, something of that nature, but how do I ascertain if the boxes have both been checked?
I'm guessing I would have to run a query against the whole table and work from the variable I get back?
you may use change events
var i = 1, interval, timeout;
$('input[type=checkbox]').on('change', function(){
if ($('input[type=checkbox]').length == $('input[type=checkbox]:checked').length) {
$('div').show();
interval = window.setInterval(
function() {
$('div').text(i++);
},
1000
);
timeout = window.setTimeout(
function(){
document.location = 'http://google.com/';
},
5000);
}
else {
window.clearTimeout(timeout);
window.clearInterval(interval);
$('div').hide().text('0');
i = 1;
}
});
example to edit http://jsbin.com/uwofus/11/edit
example to test http://jsbin.com/uwofus/11
You tagged this with jQuery, so I'm assuming you want to do the check in the browser, and not in the database.
if ($("input[type='checkbox']:checked").size() == 2) {
//both boxes are checked
//display message/start timer here
} else {
//not all boxes are checked
}
You could give your checkboxes a class e.g. mycb, then count the number checked:
$('.mycb').change(function(){
if($('.mycb').size() == $('.mydb:checked').size())
{
// all checkboxes are checked - do something
}
});
I have a question about JQuery Min Max Validation looping through dynamic created input items.
In my php page i have a dynamic table who loops through the data in the DB.
Sometimes i have an table with 3 input Items (Cells) sometimes with 6 or 12 input items.
With jquery i found to validate min - max value of data, but it works only for the first input item.
How can loop throug all the input item to get the same min max validation?
Here the JQuery code:
$(document).ready(function(){
$("input").click(function(){
var enteredValue = $("input:#value_one").val();
var min=1;
var max = 3;
var num = parseInt(enteredValue);
if (min > num || max < num) {
alert('Number ' + num + ' is not a number between ' + min + ' and ' + max);
return false;
}
});
});
Here apart of the PHP HTML Code:
foreach($datas as $idactivite=>$dat){
$totalactiv=0;
$nbdiviseur=0;
foreach($dat as $dd){
$totalactiv+=$dd["note"];
$nbdiviseur++;
}
$mamoyactiv=$totalactiv/$nbdiviseur;
$position=3;
$mamoyactiv = substr($mamoyactiv, 0, $position);
$moyenneverticale[$idactivite]=$mamoyactiv;
// Here the input Item who loops through the DB Query to get them values:
$htmldroit.="<td id='myguaNote' bgcolor='$bgcolor' align='center'>
<input name='".$idactivite."_".$idagent."' id='value_one' maxlength='1' class='grand' value='".$dat[$idagent]["note"]."' ></td>";
$totalfamille+=$dat[$idagent]["note"];
$TabRes[$ind] += $dat[$idagent]["note"];
$TabObj[$ind] = " ";
$TabResColor[$ind]=0;
$ind++;
}
Somebody any ideas?
THX in advance
I think you're not really selecting the input field which was actually clicked.
Replace var enteredValue = $("input:#value_one").val() with
var enteredValue = $(this).val();
The callback function from click holds a reference to the clicked DOM element in the this keyword. wrap it in $() to make it a jQuery object and finally call val() on it.
Fiddle
Edit:
To validate multiple input fields on button click I used a helper class validate. Assuming all input fields you want to validate have this class you can bind some code to submit button's on click:
$("#submitButton").click(function(){
$(".validate").each(validateField);
});
First all elements having the class validate will be selected and on this collection we call jQuery's each() which takes a function handle as argument. This function (validateField in this case) should take to input arguments (index and element, see the documentation for more details - if you think of a strange for for a "for in"-loop you're not far off.).
I moved the your validation code in this function and simply replaced $(this) by $(element)
Fiddle
few tips
if you are working with dynamic data then don't use simple 'click' function, instead try .on ( with jQuery 1.7+)
$('document').on('click', 'input', function(){
var enteredValue = $(this).val();
//your rest of code
});
Try this
//========== Prototype to find out min value in an Array=========================
Array.prototype.min = function()
{
return Math.min.apply(null, this)
}
//============= Jquery Scripting===================================================
$selector=$("input"); //Your selector which is cursoring your inputs
$aryVal=new Array; //Define an Array
$selector.each(function() //Iterate to all the input
{
$aryVal.push(this.value); //push the value to array
});
var min = Math.min.apply(null, $aryVal); //Getting min value from array
alert(min);
It sounds like you might be looking for .on(), which will keep things up-to-date as the page changes, whereas the click you have is just on the state of the page when it's created. Try:
$("input").on("click",function(){
||
if (min > num || max < num) {
change to
// For a number not between min and max
if (num < min || num > max) {
// For a number between min and max
if (num >= min && num <= max) {
For testing:
<script>
function test(){
$html = document.getElementById("msg");
num = 100;
min = 10;
max = 100;
if (num < min || num > max) {
$html.innerHTML = "Num is not between min and max";
return;
}
if (num >= min && num <= max) {
$html.innerHTML = "Num is between min and max";
return;
}
}
</script>
<body onload="test()">
<div id="msg" style="border:1px solid #000000; height:100px">Answer has not been found!</div>
</body>
Good practice when creating a dynamic amount of elements which are being used to inject a variable somewhere is:
Give unique ID for identification.
Use CSS class. Class styles are meant to be repeated, ID's are not.
So if I were to generate a number of inputs 1 to 100
for ($i = 1; $i <= 100; $i++)
{
$IdAndName = "input" . $i;
echo("<input type='text' id='" . $IdAndName . "' name='" . $IdAndName . "' class='myStyle'/><br>\n");
}
Now you would have HTML elements with ID input1 to input100
You can then use the JQuery click event as you have, then use $(this).val() to retrieve it's value on click.
i have a javascript shopping basket, in which the sum is returning a NaN error,almost every time.
in the code i have
$('#add-to-basket select').selectbox();
$('#contents select').selectbox().change(function (e) {
var product = $(this).parents('.product');
var ppu = product.find('.ppu').val();
product.find('.price .wrapper .value').text($(this).val() * ppu);
var total = 0;
$('.product .price .value').each(function (index, value) {
total += new Number($(value));
});
var form = $(this).parents('form');
form.ajaxSubmit(function () {
});
$('#total .value').text(total);
});
i tried using parsefloatm but still it dosn't work...
$(value) gives you the jQuery-wrapped element, not the actual value.
You want $(value).val() instead if the elements are form inputs, or $(value).text() if not.
Also, instead of new Number(...) you should just use Number(...), or even +...:
$('.product .price .value').each(function (index, value) {
total += +$(value).val();
});
See this question for the difference between new Number and Number.
Ok ,
Lets say I am creating a form. And its an address form,form elements as such :
field 1 / house number
field 2 / street name
field 3 / suburb
etc etc etc
And someone fills in the form,:
1
smith street
townsville
What I want ( similar to stack overflows live form )
Is another form element, that propagates the form field entries LIVE but replaces spaces with text:
So it appears like: 1+snith+street+townsville
With a search button at the end. This then triggers the rest of the script we have already done, which basicaly grabs the lat and long of the address and displays a gmap.
Thats essentially it, but we would need that all this occurs, whilst on the form, and before submission.
Any help appreciated, have asked several other places. No joy, but always use StackOverflow..
Thanks Ozzy
$('#my_form input').change(function() {
var new_text = '';
$('#my_form input').each(function() {
new_text += $.trim($(this).val()).replace(' ', '+') + '+';
});
$('#my_display').val(new_text);
});
here something that might work. . .
$(document).ready(function(){
$('body').live('keypress', function (event) {
if ($(event.target).hasClass('form-element')) {
var text;
$('#yourform input.form-element').each(function() {
text += $(this).attr('value') + '+';
});
$('#yourtargetelementthatwillholdallthenames').attr('value', text.substring(0,text.length - 1))
}
});
});
i haven't tried this in a browser, but give it a shot. It might need some tweaking for your needs.
If you're submitting this for a search, use encodeURIComponent() instead so you encode everything needed, like this:
$("#form1 input[type=text]").bind("keyup change", function() {
var vals = $("#form1 input[type=text]").map(function() { return this.value; });
$("#otherField").val(encodeURIComponent(vals.join(" ")));
});