Calculate sum of select fields in a dynamic form - javascript

I have a problem that it's been haunting me for a few days already, I have a dynamic select field where the user pick an ingredient from the DB and if he wants to add more ingredients he just click on 'Add' button and another select field is created, all select fields show its name and price(as text) and there's an input text field( basePrice) that should have the sum of every select created
Select field
<select name="ingredienteId[]" id="ingredienteId" onchange="DoMath()">
<?php foreach($ingredientes as $ingrediente) {
$essaEhATorta = $torta['ingredienteId'] == $ingrediente['id'];
$selecao = $essaEhATorta ? "selected='selected'" : "";
?>
<option value="<?=$ingrediente['id']?>" <?=$selecao?>>
<?=$ingrediente['nome']?> <?=$ingrediente['price']?>
</option>
<?php } ?>
</select>
Dynamic select field
$('#add').click(function() {
var newSelect = $('<label>Ingrediente</label> <select name="ingredienteId[]" id="ingredienteId" class="form-control"> <?php foreach($ingredientes as $ingrediente) {$essaEhATorta = $torta["ingredienteId"] == $ingrediente["id"];$selecao = $essaEhATorta ? 'selected="selected"' : "";?> <option value="<?=$ingrediente["id"]?>" <?=$selecao?>><?=$ingrediente["nome"]?><?=$ingrediente["preco"]?> </option><?php } ?> </select>')
$('#notas').append(newSelect);
});
basePrice input text field
<input class="form-control" type="text" value="<?=$torta['precoBase']?>" name="precoBase" id="basePrice"/>
As I said before, the select option has the name/price of the product as text, <?=$ingrediente['nome']?><?=$ingrediente['price']?>, so as I only wanted the price I came up with this code:
DoMath()
function DoMath(){
var e = document.getElementById("ingredienteId");
var finalPrice= e.options[e.selectedIndex].text;
var noLetterPrice = finalPrice.replace(/[^0-9,"."]/g,'');
var result = parseFloat(noLetterPrice);
document.getElementById("basePrice").value = result;
View
Part of my code is in portuguese but I hope u guys understand
As you can see the conversion part works but I have no idea how to make the sum part work, I have tried a few things but nothing seems to work

Instead of taking value and find price using regex will create issue when options names contains some digital values.
In Jquery we can provide any custom attribute to any field.So take that price in one of custom attribute in option.It will be very easy.
Just try below code
Select Field HTML Structure
<input type="button" name="add" id="add" value="Add" />
<input class="form-control" type="text" value="0" name="precoBase" id="basePrice"/>
<div id="notas">
<div id="ing_div">
<label>Ingrediente</label>
<select name="ingredienteId[]" class="baseingredient">
<option value="" ing-price="0"> Select Price</option>
<?php
foreach ($ingredientes as $ingrediente) {
$essaEhATorta = false;
$selecao = $essaEhATorta ? "selected='selected'" : "";
?>
<option value="<?= $ingrediente['id'] ?>" <?= $selecao ?> ing-price="<?= $ingrediente['price'] ?>">
<?= $ingrediente['nome'] ?> <?= $ingrediente['price'] ?>
</option>
<?php } ?>
</select>
</div>
</div>
In above HTML i have taken Price in ing-price attribute.
Javascript Code
<script>
$(document).on("click",'#add',function() {
var newSelect = $('#ing_div').clone();
newSelect.find("select[name='ingredienteId[]'").val();
$('#notas').append(newSelect);
});
$(document).on("click",".baseingredient",function(){
tot=0;
$(".baseingredient").each(function(){
tot+=parseFloat($(this).find("option:selected").attr("ing-price"));
})
$("#basePrice").val(tot);
});
</script>

You should use .on() instead of .click() and onchange, like this:
$(document).on('click','#add',function(){
var newSelect = $('<label>Ingrediente</label> <select name="ingredienteId[]" id="ingredienteId" class="form-control"> <?php foreach($ingredientes as $ingrediente) {$essaEhATorta = $torta["ingredienteId"] == $ingrediente["id"];$selecao = $essaEhATorta ? 'selected="selected"' : "";?> <option value="<?=$ingrediente["id"]?>" <?=$selecao?>><?=$ingrediente["nome"]?><?=$ingrediente["preco"]?> </option><?php } ?> </select>')
$('#notas').append(newSelect);
});
$(document).on('change','#ingredienteId',function(){
// calculate sum of every select fields
});
The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().
From the documentation of .on():
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

You can use each() inside your script, which totals the cost of ingredients, when a select field has been changed.
We have to assign first class tag for your select inputs.
<select class="ing" .....
Have it also to the "to be appended" select inputs.
var newSelect = $('<label>Ingrediente</label> <select class="ing" .....
Using each(), we can run through all the select fields that has class tag of ing:
$(document).on("change", ".ing", function(){ /* WHEN A SELECT FIELD HAS CHANGED */
var total = 0;
$('.ing').each(function() { /* RUN ALL SELECT FIELD */
total = total + parseInt($(this).val()); /* SUM UP ALL */
});
$("#basePrice").val(total); /* CHANGE THE VALUE OF BASE PRICE FIELD */
});
I prefer having
$(document).on("change", ".ing", function(){
rather than your previous
function DoMath(){
function due to the dynamically appended select fields.
Here is a jsfiddle (example) that you can look up to.

Related

Select tag HTML dynamic javaScript PHP

Hello I want to achieve is to make "Select Form HTML" dynamic using JavaScript, What I mean by that is I expect every time I select a dropdown must be selected the value that I set to that tag.
The data from tag is from database I loop the data using php
ex. 1 src: Get selected value/text from Select on change
This example is 100% working correct but what I need is not to get the value but to assign like sample below next example 2
function handleSelectChange(event) {
var selectElement = event.target;
var value = selectElement.value;
alert(value);
}
<select onchange="handleSelectChange(event)">
<option value="1">one</option>
<option value="2">two</option>
</select>
ex 2 Those function will alert or run everytime I select/Click each of them F1 or F2
<table>
<tr>
<td onclick="myFunction1()">F1</td>
<td onclick="myFunction2()">F2</td>
</tr>
</table>
<script>
// Function 1 will run when I click the F1
function myFunction1() { alert('myFunction1'); }
// Function 2 will run when I click the F2
function myFunction2() { alert('myFunction2'); }
In example 1 As you can see the first example select form html will grab the the value of option tag, right?.
Now In example number 2 it will run the function when I click each of the F1 or F2
So what I need to the program is pass a value from my database to my javaScript function and run it like in alert or example 1 but in "Select tag" HTML version
ex. 3 Here's my query
<form action="">
<select name="customers" id="myId" class="form-control">
<option value="">Select a customer:</option>
<?php
$user_id = 1;
$sql = "SELECT * FROM `myTable` WHERE user_id = '$user_id' Order by create_at DESC";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{ ?>
<!-- appsFunction('<?php echo $row['colName2']; ?>') << will be the value that should run in console.log -->
<option value="<?php echo $row['id']; ?>" onclick="appsFunction('<?php echo $row['colName2']; ?>')"><?php echo $row['colName1']; ?></option>
<?php }
} else { return false; }
?>
</select>
</form>
ex. 3 part 2 javascript
<script>
function appsFunction(passVar) {
colose.log(passVar);
}
</script>
As you can see in my first example a "Select Tag" HTML when I select dropdown it returns to me a value right?, in second example when I click F1 or F2 it will run the function then return alert, What I need here is When I select the dropdown it will accept the value I pass in function "appsFunction(passVar)" appsFunction('<?php echo $row['colName2']; ?>') from select tag which the value is from my database.. so I need help idea how to do that properly..
NOTE: The function must be run when I select the dropdown, the function must be accept the value I set which from my database it's like totally example number 2 but in Select tag HTML version not just text or html table.
Thanks in advance for solving my problem.
If you register an event handler on the select element itself that listens for change events you will be able to process the selected OPTION and access any value/property associated with it. You cannot assign an event handler directly to an OPTION element as you are trying to do here. You can add as many dataset attributes as you need to the OPTION elements however which you can easily access in the Javascript event handler.
If the value you pass into the SQL statement is to be dynamic ( from a GET or POST request most usually ) you really need to use a Prepared Statement to help mitigate SQL Injection attacks.
As your select menu is making use of only 3 columns from the mytable table you should limit the returned fields to those columns which in turns helps when using a Prepared Statement as you can easily assign the results as variables.
<form name='geronimo'>
<select name="customers" class="form-control">
<option selected hidden disabled>Select a customer:
<?php
$user_id = 1;
$sql="select `id`, `colName1`, `colName2` from `mytable` where user_id = ? order by create_at desc";
$stmt=$mysqli->prepare($sql);
$stmt->bind_param('s',$user_id);
$res=$stmt->execute();
if( $res ){
$stmt->bind_result($id,$col1,$col2);
while( $stmt->fetch() ){
printf('<option value="%s" data-col="%s">%s', $id, $col2, $col1 );
}
$stmt->free_result();
$stmt->close();
}
?>
</select>
</form>
<script>
document.forms.geronimo.customers.addEventListener('change',function(e){
let id=this.value;
let col2=this.dataset.col;
let col1=this.options[this.options.selectedIndex].text;
alert( id + ' ' + col2 + ' ' + col1 )
});
</script>

php Dropdown Realtime Update

My apologies if this has been answered before but I did do a search and haven't seen any answers for the questions asked in other posts. The answers I did see didn't relate to my question (mostly to do with dropdowns getting results from mysql).
I have a php dropdown list where you need to select a value (1, 2 or 3). Based on what you select, the list should update a variable and show a hidden div tag. Now from the information I gathered it seems like this cannot be done with php alone but requires a javscript or ajax script.
php:
<form>
<select name="options" onchange="{dosomething}">
<option value="0">[Select value]</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select><br>
</form>
This should then update this variable and div in REALTIME:
<div id="test" style="display:none">
$answer= 1 + $value
<?php
echo "1 + $value = $answer";
</div>
javascript/ajax:
<script>
function dosomething {
#update $value based on dropdown and do calculation
#unhide div with id "test"
}
</script>
I need to mention that I have no knowledge of javascript or ajax.
If you only need to view the new result in the same page without requesting something to the server add this script below your last div:
<script>
var element = document.getElementsByName('options');
if( element.length > 0 ){
element[0].addEventListener('change',update_text,false);
//element[0].addEventListener('change',function(){update_text(param)},false);
}
function update_text(evt){
console.log(evt);
var first_element = evt.target;
var selection = first_element.options[first_element.selectedIndex].value;
//do math:
selection = +selection + 1; //this cast selection as number and not as String
console.log(selection);
var test = document.getElementById('test');
test.style.display = 'block';
test.innerHTML = `<p>${selection}</p>`;
};
</script>

PHP textarea combined with select change and .load() function

I have a textarea where I will load the term respective to the value of my select. I'm loading the content to the textarea using .load("load_myinvoices_default_terms.php?id="+id). I can load the content successfully. But when I'm to type on the textarea and then change the selected option, the .load() function wont load anymore.
My hunch is that when I type on the textarea it is put on the value, while on I use the .load it is put on the html.
I just want to be able to type on the textarea and still be able to change it's value when I change the selected option.
invoice.php:
<select id="setDefaultTermSelection" name="invoice_term_id" onChange="load_myinvoices_default_terms();">
<option value="0">Set as new term</option>
<option value="1">Term 1</option>
<option value="2">Term 2</option>
</select>
<textarea id="default_terms" name="invoice_terms" placeholder="Enter your terms and conditions" rows="5"></textarea>
script:
<script type="text/javascript">
function load_myinvoices_default_terms()
{
var id = $("#setDefaultTermSelection").val();
$("#default_terms").load("load_myinvoices_default_terms.php?id="+id);
}
$("#default_terms").keyup(function(e)
{
$("#setDefaultTermSelection").val(0);
});
</script>
load_myinvoices_default_terms.php:
<?php
include ("includes/connection.php");
$id = $_REQUEST['id'];
if($id > 0)
{
$query = "SELECT * FROM terms WHERE user_id = $_SESSION[user_id] AND term_id = $id";
$selectQuery = mysqli_query($con,$query);
$row = mysqli_fetch_array($selectQuery);
echo $row['term_description'];
}
else
echo "";
?>
What's happening is that, when you set your select value programmatically like this: $("#setDefaultTermSelection").val(0);, the event change is not triggered.
onchange only triggers when the user clicks. From MDN:
The change event is fired for <input>, <select>, and <textarea>
elements when a change to the element's value is committed by the
user. Unlike the input event, the change event is not necessarily
fired for each change to an element's value.
But, you can trigger the change manually ("simulating" user click) with the jQuery's trigger() method. Something like this:
$("#setDefaultTermSelection").val("0");
$("#setDefaultTermSelection").trigger("change");
Or (one line):
$("#setDefaultTermSelection").val("0").change();
In the last example, .change() is an alias for .trigger("change")
Some points:
The value inside <option> tag is a string. So, you should set the value with .val("0");.
The event according to specification is actually onchange, and not onChange (capital "C"). However, modern browsers actually accept both ways.
I've solved the problem.
First, I've put these on my script as mrlew suggested.
$("#setDefaultTermSelection").val("0");
$("#setDefaultTermSelection").trigger("change");
then on the load_myinvoices_default_terms.php:
<?php
include ("includes/connection.php");
$id = $_REQUEST['id'];
if($id > 0)
{
$query = "SELECT * FROM terms WHERE user_id = $_SESSION[user_id] AND term_id = $id";
$selectQuery = mysqli_query($con,$query);
$row = mysqli_fetch_array($selectQuery);
$x = $row['term_description'];
json_encode($x);
}
else
echo "";
?>
<script>
var ar = <?php echo json_encode($x) ?>;
$("#default_terms").val(ar);
</script>
tho there are more efficient ways of solving this, so please let me know, thanks :)

Run Function on default HTML Select with PHP And Javascript

I try to Run Default Function on HTML Select, but Default Function doesn't works for Default Selected Value, But it Works On User Select
<?php
$status_selected = 'A002';
?>
<!-- HTML Select 1 -->
<select id="state" class="l" name="state" onchange="Func()">
<option value="A001" <?php if($status_selected == "A001") echo "selected"; ?> data_item=" , StateA003 One, A003 State Two, A003 State Three">A001</option>
<option value="A002" <?php if($status_selected == "A002") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A002</option>
<option value="A003" <?php if($status_selected == "A003") echo "selected"; ?> data_item=" , A003 State One, A003 State Two, A003 State Three">A003</option>
</select>
<!-- HTML Select 2 -->
<label for="city">Item : </label><select id="city" name="item" class="l" onchange="onSelected()">
<script>
function Func() {
var city = document.getElementById('item');
var state = document.getElementById('state');
var val=state.options[state.selectedIndex].getAttribute('data_item');
var arr=val.split(',');
item.options.length = 0;
for(i = 0; i < arr.length; i++) {
if(arr[i] != "") {
item.options[item.options.length] = new Option(arr[i],arr[i]);
}
}
}
function onSelected() {
var item = document.getElementById('item').value;
var state = document.getElementById('state').value;
console.log('Parent : ' + state+ ', Item : ' + item);
}
</script>
it load HTML Select One And then Select Item in HTML Select Two, But HTML Select Two Works Only By Manual User Select And Not Works For Default Programatically Value
Whole Of Codes Above Are On PHP File.
How i can fix it ?
Not sure if it is relevant, but maybe you want a chained select box? If not, please clarify your question, it's very hard to follow.
EDIT: So the real issue is selecting the right option by code. In that case, this is a duplicate of How do I programmatically set the value of a select box element using javascript?.
In your onload script(or just after the functions if the script is at the bottom of the page), also run Func(), then set the value for #city:
Func();
var state = document.getElementById('state'),
city = document.getElementById('city'),
selectedCity = state.getAttribute('data-selected-city');
if(selectedCity) {
city.value = selectedCity;
}
You need to store the selected city somewhere, my suggestion is to add it to the select:
<select id="state" data-selected-city="new-york">
<!--and so on--->
</select>
NOTE: setting a data attribute in HTML5 should begin with data-, not an underscore. So it's data-item="", not data_item="". That will give you a warning when running HTML validator.
Put Out Of PHP Tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
On Script Tag Put :
$(function() {
$("#state").on("change", Func());
});
After :
item.options[item.options.length] = new Option(arr[i],arr[i]);
put the code :
$(item).prop("selectedIndex",i);

js change select name based on option selection

I have a dynamic drop down menu where options are loaded from database, Now i need to change the attribute every time different option is selected from the drop down menu.
To achieve this I am trying to use js in my opinion suitable to do the job but unfortunately I find it difficult and cannot come up with a correct solution, actually i dont know how to start it.
Here is my PHP code that dynamicly generates drop down menu:
$opt = '<select id="Forex" name="" style="display: none">';
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = '';
while($result = mysqli_fetch_assoc($query)){
if($timestamp < $result['endingDate']){
$opt2 .= '<option id="'.$result['id'].'" value="'.$result['startingDate'].'">'.$result['course'].'</option>';
}
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Could some one suggest a solution a at least give me a link to a article that covers this problem
You can add "onchange" event and change the name whatever you like:
$('#Forex').change(function(){
var val = $(this).val(); // you can get the value of selected option
//you can process your conditions here
$(this).attr('name', 'your_choice_name'); // this will change the name attribute
});
or you can do this from javascript
<select id="Forex" name="abc" onchange="changeAttr(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
<script type="text/javascript">
function changeAttr(ele)
{
var val = ele.value;
var n = "";
if(val == 1){
n = 'xyz';
} else if(val == 2){
n = 'abc';
}
ele.setAttribute('name', n);
}
</script>
Hope this will help you what you want...
Use jquery, with a "onChange" event that will change the attribute you want with the selected item in the list.
jQuery get value of select onChange
Hei!
Not sure if I understood you, but you can use jQuery to manipulate attributes on change event.
For event http://api.jquery.com/change/
To change atribute http://api.jquery.com/attr/

Categories

Resources