Javascript and multiple select values - javascript

I have a form with 2 <select>, select1 allows simple selection and select 2 allows multiple selection. What I want is, when the user select something in select1, associated data in select2 should be selected according to my array of data.
function selectIt() {
var divArray = new Array();
// this is the value for first element on select1
divArray[0] = 3;
// these are the corresponding values on select2 that should be selected
divArray[0] = new Array();
divArray[0][0] = 5;
divArray[0][1] = 1;
divArray[0][2] = 2;
// and so on
divArray[1] = 2;
divArray[1] = new Array();
divArray[1][0] = 6;
divArray[1][1] = 3;
divArray[1][2] = 2;
var select2 = document.getElementById("secondSelect");
for (var i=0; i < select2.options.length; i++)
select2.options[i].selected = false;
}
So if the user selects index 1, in select2 items 2,3 and 6 should be selected.
First I deselect previously selected items using:
var select2 = document.getElementById("secondSelect");
for (var i=0; i < select2.options.length; i++)
select2.options[i].selected = false;
After that, I do not know what to do.
some loop here
select2.options[i].selected = true;
Any help will be greatly apreciated!!!!

You can declare arrays in this way:
divArray[0] = [5, 1, 2];
I will just try to answer by writing it without testing so bare in mind it can have some errors:
document.getElementById("firstSelect").onchange = function() {
var optionIndex = this.selectedIndex; // in this function 'this' is select element
var optionsToSelect = divArray[optionIndex];
var select2 = document.getElementById("secondSelect");
for (var i = 0; i < optionsToSelect.length; i++){
select2.options[optionsToSelect[i]].selected = true;
}
};

Becuase I need some database data I combined some PHP code inside the JS:
<script type="text/javascript">
function selectM() {
var divArray = new Array();
<?
if ($result = $database->getDivs()){
$cont = 0;
while ($divs = mysql_fetch_array($result)) {
$da = "divArray[".$divs['iddiv']."]";
if ($resultEd = $database->getEdic($divs['iddiv'])){
if ($cont == 0) $da .= " = [";
$tot = mysql_num_rows($resultEd);
while ($divEd = mysql_fetch_array($resultEd)) {
$da .= $divEd['ed_id']." ";
$cont++;
if ($cont < $tot) $da .= ", ";
}
}
$da .= "]; ";
$cont = 0;
echo $da;
}
}
?>
var largo, valor;
var inexE = document.getElementById("idDiv").value ;
var ediciones = document.getElementById("ediciones");
if (inexE > 0) {
var toSelect = divArray[inexE];
for (var i=0; i < ediciones.options.length; i++) {
ediciones.options[i].selected = false;
valor = ediciones.options[i].value;
largo = toSelect.length;
for(var j = 0; j < largo; j++) {
if(toSelect[j] == valor)
ediciones.options[i].selected = true;
}
}
} else {
for (var i=0; i < ediciones.options.length; i++)
ediciones.options[i].selected = false;
}
}
</script>
Works perfect!
Thank you for pointing me in the right direction!!!

Related

nested for loop breaks parent loop

function next() {
document.getElementById('config').setAttribute("hidden","true");
document.getElementById('formdiv').removeAttribute("hidden");
mixer();
}
function mixer() {
var x = 0;
for (var i = 0; i < parseInt(document.getElementById('nm').value); i++) {
var title = document.createElement("P");
title.style = "font-family:verdana;font-size:18px;";
title.id = "p"+String(i);
document.getElementById("myForm").appendChild(title);
document.getElementById("p"+String(i)).innerText = "Enter the amount of mixer number "+String(i+1);
var mixers = document.createElement("INPUT");
mixers.type = "text";
mixers.id = "m"+String(i);
mixers.size = '1';
document.getElementById("myForm").appendChild(mixers);
var options = ['Select a unit','ml','L','UK Pints','US Pints'];
var dropdown = document.createElement("SELECT");
dropdown.id = "s"+String(x);
document.getElementById("myForm").appendChild(dropdown);
/*for (j = 0; i < options.length; j++) {
var optiontag = document.createElement("OPTION");
optiontag.value = options[j];
optiontag.innerText = options[j];
document.getElementById("s"+String(x)).appendChild(optiontag);
}*/
x += 1;
}
}
this function creates the output when passed mn = 3
https://imgur.com/Hhv6fVE
when i un-comment the nested loop at the bottom, it outputs this
https://imgur.com/80juxgX
it should output the same as the first image but with the options for the
dropdown menus

PHP Won't Post Table of Values

I have a table of values in HTML that I want to post. It looks like this:
After the user selects all of the relevant teams, I want to save it into a form, combining all the rows into a form like this:
PHP:
$numRows = 1;
$startMatchNum = 1;
if(isset($_GET['num'])) {
$numRows = $_GET["num"];
$startMatchNum = $_GET["start"];
}
JavaScript:
function getSelectionValue(rowNum, columnNum) {
document.cookie = "rowNum=" + rowNum;
//FOR EXTERNAL PHP FILE
//window.location = "http://example.com/file.php";
var id =
<?php
$index = 0;
$row = 0;
if ( ! empty( $_COOKIE['rowNum'] ) ) {
$row = $_COOKIE['rowNum'];
}
echo '"'.$values[$index].$row.'"';
?>;
var e = document.getElementById(id);
var selectedValue = e.options[e.selectedIndex].value;
}
function postRefreshPage() {
var theForm, newInput1, newInput2, newInput3, newInput4, newInput5, newInput6;
var rows = <?php echo $numRows; ?>;
var nums1 = new Array(rows);
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'addMatch.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'blue1Team';
newInput1.value = "";
for(var i = 0;i < rows;i++) {
newInput1.value += getSelectionValue(i, 0);
if((i + 1) != rows) {
newInput1.value += "|";
}
}
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'blue2Team';
newInput2.value = "";
for(var i = 0;i < rows;i++) {
newInput2.value += getSelectionValue(i, 1);
if((i + 1) != rows) {
newInput2.value += "|";
}
}
newInput3 = document.createElement('input');
newInput3.type = 'hidden';
newInput3.name = 'blue3Team';
newInput3.value = "";
for(var i = 0;i < rows;i++) {
newInput3.value += getSelectionValue(i, 2);
if((i + 1) != rows) {
newInput3.value += "|";
}
}
newInput4 = document.createElement('input');
newInput4.type = 'hidden';
newInput4.name = 'red1Team';
newInput4.value = "";
for(var i = 0;i < rows;i++) {
newInput4.value += getSelectionValue(i, 3);
if((i + 1) != rows) {
newInput4.value += "|";
}
}
newInput5 = document.createElement('input');
newInput5.type = 'hidden';
newInput5.name = 'red2Team';
newInput5.value = "";
for(var i = 0;i < rows;i++) {
newInput5.value += getSelectionValue(i, 4);
if((i + 1) != rows) {
newInput5.value += "|";
}
}
newInput6 = document.createElement('input');
newInput6.type = 'hidden';
newInput6.name = 'red3Team';
newInput6.value = "";
for(var i = 0;i < rows;i++) {
newInput6.value += getSelectionValue(i, 5);
if((i + 1) != rows) {
newInput6.value += "|";
}
}
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
theForm.appendChild(newInput3);
theForm.appendChild(newInput4);
theForm.appendChild(newInput5);
theForm.appendChild(newInput6);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
location.reload();
}
Then, after it refreshes, it runs this PHP code:
if($_POST) {
$blueTeam1 = explode ("|", $_POST['blueTeam1']);
$blueTeam2 = explode ("|", $_POST['blueTeam2']);
$blueTeam3 = explode ("|", $_POST['blueTeam3']);
$redTeam1 = explode ("|", $_POST['redTeam1']);
$redTeam2 = explode ("|", $_POST['redTeam2']);
$redTeam3 = explode ("|", $_POST['redTeam3']);
for($i = 0;i < $numRows;$i++) {
$matchNumber = $i + 1;
$query = "INSERT INTO match_info (matchNumber, blueTeam1, blueTeam2, blueTeam3, redTeam1, redTeam2, redTeam3)
VALUES ('$matchNumber','$blueTeam1[$i]','$blueTeam2[$i]','$blueTeam3[$i]','$redTeam1[$i]','$redTeam2[$i]','$redTeam3[$i]')";
$mysqli->query($query);
}
}
However, it doesn't seem to be submitting. Any help is greatly appreciated!
EDIT: I found the error, but I don't know how to fix it. In the Javascript code, the getSelectionValue function returns undefined, but I'm not sure why.
You can try to remove
location.reload();
in getSelectionValue() function, because you submit but in the same time you reload the initial script.
I figured it out. It was a variety of issues. First of all, the IDs in my PHP code didn't match the IDs in the JavaScript table. Secondly, my use of cookies to pass JavaScript variables to PHP didn't work, so I copied the PHP array I wanted to access and set it again in JavaScript. So, the function getSelectionValue(rowNum, columnNum); doesn't need to access the PHP code. Lastly, my table in the database didn't have the matchNumber column in it, so the whole process failed.
Thanks to all those that helped!

compare a select option value and a value from URL

I have a select tag to choose categories, each option contain the category number as value.
The category number is in the URL string.
I'm trying to write a JS to check if the option value is the same as the category number in the URL and if so make the option selected. so far the script dosnot work.
What am I doing wrong?
here is the code:
function GetUrlValue(VarSearch){
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for(var i = 0; i < VariableArray.length; i++){
var KeyValuePair = VariableArray[i].split('=');
if(KeyValuePair[0] === VarSearch){
return KeyValuePair[1];
}
}
}
function compareValue(){
var x = document.getElementById("selectcategory").length;
for (var i = 0; i < x; i++){
var categNo = document.getElementById("selectcategory").options[i];
var UrlValue1 = GetUrlValue('icid');
if (categNo === UrlValue) {
document.getElementById("selectcategory").options[i].selected = true;
}
alert(UrlValue1);
}
}
if needed, I will send a link to the work.
if doing that with jquery is easier, i will be happey to learn.
thanx.
The problem is that categNo should be the value of the corresponding option tag. Also it's better to cache select element and not requery DOM in the loop:
function compareValue() {
var select = document.getElementById("selectcategory");
var x = select.options.length;
for (var i = 0; i < x; i++) {
var categNo = document.getElementById("selectcategory").options[i].value;
var UrlValue = GetUrlValue('icid');
if (categNo === UrlValue) {
select.options[i].selected = true;
}
}
}
Demo: http://jsfiddle.net/dj7c6sdL/

How do I reverse results of a table row with Javascript from PHP

I'd like to be able to reverse the results of a table returned from a PHP database with javascript, but can't seem to figure out how to get the reverse(); method to work. I'd appreciate any help you could give me.
This is my Javascript:
function title()
{
var sortedOn = 0;
var display = document.getElementById("table");
var list = new Array();
var tableLength = display.rows.length;
for(var i = 1; i < tableLength; i++){
var row = display.rows[i];
var info = row.cells[0].textContent;
list.push([info,row]);
}
list.sort();
var listLength = list.length;
for(var i = 0; i < listLength; i++) {
display.appendChild(list[i][1]);
}
This is in my html table:
<th>Title</th>
function reverse(){
var display = document.getElementById("table");
var length = display.rows.length;
for(var i = 0; i < length; i++)
{
display.appendChild(
display.removeChild(display.rows[length - i - 1])
);
}
}
Here's the fiddle

how to get checkbox from multiple cells in html table?

I have dynamic html table and every cell have one checkbox. I want to get the selected checkbox if the user select from multiple checkbox from different row.
function GetAllChecked() {
var chkedshid = new Array();
var rows = new Array();
rows = document.getElementById("Tbl_Id").getElementsByTagName("tr");
trcount = rows.length;
for (var i = 0; i < rows.length; i++) {
trid = rows[i].id;
chkedshid = chkedshid + chkedshid
if (inputList = document.getElementById(trid).getElementsByTagName("input")) {
for (var n = 0; n < inputList.length; n++) {
if (inputList[n].type == "checkbox") {
if (inputList[n].checked == true) {
chkedshid[n] = inputList[n].id;
}
}
}
}
}
document.getElementById('Hidden_CellSelected').value = chkedshid.join();
document.getElementById("BtnSav2Cart").click();
}
why why this function return just last selected checkbox for last row in loop????
i need the all selected checkbox for all rows!!!!!!!
Assuming you are using jQuery.
Then you can simply do -
$("#myTableId input:checked")
If your checkbox have specific class then you can also do -
$("#myTableId .specificCheckboxClass:checked")
On some Button click try to execute this code
var checkedTransactions = $("input:[name='idofcheckboxe']:checked").map(function () {
return $(this).val();
}).get();
var will return all id of check boxes which are selected
thanks all i solve the problem:
function GetAllChecked() {
var chkedshid = new Array();
var rows = new Array();
rows = document.getElementById("Tbl_Id").getElementsByTagName("tr");
trcount = rows.length;
var totlchk = new Array();
for (var i = 0; i < rows.length; i++) {
trid = rows[i].id;
if (inputList = document.getElementById(trid).getElementsByTagName("input")) {
for (var n = 0; n < inputList.length; n++) {
if (inputList[n].type == "checkbox") {
if (inputList[n].checked == true) {
chkedshid[n] = inputList[n].id;
}
}
}
totlchk = totlchk.concat(chkedshid.join());
}
}
document.getElementById('myHiddenfield').value = totlchk.join();
document.getElementById("BtnSav2Cart").click();
}
var table = document.getElementById("mytable");
checkbox = table.getElementsByTagName("input");
for(var indexCheckbox = 1; indexCheckbox<checkbox.length; indexCheckbox++){
if(checkbox[indexCheckbox].checked){
//do something
}
}

Categories

Resources