Checking if selected option is unique - javascript

I'm working on school project and I have a problem with validating select boxes. It's very simple trip planner and let's say that I have 3 places that user visited and now he has the option to determine the order of visits. For example: [1]cinema, [3]concert,[2]shopping mall. The select boxes are generated automatically by PHP. How can I write universal jQuery script that validates the select boxes that each of them is unique?
Here is PHP code that generates the select fields;
$title = $_GET['title'];
$elements = count($_GET['eventid']);
echo "<h5>Order your trip</h5>";
foreach($_GET['eventid'] as $index => $id)
{
echo"<strong>" .$title[$index] . "</strong><select name='".$id."'>";
for($i=1;$i<=$elements;$i++){
echo"<option value='". $i ."'>". $i ."</option>";
}
echo"</select><br><br>";
}
Now I would like to validate select boxes no matter how many events there are. I came up with this code. It works but can it be done easier?
$('#validate').click(function() {
var selectValues = new Array();
$('select.order').each(function() {
selectValues.push($(this).val());
});
var elements = selectValues.length;
var i;
for (i = 0; i < elements - 1; i++) {
if (selectValues[i] == selectValues[i + 1]) {
alert('error');
}
}
});

Related

How to input array from php into javascript function and display the output using HTML?

I am trying to take the values from the array in PHP, and pass them onto the JavaScript function. The code below functions as intended. The values are taken from a MySQL database and entered into their respective arrays. [Disclaimer: New to coding]
echo "<div id='demo'></div>";
$sql = mysqli_query($conn, "SELECT DISTINCT Safepoint_name,Latitude,Longitude FROM safepoints");
while($row = mysqli_fetch_array($sql)) {
$latl[] = $row['Latitude'];
$long[] = $row['Longitude'];}
foreach($latl as $name) {
echo "$name";
}
foreach($long as $name) {
echo "$name";
}
The problem I am having is with code as shown below. It does not process and show the output as desired. I want the output to be shown one after the other after subtracting the two arrays. I would prefer if the output could be designed via HTML. What am I supposed to do?
[Note: The function is just a trial function just for checking whether it works]
<p id="demo"></p>
<button onclick = "myFunction()">Submit</button>
<script type="text/JavaScript">
let text = "";
function myFunction() {
var latitute = <?php echo json_encode($latl); ?>;
var loni = <?php echo json_encode($long); ?>;
for (let i = 0; i < latitute.length; i++)
{
var x[i] = latitute[i]-loni[i];
text += x[i]+"<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
I think your problem here is that you are defining variable x in a cycle (first warning something is fishy) and you are assigning a value into it's array index at the same time (which is technically possible, but not recommendable, in PHP, but definitely not in JS where is causes syntax error).
You can skip the variable completely and just generate the text.
for (let i = 0; i < latitute.length; i++) {
text += (latitute[i]-loni[i]) +"<br>";
}
Or if you need to keep the result array for later, you should define it as an array before the cycle:
var x = [];
for (let i = 0; i < latitute.length; i++) {
x[i] = latitute[i]-loni[i];
text += x[i]+"<br>";
}
Update:
<p id="demo"></p>
<button onclick = "myFunction()">Submit</button>
<script type="text/JavaScript">
console.log('Preparing JS...');
let text = "";
function myFunction() {
console.log('Calculating demo...');
var latitute = [9,8,7];
var loni = [1,2,3];
for (let i = 0; i < latitute.length; i++) {
text += (latitute[i] - loni[i]) + "<br>";
}
document.getElementById("demo").innerHTML = text;
alert('Demo OK');
}
</script>
JS runs OK after submit.
Right-Click your page and use "View page source file" to check what PHP generates into the JS - if it's really valid array as in the example above.
Then open Debugger (press F12 in browser) and see Console if there are any Syntax or other errors.
If you are in doubt if JS is running, you can add console.log() and/or alert() into your code (see the example).

How to display data value in real time depending on the other column with AJAX/PHP/JAVASCRIPT?

I'm currently trying to do a survey system. I have a dynamic dropdown that displays one column 'questiontitle' from my table database. Here's my code of displaying the 'questiontitle' in the dropdown.
<?php
$query=mysqli_query($con, "SELECT * FROM question");
while($row=mysqli_fetch_array($query))
{
?>
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
<?php
}
?>
echo "</select>";
And here's my database table.
My main question is how do I display the 'Option_1 to Option_10 columns' depending on the 'answer_type' column when a data is clicked from the dropdown in real time without refreshing the page? Like if the 'answer_type' is checkbox, it will display the option1-10 as checkbox and if it's radiobutton, it will display the option1-10 as radiobuttons.
There is a lot work to be done to achieve what you want to do. But I can give you a small snippet which you can use to start.
What you still have to do is
Show a page with all questions in the select box. This is done in PHP
checking how ajax works. Expand the showQuestion() function with ajax functionality so your question & answer data is retrieved from the server. this is a good read. When you got your answer, call the appropriate function to display your question and answers. OR store all your information locally...
add a button so that you can send the answers to the server. Listen to the click event and send data (small modifications are required to what I have wrote though) to the server (read the link that I have shown in point 2)
// question object
var questions = {
json1: {
questiontitle: 'How frequently ...',
answertype: 'radiobutton',
options: ['Heavy user', 'serious user', 'regular user', 'light user']
},
json2: {
questiontitle: 'What part of the day...',
answertype: 'checkbox',
options: ['Morning', 'Afternoon', 'Early evening', 'lat evening']
},
json3: {
questiontitle: 'To what extend does the ...',
answertype: 'radiobutton',
options: ['1-5 times', '6-10 times', '> 10 times']
}
};
// function that adds the "questions" input elements to the container
function insertToQuestionBox(els) {
var box = document.getElementById('questionBox');
// cleanup box
while(box.firstChild) box.removeChild(box.firstChild);
// populate with els
for(var i = 0; i < els.length; ++i) box.appendChild(els[i]);
}
// creates the input element based on args
function createInput(type, name, text) {
var i = document.createElement('input');
i.type = type;
i.name = name;
var l = document.createElement('label');
l.textContent = text;
var s = document.createElement('section');
s.appendChild(l);
s.appendChild(i);
return s;
}
// create element with question in it
function createQuestionEl(question) {
var s = document.createElement('span');
s.textContent = question;
return s;
}
// function that is called if the question is of type radio
function handleRadioButtons(data) {
var inputs = [];
inputs.push(createQuestionEl(data.questiontitle));
for(var i = 0; i < data.options.length; ++i) {
inputs.push(createInput('radio', 'rraaddioo', data.options[i]));
}
insertToQuestionBox(inputs);
}
// create checkboxes
function handleCheckboxes(data) {
var inputs = [];
inputs.push(createQuestionEl(data.questiontitle));
for(var i = 0; i < data.options.length; ++i){
inputs.push(createInput('checkbox', 'nana' + i, data.options[i]));
}
insertToQuestionBox(inputs);
}
// gets called each time the drop down has changed
function showQuestion() {
var data = questions[this.value];
switch(data.answertype) {
case 'radiobutton': handleRadioButtons(data); break;
case 'checkbox': handleCheckboxes(data); break;
// todo when default? error ?
}
}
// listen to select changes
document.getElementById('showQuestion').addEventListener('change', showQuestion);
<select id="showQuestion">
<option>please choose</option>
<option value="json1">show json1</option>
<option value="json2">show json2</option>
<option value="json3">show json3</option>
</select>
<div id="questionBox"></div>
On select box change event pass questionid to server side and query your database for answer_type and options and in that method add a condition
$options = '';
if(anwsertype=='radio') {
$options .= <input type="radio" /> Your option
} else {
$options .= <input type="checkbox" />Your option
}
The above condition should be in a loop for each option.

two dependent dropdowns php arrays

I'm trying to substitute the code that uses javascript and arrays which are visible in source code.
I want to be able to create this with php arrays, or use AJAX and have it stored in another file. I don't know how to make the proper php commands or arrays
var cars= new Array();
cars["OTHER"] = new Array("Heavy Machinery","Semi-Truck","Pickup Truck","Sedan","SUV","Misc");
cars["ATV"] = new Array("small","large");
cars["Boat"] = new Array("Under 20 Feet","Over 20 Feet");
cars["Motorcycle"] = new Array("250CC","500CC","700CC","900+");
cars["RV"] = new Array("Under 25 Feet","Over 25 Feet","5th Wheel");
cars["AC"] = new Array("Cobra");
cars["Acura"] = new Array("1.6 EL","1.7 EL","2.3 CL","2.5 TL","3.0 CL","3.2 TL","3.5 RL","CL","CSX","EL","ILX","Integra","Legend","MDX","NSX","NSX-T","RDX","RL","RSX","SLX","TL","TSX","Vigor","ZDX");
cars["Alfa Romeo"] = new Array("145","146","147","155","156","159","164","166","33","75","308","1900","2600","4C","6C","8C","Alfasud","Alfetta","Berlina","Bimotore","Canguro","Corsa","Disco Volante","Duetto","G1","GT","GTV","GTV-6","GTV6","Giulia","Guiletta","GP","Grand Prix","GTA","Iguana","Junior Z","Milano","Montreal","Navajo","P1","P2","P3","Quadrifoglio","RL","RM","Scarabeo","Spider","Sports Car","Sportwagon","Stradle","Tipo","Torpedo");
........................ALL OTHER MAKES AND MODELS ARE IN BETWEEN........................
cars["Yugo"] = new Array("55","Cabrio","GV");
jQuery(document).ready(function($){
$('span.text select').change(function(){
$(this).siblings('.value').text($(this).find('option[value="'+$(this).val()+'"]').text());
});
for ( make in cars )
{
$('#formmake').append('<option value="'+make+'">'+make+'</option>');
}
$('#formmake').change(function(){
var val = $(this).val();
$('#formmodel').html('<option value="">Select Model</option>');
for ( i in cars[val] )
{
$('#formmodel').append('<option value="'+cars[val][i]+'">'+cars[val][i]+'</option>');
}
$('#formmodel').append('<option value="Other">- Other -</option>');
});
$('#formmake, span.text select').each(function(){
var def = $(this).siblings('.value').text();
$(this).find('option[value='+def+']').attr('selected', 'selected');
$(this).change();
});
});
---------------------- this is what i want to do to HIDE the source on the site --------------------
here is my php to get the MAKE but how do I create the model array so that when a user chooses a car the appropriate MODELS will populate in the corresponding dropdown (called Select Model: )
<?php
$car_make = array('ATV','Boat','Motorcycle','Acura','Alfa Romeo','AM General'); //this is only a partial array, it will have all the makes
echo '<select name="car_make">';
for($i = 0; $i < count($car_make);$i++)
{
echo '<option value="'. ($i + 1) . '">' . $car_make[$i] . '</option>';
}
echo '</select>';
?>
how do i create a second array with vehicle models that will use the first array's option value to lookup a make and then pull the corresponding make's from the model array ?
Well you can use jQuery to select the value of the first select menu and then use it to compare with the specific value for make and then display its specific models
var model=new Array();
function getmodel() {
var make=$('select[name=make]').val();
if(make==='toyota'){$("select[name=model]").html('');$("select[name=model]").append("<option value='corolla'>Corolla</option><option value='camry'>Camry</option><option value='hilux'>Hilux</option>");}
if(make==='honda'){$("select[name=model]").html('');$("select[name=model]").append("<option value='civic'>Civic</option><option value='jazz'>Jazz</option><option value='accord'>Accord</option>");}
if(make==='suzuki'){$("select[name=model]").html('');$("select[name=model]").append("<option value='cultus'>Cultus</option><option value='vitara'>Vitara</option>");}
if(make==='bugatti'){$("select[name=model]").html('');$("select[name=model]").append("<option value='veyron'>Veyron</option><option value='chiron'>Chiron</option>");}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
SELECT MAKE:
<select name='make' onchange='getmodel();'>
<option value='toyota'>TOYOTA</option>
<option value='honda'>HONDA</option>
<option value='suzuki'>SUZUKI</option>
<option value='bugatti'>BUGATTI</option>
</select>
<br/>
SELECT MODEL
<select name='model'>
</select>

Populate select box from database query based on another select box using only 1 table

Hi guys I am currently creating a website with the main function of booking cars. Therefore the user would be first able to select a car category from the database query which will output the selected car category names. After selecting the car category name, the second select box would then by dynamically updated with a new set of of car names that are associated with the category.
There may have been many similar questions to this however for the website NO jQuery or AJAX can be utilized. And other questions and examples often utilize 2 or more tables however I am using only 1 table for this function.
The example below should show how the Select box should be updated:
Dynamically updated select box.
The table utilized is this:
Table Utilized
My codes are as such:
<?php
session_start();
include "dbconn.php";
$query = "SELECT carid, brand FROM cars";
$result = $dbcnx->query($query);
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
}
$jsonSubCats = json_encode($subcats);
?>
<!docytpe html>
<html>
<head>
<script type='text/javascript'>
<?php
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
</head>
<body onload='loadCategories()'>
Car Category:<br />
<select size="1" name="categoriesSelect" id="categoriesSelect">
<option> Select Car Category </option>
<option value="sedan"> Sedan </option>
<option value="mpv"> MPV </option>
<option value="hatch"> Hatchback </option>
</select><br /><br />
Car Brand:<br />
<select id='subcatsSelect'>
</select>
</body>
</html>
I may have identified the error to the php statement:
while($row = $result->fetch_assoc()){
$subcats[] = array("id" => $row['carid'], "val" => $row['brand']);
As I can only see the first select box query correctly consisting of the 3 car category of MPV, Sedan and Hatchback.
Currently the all the Car Brand name appears however the results do not correspond with the car category as shown in the database.
Thank You.
As both arrays in PHP follow the same pattern when created the json data will be similar also thus the method to traverse the data should follow that in loadCategories function - so perhaps this:
function updateSubCats(){
var oSelect = document.getElementById("subcatsSelect");
oSelect.options.length = 0;
for( var i in subcats ){
oSelect.options[ i ]=new Option( subcats[ i ].val, subcats[ i ].id );
}
}
Without using Ajax or over complicating things with complex json iteration you could try along these lines. It should be noted that embedding the $_GET variable directly in the sql is not the best option - prepared statements would be better but should give the idea.
<?php
session_start();
include "dbconn.php";
?>
<!docytpe html>
<html>
<head>
<title>Chained select</title>
<script type='text/javascript'>
function bindEvents(){
document.getElementById('categories').addEventListener( 'change', getSubcategories, false );
}
function getSubcategories(e){
var el=e.target ? e.target : e.srcElement;
var value=el.options[ el.options.selectedIndex ].value;
location.search='?category='+value;
}
document.addEventListener( 'DOMContentLoaded', bindEvents, false );
</script>
</head>
<body>
<form>
<select id='categories'>
<?php
$query = "SELECT carcat FROM cars";
$result = $dbcnx->query($query);
while( $row = $result->fetch_assoc() ){
echo "<option value='{$cat['carcat']}'>{$cat['carcat']}";
}
?>
</select>
<select id='subcategories'>
<?php
if( !empty( $_GET['category'] ) ){
$sql = "SELECT carid, brand FROM cars where carcat='{$_GET['category']}';";
$result = $dbcnx->query( $sql );
if( $result ){
while( $row = $result->fetch_assoc() ){
echo "<option value='{$row['carid']}'>{$row['brand']}";
}
}
}
?>
</select>
</form>
</body>
</html>
Of course it won't, you're accessing your arrays wrong:
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
^^^^^ ^^^^^
Your subcats array is only 2-dimensional, yet you're accessing it as a 3-dimentional array here.

Creating multiple select populated by js array

Ok this is a bit complicated. Basically I populate a select with an array. Then, I want to create another select, and populate it with the same array again. I believe that the populate function is not called properly when a new select is created, but I cannot find when to call it, to populate the created select.
1st: I query my db to get some member names, and use json_encode my resulting array, to create a json array.
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
$json_array = json_encode($result_array);
then I echo that array to a javascript array, and populate a select tag with the result. All this happens on window load.
<script>
var members = <?php echo $json_array; ?>;
function populate()
{
var sel = document.getElementById('members');
var fragment = document.createDocumentFragment();
members.forEach(function(member, index) {
var opt = document.createElement('option');
opt.innerHTML = member;
opt.value = member;
fragment.appendChild(opt);
});
sel.appendChild(fragment);
}
window.onload = populate;
</script>
The html div containing the select:
<div id="Members">
<select id="members"></select>
</div>
<input type="button" value="+" onClick="addInput('Members'); populate();">
and then I use another script to create more divs
<script>
var counter = 1;
var limit = 3;
function addInput(divName)
{
if (counter == limit)
{
var message = document.getElementById("linkLimit");
message.innerHTML = "Maximum amount of links reached";
}
else
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<select id='members'></select>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
However, the resulting selects are never actually populated. I believe that the populate function is not called properly, but I cannot find when to call it, to populate the created select.
Alternatively, for a static amount of select inputs, I tried doing
<div id="Members">
<select id="members" name="members"></select>
<select id="members1" name="members"></select>
<select id="members2" name="members"></select>
</div>
but again, only the first select is populated
By using a for loop and giving members, members1, members2 through an array, all three lists are populated, however, this is not so functional, since I can't know how many members the user will want to select

Categories

Resources