Operation with Javascript with a variable from a form in PHP - javascript

I'm new on this site, so please don't judge me. ;)
Btw, my question is about how can i call varible(montoUti) from this form and make an operation with javascript by the moment when I select an option.
I've been reading that i can use a function called "onchange" but I'm not sure how it works.
I have this code in php that is calles FEvaluacion.php
`
<select class="col-lg-12" name="montoUti" onchange="myFunction()">
<option value="<?php echo $montoUti?>">------</option>
<?php
require("connect_db.php");
$query = $mysqli -> query ("SELECT montoUti FROM utilidad");
while ($valores = mysqli_fetch_array($query))
{
echo '<option
value="'.$valores[montoUti].'">'.$valores[montoUti].'</option>';
}
?>
</select>'
And here we have the another code in javascript called operacion.php
`<script>
function myFunction()
{
var bmontoUti = document.getElementById("montoUti").value;
if(prom>=60 && prom<=80)
{
utilidad=(prom/bmontoUti)*5;
document.formulario.utilidad.value=utilidad;
}
}
</script>'
However, I really hope you can help me.
Thanks
Regards!

to use document.getElementById("montoUti").value; you need to set an id in your <select> you are currently just setting a name try
<select class="col-lg-12" id="montoUti" name="montoUti" onchange="myFunction()">

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>

Change select option with javascript based on PHP variable

I've read multiple threads here and still can't find a good answer for my question, so I'm sorry for this silly question but there are no words for how bad I am with Javascript.
So I'm currently trying to change the select options on a 2nd select tag based on the selected option from the first one.
<select name="category" id="category">
<option value="" disabled selected value>Cat1</option>
<?php
$stmt = $conn->query("SELECT * FROM cats");
while($row = $stmt->fetch()) {
echo "<option value='".$row['name']."'>".$row['text']."</option>";
}
?>
</select>
</div>
</div>
<div class="div3">
<div class="div4">
<label for="test">cat2</label>
</div>
<div class="div7">
<select name="sub" id="sub">
<?php
$stmt = $conn->query("SELECT * FROM cats WHERE name = $cat");
while($row = $stmt->fetch()) {
echo "<option value='".$row['subname']."'>".$row['subtext']."</option>";
}
?>
</select>
</div>
So I know that I somehow need to call a JavaScript with "onchange" which will get the $cat variable and then pass back the information from the SQL table. But I have absolute no idea how I can do this..
I don't wanna use either form or Ajax. If this is possible with pure Javascript, I would be really happy..
Then of course I don't expect you to solve the entire issue for me but I would be glad if someone could point me in the right direction (Don't think too much about the prepared statements with $stmt, this is just a first test)
If you don't want to use Ajax, you need to get all data for each main category and save them all into a pieced-together JS array.
Something like
$jstext = ''; //our pieced-together array definition for JS
$stmt = $conn->query("SELECT * FROM cats");
while($row = $stmt->fetch()) {
echo "<option value='".$row['name']."'>".$row['text']."</option>";
$stmt2 = $conn->query("SELECT * FROM cats WHERE name = {$row['name']}");
$jstext .= "subcategories['".$row['name']."'] = '";
$tmp = '';
while($row2 = $stmt2->fetch()) {
$tmp .= '<option>'.$row2['name'].'</option>'; //generate html for each subcategory
}
}
$jstext .= $tmp."';\r\n"; //add subcategories to array index, add line break
Then in your <script> tag, add:
<script>
var subcategories;
<?php echo $jstext ?>
</script>
This should generate an array with an index of each main category and the content is the respective sub-categories.
Example Output:
<script>
var subcategories;
subcategories['maincat1'] = '<option>subcat1</option><option>subcat3</option>';
subcategories['maincat2'] = '<option>subcat4</option><option>subcat6</option>';
</script>
Now you just need to replace the innerHTML of your "sub" select when the "category" select fires an onchange event.

multiselect filter using javascript

I have option tag and it works fine with single filter and I want to make it multi select....following is my code:-
$('#version_no').change(function () {
var version_no = $('#version_no').val();
if (version_no != null) {
showAll(version_no);
} else {
showAll();
}
});
showAll() is a function that returns data after filtering. if no filter is selected then everything is shown.
following is the view code:-
<select multiple="multiple" style="margin-top:15px;" name="version_no" id="version_no">
<option value="">Select Version No</option>
<?php if (count($get_version_no)): ?>
<?php foreach ($get_version_no as $version): ?>
<option value=<?php echo $version->version_no; ?>><?php echo $version->version_no; ?></option>
<?php endforeach; ?>
<?php else: ?>
<?php endif; ?>
$get_version_no is generating the dropdown value like 1,1.1,1.2 etc.....
SO I want to make it multi select any help will be appreciated. I'm using codeigniter 3.
You need to make version_no array in name for multiple select
<select multiple="multiple" style="margin-top:15px;" name="version_no[]" id="version_no">
In jquery
var version_no= [];
$.each($("#version_no option:selected"), function(){
version_no.push($(this).val());
});
var version = version_no.join(", ");
version will be the string with all selected values seperated by comma
Your Javascript code just needs to be refactored so that version_no is an array instead of a single value. You can use the ':selected' selector to get the selected options.
(see https://api.jquery.com/selected-selector/)
You will also need to refactor the showAll() function so that it parses an array instead of a single value. I would also have the showAll() function perform null checks instead of doing that if...then/else.

Want to update one select block if the value selected on the other select box

As i mention on the question, i want to update one select box if another value in the another select box is selected.
for example:
<select id="makale" size="4"name="formMakale"style="height:7em;width:16em;border:0px;outline:0px;font-size:16px;padding-left:10px;" >
<?php
$authorsQuery = $hb->authors();
foreach($authorsQuery as $v){
echo '<option value="'.$v->id.'">'.$v->name.'-'.count($hb>aticlesbyauthor($v),1000).' yazi</option>';}
?>
</select>
<select id="kategoriSec" size="4" name="formCat"style="height:7em;width:16em;border:0px;outline:0px;fontsize:16px;padding-left:10px;" >
<?php
$catQuery = $hb->db->get_results("SELECT * FROM category");
foreach ($catQuery as $v) {
echo '<option value="'.$v->id.'">'.$v->name.'</option>';
}
?>
if i select something from this select box with id makale, i want to update the options of the select box with id kategorisec.
can you help me?
Thank you.
If you just want to change it on the browsers side, use the onchange event handler.
If you want to update the checkboxes based on server data, you could use ajax or simply use an iframe:
<input onclick="update(this)">
<iframe src="checkboxes.php">Oh ,update your browser</iframe>
<script>
function update(elem){
if(elem.selected){ iframe=document.getElementsByTagName("iframe")[0]
iframe.src="checkboxes.php?select="+elem.value;
}
}
</script>

Sending a different column instead of this.value in php to javascript function (Query)

I've made a select list and filled it with info from a DB. Now i'm trying to make it so whenever you select a different item in the list it calls a javascript function that checks if the selected item/entity (or whatever it's supposed to be called) has a comment or not, and reacts accordingly.
So far I have this, which does work, and only shows the paragraph if the ID of the selected item sent is over 5. However, I don't know how to send the comment that is in the query as the parameter, so that it can then check the length and react.
This is what I have so far:
// Create connection
$conn = mysql_connect("localhost", "root", "admin")
or die("Could not connect: " . mysql_error());
// Selecting the DB
mysql_select_db("tickets") or die("Could not connect: " . mysql_error());
$query = mysql_query("SELECT * FROM tickets order by ID");
$numrows = mysql_num_rows($query);
//I want to change this.value to be the selected item's comment
echo '<select name="Tick" size='.$numrows.' onChange="checkSelectedValue(this.value)">';
while ($row = mysql_fetch_array($query)) {
echo '<option value="'.$row['ID'].'">Comment: '.$row['comments'].' </option>';
}
echo '</select>';
echo '<p id="commentNotifier" style='display:none;'> Selected item has a comment. </p>';
How would I modify this so the parameter of onChange="checkSelectedValue(this.value)" would be the selected item's comment instead of this.value which is, in my case, the ID.
Note that I don't want to change the value of each option to be comments instead of ID.
This is the javascript functon that works with the ID sent, and if it is over 5 it shows the paragraph that's otherwise hidden:
<script type="text/javascript">
function checkSelectedValue(val){
var element=document.getElementById('commentNotifier');
if(val > 5) //I would change this to val.length > 0 to check if comments exists or not
element.style.display='block';
else
element.style.display='none';
}
</script>
Pretty straightforward function. Cheers in advance!
In a pure javascript solution the best answer of this stack would helps : Get selected value in dropdown list using JavaScript?
You can use this to select the comment from the dropdown:
$('#mySelect').find(":selected").text()
But it requires you to use jQuery
Working fiddle: https://jsfiddle.net/b1qjw214/
In pure javascript:
function findElem() {
var elem = document.getElementById("mySelect");
var elemTxt = elem.options[elem.selectedIndex].text;
}
Fiddle: https://jsfiddle.net/dsy3tgmy/
Use data-* attributes and instead of this.value, pass this as argument so that you can deal with element and all its attributes.
Element.dataset returns the object of all the data-* attributes of the element
Try this:
function checkSelectedValue(elem) {
console.log('Value: ' + elem.value);
console.log('Comment: ' + elem.options[elem.selectedIndex].dataset.comment);
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<select onChange="checkSelectedValue(this)">
<option data-comment='Comment goes here' value="volvo">Volvo</option>
<option data-comment='Comment goes here' value="saab">Saab</option>
<option data-comment='Comment goes here' value="mercedes">Mercedes</option>
<option data-comment='Comment goes here' value="audi">Audi</option>
</select>

Categories

Resources