Javascript Get value from select boxes in loop - javascript

I have the following:
while($round < $counter)
<select name="picks[]" id="winner">';
echo'<option value="'.$row['team1'].'">'.$team1.'</option>';
echo'<option value="'.$row['team2'].'">'.$team2.'</option>';
echo'</select>';
echo'BY';
echo'<select name="score[]" id="score>';
echo'<option value="1">1</option>';
echo'<option value="2">2</option>';
echo'<option value="3">3</option>';
echo'<option value="4">4</option>';
echo'<option value="5">5</option>';
echo'<option value="6">6</option>';
echo'<option value="7">7</option>';
echo'<option value="8">8</option>';
echo'<option value="9">9</option>';
echo'<option value="10">10</option>';
Which along with some other code produces this
I would like to get the value of each select box score and selected team to display in a div at the bottom of the page before user clicks submit
I have managed to achieve this result:
using the code below but it only works with 1 team
function disp(){
var winner = document.getElementById("winner").value;
var score = document.getElementById("score").value;
document.getElementById("pickedDiv").style.cssText='background:#f0f0f0;width:60%; height:200px; border:thin solid black; border-raduis:10px;';
document.getElementById("picked").innerHTML="You are selecting: "+winner+" to win by "+score;
}
If someone could please give me some advise how I can modify the script above to get all selected teams and points to disp in div

First, get a select element of your choice:
var element = document.getElementById("winner");
For the text of the selected option, you need to use:
var option_text = element.options[element.selectedIndex].text;
And for its value:
var option_value = element.options[element.selectedIndex].value;
HOW TO IMPLEMENT:
In your case, assuming each winner and score have a unique id:
We will use the counter $i to achieve this
Be sure to define the $max variable to the number of times you want to loop
for ($i = 0; $i < $max; $i++)
{
// here we concatenate the counter to the id of the select element
// the first winner in the loop will have id winner0, the second winner1,
// and so on
echo '<select name="picks[]" id="winner' . $i . '">';
echo '<option value="'.$row['team1'].'">'.$team1.'</option>';
echo '<option value="'.$row['team2'].'">'.$team2.'</option>';
echo '</select>';
echo 'BY';
// here we concatenate the counter to the id of the select element
// the first score in the loop will have id score0, the second score1,
// and so on
echo '<select name="score[]" id="score' . $i . '">';
echo '<option value="1">1</option>';
echo '<option value="2">2</option>';
echo '<option value="3">3</option>';
echo '<option value="4">4</option>';
echo '<option value="5">5</option>';
echo '<option value="6">6</option>';
echo '<option value="7">7</option>';
echo '<option value="8">8</option>';
echo '<option value="9">9</option>';
echo '<option value="10">10</option>';
echo '</select>'
}
Our server-side code is ready. Now, lets get back to our client-side code.
We need a way to get all the elements that we generated previously.
We are going to need a loop:
for (var i = 0;;i++)
{
// note that our for doesn't have an exit condition.
// it will loop forever. we need a way to find out
// which is the last element, and break the loop
var winner = document.getElementById("winner" + i);
var score = document.getElementById("score" + i);
// if the element is not found, break the loop
if (winner == null || score == null)
{
break;
}
// get the text of the selected option
var winner_text = winner.options[winner.selectedIndex].text;
// get the value of the selected option
var winner_value = winner.options[winner.selectedIndex].value;
// here, you are ready to do whatever you please with the variables
// winner_text and winner_value
// now, lets get the score text and value
var score_text = score.options[score.selectedIndex].text;
var score_value = score.options[score.selectedIndex].value;
}

Related

Can i pass array to an HTML? Creating a dynamic html table with php/javascript

I have created a table with 3 columns and rows with the size of an array pulled from the database. I have got the value but I want to create a button inside the cells with the name from pname and when you click that button it will take you to the value of plink. I tried using <input type="button" value=" " onclick="window.open( )", but it doesn't seem to pass the arrays. I am sure there is an easier/ better way to do it with JavaScript, but I am not familiar with JavaScript. Please help me out. Here is my code.
I want the format 3 columns and infinite rows(based on the data).
<!DOCTYPE html>
$pname = array();
$plink = array();
$results = $wpdb->get_results("SELECT name, link FROM `wptable`);
if(!empty($results)) {
foreach($results as $row){
$pname[] = $row->name;
$plink[] = $row->link;
}
}
$num = 0;
echo "<table class='table'>";
echo "<tbody>";
echo "<br><br>";
$quant_row = count($pname)/3;
$quant_col = 3;
for ($count_row = 0; $count_row < $quant_row; $count_row++)
{
echo "<tr>";
for ($count_col = 0; $count_col < $quant_col; $count_col++)
{
echo "<td>";
echo $plink[$num];
echo "</td>";
$num++;
}
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
You just need to echo a button inside an anchor:
echo '<button type="button">' . $pname[$num] . '</button>';
try this.
echo "<td>";
echo "<button onclick=\"Document.getElementById('link$num').display=state$num? 'none' :'block';state$num=!state$num; \">". $pname[$num] ."</button><div id='link$num'>". $plink[$num]."<div>";
echo "";
when you click on $pname , you show the $plink. reclick and hide the content

How can i add selected=selected to save my dropdown if there is an error in my form?

I have two php files one is a class my_class
has a function in it called dropit()
this function looks like
#res = DataBase::database("select id, name,image from product");
echo "<option value="0">Select one</option>";
if($res){
foreach($res as $value){
echo "<option value='{$value[id]}' data-image='{$value['image']}'>{$value['name']} -- {$value['id']}</option>"
}
}
echo "</select>"
then in my index php i have a drop down that is populated using
<?php my_class::dropit(); ?>
if there is a error in my form i would like the dropdown to stay on the selected item
You can check if your select value is in $_POST and while in your foreach() loop check to see if it matches the current value.
#res = DataBase::database("select id, name,image from product");
echo "<option value="0">Select one</option>";
if($res){
foreach($res as $value){
$selected = isset($_POST['nameofyourselect']) && $_POST['nameofyourselect'] == $value[id]) ? " selected='selected'" : "";
echo "<option value='{$value[id]}' data-image='{$value['image']}'{$selected}>{$value['name']} -- {$value['id']}</option>"
}
}
echo "</select>"

PHP: Two <select>, first one allready fill, the second one I want to fill with values

I am have this issue:
<fieldset>
<?php
echo form_open('rssFeedReader/addSource');
echo '<h2><small>(*) Select in which category you want to add a new Rss Source </small><h2>';
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="category" id="category">';
foreach( $categories as $row )
{
// here i have some values from my database
echo '<option value="'.$row->id.'">' . $row->category_name . '</option>';
}
echo '</select>';
echo '</div>';
// NOW, HERE I WANT TO PUT ANOTHER <SELECT>
echo '<div class="form-group">';
echo '<select class="form-control input-lg" name="anotherID" id="anotherID">';
foreach( $array as $r)
{
// here i have some values from my database
echo '<option value="'.$r->something.'">' . $r->something_else. '</option>';
}
echo '</select>';
echo '</div>';
echo '<div class="form-group">';
echo form_submit(array('class' => 'btn btn-primary btn-lg btn-block', 'id' => 'remove_source', 'name' => 'remove_source', 'value' => 'Remove Source'));
echo '</div>';
?>
<?php echo validation_errors('<p class="error">'); ?>
Now, what I want to do.
The second select list is empty initially.
I want to fill it with values depending of what is chose in first select list.
How can I do that? To fill the second select list only if something is selected in first select list.
MrCode has a nice example for you.
Using Ajax To Populate A Select Box
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#category').on('change', function (){
$.getJSON('select.php', function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['name'] + '</option>';
}
$('#anotherID').html(options);
});
});
});
</script>
Your select.php should json_encode() the data which you want to fill your select with
The best way to handle this would be to populate the list after you made a change on the first list. For example.
$("#category").on("change", function(){
var selectedValue = $(this).val();
$.get("some.php?value=" + selectedValue, function(response){
var options = "";
for(var i = 0; i < response.length;i++){
var val = response[i];
options += "<option value='" + response[i].id + "'>" + response[i].name + "</option>";
}
$("#anotherID").empty().append(options);
});
}
I had to make several assumptions. for example your some.php will take a value parameter. The return is json array [{id:1, name:"option 1"}, {id:2, name:"option 2"}]. Please keep this in mind.

Javascript - calculating the remaining between two related fields

First of all, I would like to calculate the remaining QTY (quantity) between two fields in a form; in other words I have the actual QTY input text field as a read-only where its value is obtained from mysql table AND there is the user QTY input text field is taken from the user input. All I want is to decrement the actual QTY based on what the user input in the user QTY.
I have the following code as follows :
$query2 = "SELECT * from store_00";
$result2 = mysql_query($query2);
$n = array();
while($row2 = mysql_fetch_assoc($result2)){
echo "<td align=center>".$row2['item_no']."</td><td align=center>";
?>
<input type="text" id="fname" value="<?php echo $row2['qty'] ?>" readonly="readonly"/>
<?php
echo "</td>";
for($i=0;$i<$num;$i++){
echo "<td align=center>"; ?><input autofocus="autofocus" onchange="myFunction(this.value);" type="text" name="n[]" value=""/><?php echo "</td>";
}
echo "</tr>";
}
And the Javascript code :
function myFunction(v)
{
var x=document.getElementById("fname");
x.value = x.value - v;
}
The above will output in the actual QTY correctly for the first time, but when user changes the value back to 0 , it will decrements from the new actual QTY value which gives a false remaining...So there must be a way to have a temporary actual QTY value saved somewhere.
Anyways I know the code looks awful, I'm still new to JS and not sure how to just create a simple relation and remaining calculation between two fields.
As you don't use jQuery and your question is about javascript, i've changed some things to do what you want easily. Also, the id should be unique while classes don't need to be unique. As you have ids with the same values that creates a problem, also as you stated, you don't store your original value, and this is your main problem. There are many methods for this but i prefer this as it's easy to understand i guess.
$n = array();
echo "<table>";
while($row2 = mysql_fetch_assoc($result2)){
echo "<tr class='inputs'>";
echo "<td align=center> ".$row2['item_no']." </td><td align=center>";
echo "<input class='original' type='text' id='c".$row2['item_no']."' value='".$row2['qty']."' readonly='readonly'/>";
echo "</td>";
for($i=0;$i<$num;$i++){
echo "<td align=center>";
echo "<input class='d".$row2['item_no']."' data-goto='c".$row2['item_no']."' data-original = '".$row2['qty']."' autofocus='autofocus' onchange='myFunction(this);' type='text' name='n[]' value='0'/>";
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
With the html5, you can define custom tags with the data- prefix, and you can reach them with getAttribute method for that object.
<script>
function myFunction(v){
var minus = 0;
var mutualInputs = document.getElementsByClassName(v.className);
for (var i = 0; i < mutualInputs.length; ++i) {
var item = mutualInputs[i];
minus = minus + parseInt(item.value);
}
var original = v.getAttribute('data-original');
var x = document.getElementById(v.getAttribute('data-goto'));
x.value = original - minus;
}
</script>
ps: your item_no's must be unique in this example.

JavaScript dropdown menu does not work in IE8

I'm using an on change for a drop down menu to display information once a choice is chosen from the dropdown. This works fine in Firefox and Chrome but I have been hoodwinked into having to use ie8 and this on change does not seem to fire. Any help would be much appreciated. Its a mix of php and html the lower part is js which outputs info when chosen.
echo "<p><h2> To View a Route: </h2><br> Pick a routes name from the list and all its information can be viewed below the selection box.</p>";
echo "<p><FORM METHOD=\"post\" ACTION=\"controller.php\">";
echo "<select class=\"toggle-data\" name='selectallrouteinfo'>";
echo "<option value=\"\">Choose a Route </option>";
for ($i = 0; $i < sizeof($list1); $i++) { //going through each element of array and outputting route
if (is_string($list1)) {
echo "<option value=\"\" data-toggle = \"$id1\" >$list1</option>";
} else {
$space = " ";
$id = $list4[$i];
$id1 = "#" . $list4[$i];
echo "<option data-toggle = \"$id1\" value=\"$id\">" . $list1[$i] . $space . $id . "</option>";
$idHolder[$i] = $id; //array for holding ids so that it passing the correct id to my loops below
}
}
echo "</select></form></p>";
for ($k = 0; $k < sizeof($idHolder); $k++) { //my outer loop is going through the ids, fitting correct id to the div and dbm obj
echo "<div id=\"$idHolder[$k]\" style=\"display: none;\">
";
$allRouteInfo = $DBM1->getAllRouteData($idHolder[$k]);
for ($j = 0; $j < sizeof($allRouteInfo); $j++) { // my inner loop is going through each element of array and outpting all route info
if (is_string($allRouteInfo)) {
echo $allRouteInfo; //if theres no info, there is no array, it has returned a string
} else {
echo $allRouteInfo[$j]; //if there is arry, happy days
}
}
echo "</div>";
//below is a js/jquery script for outputting my choice in the select of route info
echo " <script>$('.toggle-data').on('change', function() { //jquery for printing my valuable info on change
var toggle = this.options[this.selectedIndex].getAttribute('data-toggle'),
toggle_class = 'unique_classname';
$('.'+toggle_class+', '+toggle).toggle().removeClass(toggle_class);
$(toggle).addClass(toggle_class);
}); </script>";
echo " </div>";

Categories