Replacing Value of Input based off of the sun of two inputs - javascript

Im trying to add up the sum of two inputs that already have a value in it. I wanted the sum to change value if any of the other two inputs change in value. I have this the following, but its not working:
<?php
while($row = mysqli_fetch_array($test)) {
echo "<tr class='saved_add'>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><select'>";
echo "<option value='service'";
if ($row['type'] == "service") {
echo "selected='selected'";}
echo ">Service</option>";
echo "<option value='hours'";
if ($row['type'] == "hours") {
echo "selected='selected'";}
echo ">Hours</option>";
echo "<option value='days'";
if ($row['type'] == "days") {
echo "selected='selected'";}
echo ">Days</option>";
echo "<option value='product'";
if ($row['type'] == "product") {
echo "selected='selected'";}
echo ">Product</option></select></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input/></td>";
echo "<td><input class='subtotal'/></td>";
echo "</tr>";
}
mysqli_close($con);
?>
JQuery:
$('.saved_add').each(function() {
sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
any ideas?

Something along these lines:
function calculateSum() {
$('.saved_add').each(function() {
sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});
}
// On first load
calculateSum();
// On change
$("input").change(calculateSum);
Your code will only calculate the value WHEN IT LOADS. You want to calculate it when it loads AND when the value changes, so you need the .change() function.

When you call .val() on an element it returns its value as a string. You have to convert it to a number first before you can do mathematical operations with it. To convert strings to integers, you can use the parseInt() method.
$('.saved_add').each(function() {
var sum = $('input:eq(2)', this).val() * $('input:eq(5)', this).val();
$(".subtotal").text(sum);
});

Edit, updated
Try
$('.saved_add').each(function(i, el) {
$(el).on("change", function() {
// cast `sum` as `Number`
sum = Number($('input:eq(2)', this).val() * $('input:eq(5)', this).val());
$(".subtotal").text(sum);
}).change();
});
jsfiddle http://jsfiddle.net/guest271314/20jeoc9y/

Thanks everyone for helping, i figured it out. Helps out to make each input as an ID so you can change it accordingly.
HTML:
<div id="saved1">
<input type="text" value="10" /><input type="text" value="10" /> <input type="text" value="10" />
<div id="subtotal1"></div>
</div>
<div id="saved2">
<input type="text" value="10" /><input type="text" value="10" /> <input type="text" value="10" />
<div id="subtotal2"></div>
</div>
JQuery:
function calculateSum() {
$("[id^=saved]").each(function() {
sum = $('input:eq(0)', this).val() * $('input:eq(1)', this).val();
$('input:eq(2)', this).val(sum);
});
}
// On first load
calculateSum();
// On change
$("input").change(calculateSum);
JSFiddle

Related

Counter works for 1st post but not for 2nd post

I have a JavaScript like counter that works on the 1st comment but the 2nd comment, I would appreciate any help given!
This keeps happening wether I use PHP or JavaScript, here is my JavaScript for the counter
var count = (function()
{
var counter = 0;
return function() {return counter +=1;}
})();
function displaycount()
{
document.getElementById("carrier").innerHTML = count();
}
function getComments($conn)
{
$sql = "SELECT * FROM comments";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{
$id = $row['uid'];
$sql2 = "SELECT * FROM users WHERE id='$id'";
$result2 = $conn->query($sql2);
if ($row2 = $result2->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row2['first_name']."<br>";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "<br>
<img src='image.ico' onclick='displaycount()'>
<p id='carrier'> 0 </p>";
echo "</p>";
if (isset($_SESSION['id'])) {
if ($_SESSION['id'] == $row2['id']) {
echo "<form class='delete-form' method='POST' action='".deleteComments($conn)."'>
<input type='hidden'
name='cid'
value='".$row['cid']."'>
<button type='submit' name='commentDelete'>
Delete
</button>
</form>";
} else {
echo "<form class='edit-form' method='POST' action='replycomment.php'>
<input type='hidden'
name='cid'
value='".$row['cid']."'>
<input type='hidden'
name='uid'
value='".$row['uid']."'>
<input type='hidden'
name='date'
value='".$row['date']."'>
<input type='hidden'
name='reply'
value='".$row['reply']."'>
<button>Reply</button>
</form>";
}
} else {
echo "<p class='commentmessage'>You need to be logged in to reply</p>";
}
echo "</div>";
}
}
}
The reason that only the first comment is updating is you using the id carrier in all your comments.
The way to fixed this is:
Change the following line in your PHP code
<p id='carrier'> 0 </p>
to
<p id="carrier-"'+$id+'"> 0 </p>
Note: try not expose the entity id, try to use another column in comment table, that is unique for each comment.
Change the click of the element, passing the column that you use in previous step, like this
<img src='image.ico' onclick='displaycount('.$id.')'>
Change your javascript function to
function displaycount(id) {
document.getElementById("carrier-"+id).innerHTML = count();
}
If you have a question, please leave a comment

Getting values of a particular row using jQuery

I have the following code which prints the values in a datatable.
<?php
foreach ($result as $val) {
?>
<input class="example" type="checkbox" value="yes" id="example" name="example"><?php echo $val->id; ?>
<?php } ?>
Now I want to send the value to the server when the checkbox is checked. I have the following code for the same, however I'm confused on how I can get the ID of the row which is echoed by PHP.
$(".example").change(function() {
var value = $('.example').attr('value');
console.log(value);
});
Thanks in advance.
You can set an another attribute to the checkbox like :
<input type="checkbox" data-id="<?php echo val->id ?>">
Then your code will :
$(".example").change(function() {
if($(this).prop("checked")) {
var value = $(this).val();
var id = $(this).data("id")
console.log(value);
console.log(id);
}
});

How to verify only one checkbox is selected from checkbox list

Here i am retriving data from database and i am doing insert,update and delete of data using checkbox.My problem is when i click more than two checkbox than also i am moving to update.php page but what i actually want is that when i click on update button first it will check that only one checkbox is selected from list if not than alert message should display like select only one checkbox. please help.Thanks in advance
Here i have put my code.
<!DOCTYPE html>
<html>
<head>
<title>Insert Update Delete</title>
</head>
<body>
<form name="dataform" id="data" action="" method="get">
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db_new", $connection);
$query=mysql_query("select * from student_info");
echo "<table>";
while($row=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>"; ?> <input type="checkbox" id="box" name="num[]" class="other" value="<?php echo $row["id"];?>" /> <?php echo "</td>";
echo "<td>"; echo $row["roll_no"]; echo "</td>";
echo "<td>"; echo $row["name"]; echo "</td>";
echo "<td>"; echo $row["division"]; echo "</td>";
echo "<td>"; echo $row["std"]; echo "</td>";
echo "<td>"; echo $row["gender"]; echo "</td>";
echo "<td>"; echo $row["subject"]; echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="insert" value="insert"/>
<input type="submit" name="update" value="update"/>
<input type="submit" name="delete" value="delete"/>
</div>
</form>
<?php
if(isset($_GET["insert"]))
{
$box = $_GET['num'];
$count =count($box);
if ($count == 0){
header('Location:insert.php');
}
elseif($count == 1){
header('Location:data.php');
}
}
?>
<?php
if (isset($_GET['update'])){
$box = $_GET['box'];
$count =count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:update.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
echo $id;
header("location:update.php?id=".$id);
}
}
}
?>
<?php
if (isset($_GET['delete'])) {
$box = $_GET['num'];
$count = count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:data.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
mysql_query("delete from student_info where id = $id");
}
}
}
?>
</body>
</html>
You could use a radio button for this instead of a checkbox.
see sample here
Use Radio Instead of CheckBox
Or if you must use a checkbox do this:
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
I would use a radio button, however I don't know your situation so here's a solution using jQuery. You want to select all of the checkboxes that are checked then see if the length of that array is greater than one. Here's the javascript code you'll need and a jsbin if you want to look at it.
http://jsbin.com/qakuzajaza/edit?js,output
$("#submitbutton").click(function() {
var count = $("input[type=checkbox]:checked").length;
if (count > 1) {
alert("Only 1 can be selected");
} else {
// submit data
}
});
1. Try this, it will not allow you to check only one checkbox at a time.
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('#ckeckboxlistId').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
The approaches are more or less similar. Try this:
submitForm(); //according to an event you prefer (click some button or anchor , no button over $ .ajaks.
function submitForm(){
var tag = document.getElementById("tdForm");
var chkbx = $(tag).find("input[type='checkbox']:checked").length;
if (chkbx !== 0) {
if (chkbx > 1) {
alert("more then 1");
}else{
alert("form submited"); //$(tag).submit();
}
}else{
if (chkbx === 0) {
alert("nothing cecked");
}
}
};
Tested works for me. Hope it helps!
While I think the radio buttons or previous validation, and interception of errors on the rules for completing the form, are much more affordable.

How to get each checked checkbox using jQuery

I have the following:
PHP/HTML CODE:
<?php
$c = 1;
foreach($this->contactos as $contacto){
?>
<div class="uk-form-row">
<label for="contactopadrino<?php echo $c; ?>" class="uk-form-label"><?php echo $contacto->email; ?></label>
<input class="contactopadrinos" name="contactopadrino[]" id="contactopadrino<?php echo $c; ?>" type="checkbox" value="<?php echo $contacto->email; ?>" />
</div>
<?php
$c++;
}
?>
jQuery CODE:
function validarEnviarDescuento(){
$('#errorofertacontainerdescuento').css('display','none');
$('#errorofertadescuento').html('');
var validar = 0;
var vacio = 0;
for(var e=1; e<6; e++){
var email = $("#email_contactopadrino"+e).val();
if(!validarEmail(email) && email != ''){
validar++;
}
if(email != ''){
vacio++;
}
}
if(!vacio){
$('input:radio:checked').each(function () {
var $this = $(this);
if ($(this).prop('checked')) {
return true;
}
});
$('#errorofertadescuento').append('<li>' + '<?php echo JText::_('COM_CSTUDOMUS_ERROR_SIN_SELECCIONAR'); ?>' + '</li>');
$('#errorofertacontainerdescuento').css('display','block');
return false;
}
if(validar){
$('#errorofertadescuento').append('<li>' + '<?php echo JText::_('COM_CSTUDOMUS_ERROR_EMAIL_INCORRECTO'); ?>' + '</li>');
$('#errorofertacontainerdescuento').css('display','block');
return false;
}
else{
return true;
}
}
Im trying to go through each input and if one is checked it should return true and submit but what I have done is not working.
You don't need to use each. instead use cobination :checked and length
return $('input:checkbox:checked').length;
It will return true if anyone of the checkbox button has checked
You can use :checked with selector to get all radio buttons those are checked.
$('input:radio:checked')
Description: Matches all elements that are checked or selected, jQuery docs
If you want to check if atleast one radio is checked then you can use length
if($('input:radio:checked').length)
{
}
For iterating through checked radio you can use each
$('input:radio:checked').each(function(){
alert(this.value);
});

retrieve value of input

I have this:
<?php $i=0;?>
<?php foreach($x as $y): ?>
<input type="hidden" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
<?php $i = $i + 1; ?>
<?php endforeach; ?>
I need to get the value of each "theid" like this:
<script type="text/javascript">
function somefunction(element, optionTitle) {
var num = document.getElementById('theid').value;
...
</script>
How can i do that considering the fact that "theid" has the $i added?
Thanks.
If you have multiple input fields and you want to do the same action on several, you could use getElementsByClassName instead of getElementById:
PHP
<input type="hidden" class="theclassname" id="theid<?php echo $i;?>" value="<?php echo $someVariable;?>"/>
JS:
<script type="text/javascript">
function somefunction(element, optionTitle) {
var myEles = document.getElementsByClassName('theclassname');
// loop over myEles and act on each one
for (var i=0; i < myEles.length; i++) {
alert("Input with id: " + myEles[i].id + " has value: " + myEles[i].value);
}
}
</script>
I would recommend using jQuery, jQuery selectors support wildcards:
$('input[id^=theid]')
See http://api.jquery.com/category/selectors/ for further reading on this topic.
If you are using jQuery would be easy like this:
$('input[id^="theid"]').each(function () {
console.log($(this).val()); //value of each theid
});
Here is a jsBin.

Categories

Resources