I am trying to calculate tax also get the id for each in a single dropdown like this
<td><select name="tax[]" class="form-control tax" id="tax_1" style="width:80px;">
<option value="">Tax</option>
<?php $s1 = mysqli_query($con, "select * from taxes"); while($s2 = mysqli_fetch_array($s1)) {
$options .= "<option value='". $s2['tax_id']."_".$s2['name']."'>".$s2['name'].'-'.$s2['rate'] . "</option>";
?>
<option value="<?php echo $s2['tax_id']."_".$s2['rate']; ?>"><?php echo $s2['name'].'-'.$s2['rate']; ?></option>
<?php
}
?>
</select></td>
These values i am passing to jquery for auto calculation purpose. Values will be like id_rate (1_5) , I have to split it and rate i should use for calculations. How to split it there.
now i am calculating it like this
$('body').on('change', '.quantity,.price,.discount,.tax', function() {
var tr = $(this).parent().parent();
var qty = tr.find('.quantity').val();
var price = tr.find('.price').val();
var tax = tr.find('.tax').val();
var dis = tr.find('.discount').val();
var amt = (qty * price) - (qty * price * dis) / 100;
var tax1 = (amt * (tax / 100));
tax1 = Number((tax1).toFixed(2));
But i am not getting how to split
You can try split function.
$('body').on('change', '.quantity,.price,.discount,.tax', function() {
if($(this).hasClass("tax")){
var taxVal= $(this).val();
var tax_id=taxVal.split('_')[0];
var rate=taxVal.split('_')[1];
}
}
function Splitval(obj) {
alert("Your Value :" + $(obj).val());
alert("Split Value :" + $(obj).val().split('_')[1] + "_" + $(obj).val().split('_')[0]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="abc" type="text" onChange="Splitval(this)">
Related
I have a problem in my code. My jQuery code is only implement of the first row of table not on others. Here is my code:
<tr>
<td><?php echo $row['serial no.'] ?></td>
<td><?php echo $row['pname'] ?></td>
<td><input type="text" class="form-control" id="prate" name = "uprice" value="<?php echo $prate = $row['uprice'];?>"></td>
<td> <input type="number" class="form-control" id="pqty" name = "quantity" value ="<?php $quant = ""; echo $quant; ?>"></td>
<td> <input type="text" class="form-control" id="pTotal" name = "price" value = "<?php $tprice = ""; echo $tprice; ?>" ></td>
</tr>
This is my HTML code:
<script>
$("#prate").keyup(function(){
// console.log('presssed');
var prate = document.getElementById('prate').value;
var pqty = document.getElementById('pqty').value;
var ptotal = parseInt(prate) * parseInt(pqty);
document.getElementById('pTotal').value = ptotal;
});
$("#pqty").keyup(function(){
// console.log('presssed');
var prate = document.getElementById('prate').value;
var pqty = document.getElementById('pqty').value;
var ptotal = parseInt(prate) * parseInt(pqty);
document.getElementById('pTotal').value = ptotal;
});
</script>
What can I try to resolve this?
What you have to do is (1) Gather all those classes in a Variable. (2) Run Foreach loop on each element. (3) While looping each element, you must sum all of these elements' values.
// Step 1: Fetch Classes
var FetchedClasses = document.getElementsByClassName("myclass");
var Sum = 0;
// Step 2: Iterate them
Array.prototype.forEach.call(FetchedClasses, function(element) {
// Step 3: Sum up their values
Sum = Sum + element.value; //
});
// Now Show it anywhere you like.
Use class selector (not id selector) and each method to emplement your desired commands on all rows.
ID must be unique, instead put a class as a reference for each table data and try each method:
$('.pqty').each(function(i, element){
$(element).keyup(function(evt) {
/* anything */
})
})
As you know, id must be unique on whole page. So on each row and items, either you have make unique id (Which will be complicated to bind event), so you can go with class or as below script for binding the events.
<script>
$('input[name="uprice"]').keyup(function(){
var prate = $(this).val();
var pqty = $(this).parent().next().find('input[name="quantity"]').val();
var ptotal = parseInt(prate) * parseInt(pqty);
$(this).parent().next().next().find('input[name="price"]').val(ptotal);
});
$('input[name="quantity"]').keyup(function(){
var prate = $(this).parent().prev().find('input[name="uprice"]').val();;
var pqty = $(this).val();
var ptotal = parseInt(prate) * parseInt(pqty);
$(this).parent().next().find('input[name="price"]').val(ptotal);
});
</script>
Not have tested but should help you.
I have three selects on my form.
Each depends on the values of the previous one.
I mean there is drop-down list with categories, car brand and car model.
The list with car brand must show the brands of chosen category. Also car model have consist of models of chosen brand.
The form HTML, the server language is PHP, I want to use Ajax JQUERY to get the value of the select.
Help please how it should be?
You should do something like this:
jQuery(function($) {
var brands = {
'Trucks': ['Ford', 'Chevrolet'],
'Cars': ['Honda', 'Volkzwagen'],
}
var models = {
'Ford': ['Model1', 'Model2'],
'Chevrolet': ['Model3', 'Model4'],
'Honda': ['Model5', 'Model6'],
'Volkzwagen': ['Model7', 'Model8'],
}
var $brands = $('#brand');
var $models = $('#model');
$('#category').change(function () {
var category = $(this).val(), brnds = brands[category] || [];
var html = $.map(brnds, function(brnd){
return '<option value="' + brnd + '">' + brnd + '</option>'
}).join('');
$brands.html('<option>Select</option>'+html)
$models.html('');
});
$('#brand').change(function () {
var brand = $(this).val(), mdls = models[brand] || [];
var html = $.map(mdls, function(mdl){
return '<option value="' + mdl + '">' + mdl + '</option>'
}).join('');
$models.html(html)
});
});
Check this JSFiddle: http://jsfiddle.net/minijavi19/2pza5/1908/
Of course if you want to use Ajax you should set your variables with it.
Thanks to everybody who paid attention to my question!!! But I want share with you with my solution. There ara 3 files: index.php, ajax-queries.js, php-funcs.php.
//index.php
$categories = $mysqli->query("SELECT category_id, category_name FROM
categories") or die($mysqli->error);
<form action="../../php/admin_funcs.php" method="post">
<select id="cat_slc" class="lists" name="category" >
<option disabled selected>Выберите категорию</option>
<?php
while ($crow = $categories->fetch_assoc())
{
echo "<option
value='".$crow['category_id']."'>".$crow['category_name']."
</option>";
}
?>
</select>
<select id="marka_slc" class="lists marka-select" name="marka" >
<option disabled selected>Выберите марку</option>
</select>
<select id="model_slc" class="lists model-select" name="mode">
<option disabled selected>Выберите модель</option>
</select>
</form>
//ajax-queries.js
$('#cat_slc').change(function () {
var cat_id = $(this).val();
var url = '../../php/data_functions.php';
$('#marka_slc').load(url + '#mark-block', {cat_id: cat_id}, function () {
$('.marka-select').fadeIn('slow');
});
});
$('#marka_slc').change(function(){
var mark_id = $(this).val();
var url = '../../php/data_functions.php';
$('#model_slc').load(url + '#model-block', {mark_id: mark_id}, function (){
$('.model-select').fadeIn('slow');
});
});
//php-funcs.php
<?php
require_once "db_connect.php";
function GetMarkas(){
global $mysqli;
$category_id = $_POST['cat_id'];
$query = "SELECT marka_id, marka_name FROM marka WHERE category_id =
'".$category_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['marka_id']."'>".$row['marka_name']."
</option>";
}
return $data;
}
function GetModels(){
global $mysqli;
$mark_id = $_POST['mark_id'];
$query = "SELECT model_id, model_name FROM model WHERE marka_id=
'".$mark_id."'";
$result = $mysqli->query($query);
$data = '';
while ($row = $result->fetch_assoc()){
$data .= "<option value='".$row['model_id']."'>".$row['model_name']."
</option>";
}
return $data;
}
if(isset($_POST['mark_id'])){
echo"<div id='model-block'>" . GetModels() . "</div>";
}
else if(isset($_POST['cat_id'])){
echo"<div id='mark-block'>" . GetMarkas() . "</div>";
}
Good day every one. I want to insert my php code in my jquery. I want to show my data in database using PHP and I want to put it in a option box. I used var in jquery plus the code of my php but isn't working. Please help me.
Shows the data:
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
while ($result2 = mysql_fetch_assoc($res)){
$name = $result2["name"];
?>
jquery code(dynamic adding text box)
var nitem =0;
var ntotal = 0;
var option = <?php echo" <option value='$name'>$name</option>";} ?>;
function totalItemExpence(){
ntotal = 0;
$('.expense_cost').each(function(){
if($(this).val() != ""){
ntotal += parseFloat($(this).val());
}
});
//$('#total').val(ntotal);
}
$(document).on('change keyup paste', '.expense_cost', function() {
totalItemExpence();
mytotal();
});
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'<select class="expense_name" id="' + nitem '">"'+ option +'"</select>' +
'<input class="expense_desc" placeholder="Expense Description" id="' + nitem + '" required/>' +
'<input class="expense_cost" onkeypress="return isNumber(event)" placeholder="Expense Cost" id="' + nitem + '" required/> ' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem + " .expense_cost").each(function(){
if($(this).val() != ""){
ntotal -= parseFloat($(this).val());
}
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
Try this for while loop :
<?php
$res2 = mysql_query("SELECT * FROM expense_maintenance ORDER BY name Asc");
$options = '';
while ($result2 = mysql_fetch_assoc($res)){
$options .= "<option value='{$result2["name"]}'>{$result2["name"]}</option>";
}
?>
And JS part :
...
var option = "<?php echo $options; ?>";
...
This line:
var option = "<?php echo "<option value='$name'>$name</option>"; ?>";
must be in your .php file, because php code won't be executed in a .js file (that's why it's called .php)...
You can wrap that line in a <style> tag in your .php file
Also, don't forget to add these things --> "
And to remove this one --> }
I have the following select list:
SELECT LIST 1:
<select name="productcolor" id="productcolor" onChange="GetAvailProductSizes();">
<option value=""><? echo $langdata['oneprodpage_selectcolor']; ?>...</option>
<? foreach ($thisproduct['availcolors'] as $color) { ?>
<option value="<? echo $color['id']; ?>"><? echo $color['name']; ?></option>
<? }; ?>
</select>
SELECT LIST 2:
<select name="productsize" id="productsize" style="width: 120px;">
<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>
</select>
If in LIST 1 no options where selected, LIST 2 will be empty. It's like LIST 2 depends of LIST 1.
This is made with this function:
<script type="text/javascript"><!--
function GetAvailProductSizes() {
$('select#productsize option').remove();
$('select#productsize').append('<option value=""><? echo $langdata['oneprodpage_selectsize']; ?>...</option>');
var color = $('#productcolor').val();
if (color > 0) {
var availsizes;
var http_request = new XMLHttpRequest();
http_request.open( "GET", '<? echo ROOT; ?>/autocompleteavailsizes/?productid=<? echo $thisproduct['id']; ?>&color=' + color, true );
http_request.send(null);
http_request.onreadystatechange = function () {
if ( http_request.readyState == 4 ) {
if ( http_request.status == 200 ) {
availsizes = eval( "(" + http_request.responseText + ")" );
for (var i = 0; i < availsizes.length; i++) {
$('select#productsize').append('<option value="' + availsizes[i].id + '">' + availsizes[i].name + '</option>');
};
} else {
alert( "There was a problem with the URL." );
}
http_request = null;
}
};
};
}
//-->
</script>
Now, I want the SELECT LIST 2 to be hidden until SELECT LIST 1 was not touched. Any help please with PHP or jQuery. Thank you!
Simply add display:none to the style attribute of the second list and use $('select#productsize').show(); inside your function to let it appear,
Database
$mySql = "SELECT field FROM fields";
$result = mysql_query($mySql);
Html:
<select id="combo1" class="combo" data-index="1">
<option></option>
<?php
while($r = mysql_fetch_array($result))
{
echo "<option value=" .$r['field '] . ">".$r['field '] ."</option>";
}
?>
</select>
<div id="combos"></div>
jQuery
<script type="text/javascript">
$('body').on('change', '.combo', function() {
var selectedValue = $(this).val();
if (selectedValue !== '' && $(this).find('option').size() > 8) {
var newComboBox = $(this).clone();
var thisComboBoxIndex = parseInt($(this).attr('data-index'), 10);
var newComboBoxIndex = thisComboBoxIndex + 1;
$('.parentCombo' + thisComboBoxIndex).remove();
newComboBox.attr('data-index', newComboBoxIndex);
newComboBox.attr('id', 'combo' + newComboBoxIndex);
newComboBox.addClass('parentCombo' + thisComboBoxIndex);
newComboBox.find('option[val="' + selectedValue + '"]').remove();
$('#combos').append(newComboBox);
}
});
</script>
Questions:
This code is creating comboboxes with my database talble fields.
My problem is that fields cant be repeated when selected once.
Where is the error in the code? Or what am I thiking wrong?
It was supposed to be like that: http://jsfiddle.net/JaVVe/1/
The problem is you are checking size() > 8, so for it work there must be more than 8 options. Change that to size() > 2. Other than that your code will work.
The other problem is you aren't wrapping the option values in quotes. Add quotes:
echo "<option value=\"" .$r['field'] . "\">".$r['field'] ."</option>";
You also have a space after field:
$r['field ']
// ^ here, remove that
on site example is
<option val="Opt1">
In your html it's value attribute instead of val so you need to change
newComboBox.find('option[val="' + selectedValue + '"]').remove();
to
newComboBox.find('option[value="' + selectedValue + '"]').remove();