Drop Down Menu Validation JS - javascript

I have a dynamically generated drop down menus using PHP, I use these manes on different web pages, Now I also want to add some JS validation to these menus so that the user does not forget to choose an option while filling in a form.
The problem is that my JS code does not work and does not validate my menus, The code looks good to me I have IF statements where they check if the first option value =0 therefore there has not been selection but it still does not work
PHP code:
$option='<select id="Forex" name="workshop">';
$option.='<option value="0">Select Forex Workshop</option>';
$option.='';
while($result = mysqli_fetch_assoc($query))
{
if($timestamp < $result['endingDate'])
{
$option.='<option id="'.$result['id'].'" value='.$result['endingDate'].'>'.$result['course']." ".$result['schedule'].'</option>';
}
}
$option.='</select>';
return $option;
}
function getBinary($link){
$timestamp = date("Y-m-d");
$query2 = mysqli_query($link, $sql2);
$option2='<select id="Binary" name="workshop">';
$option2.='<option value="0">Select Binary Workshop</option>';
$option2.='';
while($result2 = mysqli_fetch_assoc($query2))
{
if($timestamp < $result2['endingDate'])
{
$option2.='<option id="'.$result2['id'].'" value="'.$result2['endingDate'].'">'.$result2['course']." ".$result2['schedule'].'</option>';
}
}
$option2.='</select>';
return $option2;
}
?>
JS CODE:
var workshop=document.getElementById('Binary').value;
if(workshop==0){
document.getElementById('Binary').style.borderColor = "red";
document.getElementById('error').innerHTML = "Please Select Workshop1";
return false;
}else{
document.getElementById('Binary').style.borderColor = "green";
}
var workshop2=document.getElementById('Forex').value;
if(workshop2==0){
document.getElementById('Forex').style.borderColor = "red";
document.getElementById('error').innerHTML = "Please Select Workshop";
return false;
}else{
document.getElementById('Forex').style.borderColor = "green";
}

You have wrongly named the select id/name.
$option='<select id="Forex" name="workshop">';
and yet you are trying to access it from JS by calling it by id workshop while the name attribute is workshop not the id.
var work=document.getElementById('workshop').value;
The id is Forex not workshop. And you call Forex from different Js line. I think your error is in trying to access a null variable. Unless you have another element with the id workshop that I'm not aware of.

Related

Process user data in PHP from JavaScript in HTML with multiple selections

just a fair warning: I'm a HTML, PHP and JavaScript noob.
I wrote code to get multiple selection boxes, where the selectable content from the second box is dependent on the
selection of the first box.
So like:
Brands: if Asus is selected the next box: and the last box is prime is selected:
Asus Prime B560
MSI Plus Z590 etc.
This has to be expendable to newer models, brands etc.
The Code I have so far:
(hersteller means manufacturer)
index.html
<!DOCTYPE html>
<head></head>
<body>
<form name="form1" id="form1" action="redir.php">
Hersteller: <select name="hersteller" id="hersteller">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
Modell: <select name="model" id="model">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
Chipset: <select name="chipid" id="chipid">
<option value="" selected="selected">-wählen-</option>
</select>
<br><br>
<input type="submit" value="weiter">
<script>var subjectObject = {
"Asus": {
"Prime": ["B560", "Z490", "Z590", "Z690"],
"ProArt": ["Z490"],
"ROG": ["Z690 ITX"]
},
"MSI": {
"Torpedo": ["Z490", "Z590", "Z690"]
}
}
window.onload = function() {
var subjectSel = document.getElementById("hersteller");
var topicSel = document.getElementById("model");
var chapterSel = document.getElementById("chipid");
for (var x in subjectObject) {
subjectSel.options[subjectSel.options.length] = new Option(x, x);
}
subjectSel.onchange = function() {
chapterSel.length = 1;
topicSel.length = 1;
for (var y in subjectObject[this.value]) {
topicSel.options[topicSel.options.length] = new Option(y, y);
}
}
topicSel.onchange = function() {
chapterSel.length = 1;
var z = subjectObject[subjectSel.value][this.value];
for (var i = 0; i < z.length; i++) {
chapterSel.options[chapterSel.options.length] = new Option(z[i], z[i]);
}
}
}</script>
</form>
</body>
redir.php
<?php
$hersteller = $_POST["hersteller"];
$chipid = $_POST["chipid"];
$model = $_POST["model"];
if ($hersteller = "Asus") {
if($model = "Prime"){
if($chipid = "B560"){
header("Location: /driver_sites/Asus_Prime_B560.html");
}
}
exit();
}
//elseif ($items = 'Item2') {
//header("Location: item2.php");
//}
?>
I want to process the data selected and redirect to a specific site. For example
if the user selects "Asus" -> "Prime" -> "B560" and clicks on "weiter" (submit), it should redirect him to
a page like Asus_Prime_B560.html
How can this be done?
Thanks in advance :)
I tried multiple ways in PHP but nothing seems to work and my knowlege is limited.
Also, I searched what feels like the entire internet but to no avail.
I hope I understood your problem, what about changing your "redir.php" file as follows:
<?php
$hersteller = $_POST["hersteller"];
$chipid = $_POST["chipid"];
$model = $_POST["model"];
$page = $hersteller.'_'.$model.'_'.$chipid.'.html';
header("Location: /driver_sites/".$page);
What this does is build the "page filename" based on the inputs and just redirect to it. Let's say that the user selected following values:
$hersteller = 'Asus';
$model = 'Prime';
$chipid = 'B560';
$page = $hersteller.'_'.$model.'_'.$chipid.'.html';
$page is now => Asus_Prime_B560.html
This example implies that all pages have the same format HERSTELLER_MODEL_CHIPID.html
Edit:
Based on your comment I will add some info
When you see some URL containing ?some=thing&foo=bar the part after the ? (question mark) is called query string. This query string parameters can be accessed by PHP using the $_GET superglobal (i.e. to read param foo i can do
$foo = $_GET['foo']; //$foo now contains "bar"
On the other end, if the form has been submitted using the POST method (<form method="post" ....>) the the data can be accessed using the $_POST superglobal
$something = $_POST['paramNam'];

Validate if more than one item was selected using jquery

This code allows the user to select one or more models of cars graphically on a web page. I am in need to check if more than one was selected. How can I get this to count the number of selected items and if it's great than one alert("something")?? In short, I need to know if both Lexus and Inifiti were chosen in the example code here. I really need the count so if it's greater than 1 selected. Any help is great appreciated, not sure what I am doing wrong .
<div class="options-item-wrapper clearfix">
<?php
$modelOptions = array(
0 => array('title' => 'Lexus'),
1 => array('title' => 'Infiniti')
);
foreach ($modelOptions as $modelOption) {
$selected = '';
$optionValue = '';
if(in_array($modelOption['title'], $modelArray)) {
$selected = 'selected';
$optionValue = '<input class="vehicle-option"
type="hidden" name="model[]"
value="'.$modelOption['title'].'">';
}
echo '<div class="options-item '.$selected.'" data-vehicle="'.
$modelOption['title'].'">
<div>'.$modelOption['title'].'</div>
'.$optionValue.' </div>';
}
?>
</div>
I have tried this but no luck thus far :
var checkedNum = $('input[name="model[]"]:selected').length;
alert(checkedNum);
if (checkedNum > 1) {
alert('Validating the form2');
// User didn't check any checkboxes
} else {
die();
}
Your code doesn't work because hidden input elements don't have a selected state.
If I understand your code correctly, you add the class 'selected' to your options items if they're selected. Wouldn't you just need to count the number of options items with the selected class?
var checkedNum = $('.options-item.selected').length;
alert(checkedNum);
if (checkedNum > 1) {
alert('Validating the form2');
// User didn't check any checkboxes
} else {
die();
}

Show and hide element through different tabs PHP

I have a select inside a form with different types of devices from the database (devices.insert.php):
Type:<select name="type" form="form_select" onchange="showDiv(this)">
<?php
$sql = "SELECT *
FROM Property
WHERE PRP_PRP_TYP_Id = 1";
$result = sqlsrv_query($con, $sql);
echo "<option disabled selected value> -- select an option -- </option>";
while ($row = sqlsrv_fetch_array($result)){
echo "<option value='".$row['PRP_Id']."'>".$row['PRP_Value']."</option>";
}
?>
</select><br>
<script type="text/javascript">
function showDiv(elem){
if(elem.value == 3 || elem.value == 24 || elem.value == 25){
document.getElementById('sc_div').style.display = "block";
}
else{
document.getElementById('sc_div').style.display = "none";
}
}
</script>
And when I select one of the items with the correct id, a div element turns visible with more options.
<div id="sc_div" style="display:none">
...
Register new SIM<br>
</div>
In sim_cards_insert.php I have a form with submit and cancel and when I press to go back (to devices_insert.php) the div sc_div is not visible again but the data that I've filled before is in the same place.
<button type="button" class="log-btn" onClick="history.go(-1)">Cancel</button>
How can I get it visible again passing through different windows?
Sounds like the browser is reverting the DOM to it's initial state - ie with the sc_div hidden.
Perhaps you could check the previous URL for the devices_insert.php page load.
<script type="text/javascript">
function showDiv(elem){
//example
var filename = document.referrer.split('/').pop();
if(filename === 'sim_card_insert.php'){
document.getElementById('sc_div').style.display = "block";
}
//...rest of function
</script>

How to pass same class/id name php values from radio button to javascript?

This is my problem. I am looping items from the database that contains items name and id. I have a radio button for each items. The id of that item is stored in the radio buttons value....Now what i want to achieve is when i click on the submit button,it will call a function call save() in javascript and save all the selected items ONLY .... i've been trying this for hours but i cant get it worked.
Here are my codes....
When i do my while looping from the DB, it will display the radio button and the items name...
<?php
$retrieveQuery = "SELECT * FROM `itemdb` WHERE `approve`= 1 AND `userId` = '$userId';";
$retrieveresult = mysqli_query($dbconnect, $retrieveQuery);
if(mysqli_num_rows($retrieveresult) > 0)
{
while($retrieverow = mysqli_fetch_assoc($retrieveresult))
{
?>
<p> </p>
<div style="background-color: rgba(0, 0, 0, 0.16);">
<input style="margin-bottom: -19px;" type="checkbox" class="item" name="item[]" value=<?php echo $retrieverow['itemID'] ?>>
<p style="margin-left: 26px;"><?php echo $retrieverow['itemName'] ?></p>
<p style="margin-top:-10px;margin-left:28px"><i><?php echo $retrieverow['category'] ?></i></p>
</div>
<?php
}
}
else
{
echo "Test : There is no approve Items to be displayed";
echo "Either wait for the admin to approve or upload items to start Trading ! ";
}
?>
This is my script:(How can i save my items?)
function save()
{
var f = document.getElementsByClassName('item').value; //my own items chosen frm invntry
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("confirmTrade").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST","trade.php?f="+f,true);
xmlhttp.send();
}
Right after i click the save() function it will send the data to another page using ajax method....
PS: Everything works fine...Other variables are passed successfully but only one item variable is being passed....
Thanks in advance!
Without looking into it too much, take a look at this line:
var f = document.getElementsByClassName('item').value;
document.getElementsByClassName gets an HTMLCollection of elements, so calling value on this doesn't make much sense. You'll need to loop through them and find the selected ones. I have it building an array then joining it into a comma separated list:
var checkboxes = document.getElementsByClassName('item');
var f = [];
for(var i = 0; i < checkboxes.length; i++){
if(checkboxes[i].checked == true)
f.push(checkboxes[i].value);
}
f = f.join();//makes comma seperated list
//proceed with ajax call

Java Script Drop Down Menu Validation

Ok I have a drop down menu that is dynamically generated by PHP and populated with data fetched from database. Frontally this works vert well, The problem that I am having is with a JS validation, am not so good with JavaScript ('Dislike it'), but for the purposes of my mini project I have to work with it anyway....
The problem is that with JS I am checking if a user has selected one of the options available in drop down menu is so the form can be submitted else display a warning.
So what I am trying to do is this.....Give a value="f" to the first option which displays "PLEASE SELECT workshop" so if at the submission of the form the value of this drop down menu == f return false else submit the form.
now if at the submission the value ==f the error is displayed but if the value is not == f and i select one of the values from drop down menu i cannot proceed with the submission its does not allow me
PHP code:
function getForex($link){
$timestamp = date("Y-m-d");
$sql = "SELECT id, course, status, endingDate, schedule FROM courses WHERE course LIKE '%Forex%' OR course LIKE '%forex%' AND status=5";
$query = mysqli_query($link, $sql);
$option='<select id="Forex" name="workshop">';
$option.='<option id="fx" value="Forex">Select Forex Workshop</option>';
$option.='';
while($result = mysqli_fetch_assoc($query))
{
if($timestamp < $result['endingDate'])
{
$option.='<option id="'.$result['id'].'" value='.$result['endingDate'].'>'.$result['course']." ".$result['schedule'].'</option>';
}
}
$option.='</select>';
return $option;
}
JS CODE:
var sel=document.getElementById('fx').value="Forex";
if(sel.match("Forex")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('fx').style.borderColor = "red";
return false;
}else{
document.getElementById('fx').style.borderColor = "green";
}
OK guys combination of many very helpful answers have helped but when I add another drop down menu like
PHP code:
function getBinary($link){
$timestamp = date("Y-m-d");
$sql2 = "SELECT id, course, status, endingDate, schedule FROM courses WHERE course LIKE '%Binary%' OR course LIKE '%binary%' AND status=5";
$query2 = mysqli_query($link, $sql2);
$option2='<select id="Binary" name="workshop">';
$option2.='<option id="bi" value="Binary">Select Binary Workshop</option>';
$option2.='';
while($result2 = mysqli_fetch_assoc($query2))
{
if($timestamp < $result2['endingDate'])
{
$option2.='<option id="'.$result2['id'].'" value="'.$result2['endingDate'].'">'.$result2['course']." ".$result2['schedule'].'</option>';
}
}
$option2.='</select>';
return $option2;
}
JS Code:
var selbi=document.getElementById('Binary').value;
if(selbi.match("Binary")){
document.getElementById('error').innerHTML = "Choose Binary Workshop Date";
return false;
}
The problem becomes that The Inner HTML message displays only for forex and get twisted around i.e. if forex is not selected it shows the message choose forex workshop if i choose the forex workshop it then shows choose binary workshop :D
You are not using select id use select id
var sel=document.getElementById('Forex').value;
if(sel.match("Forex")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('fx').style.borderColor = "red";
return false;
}else{
document.getElementById('fx').style.borderColor = "green";
}
i have done javaScript drop-down validation .when in drop down value is "select one" in that time give you messages "please select your value ".My hole project in github .Project link
is Javascript drop-down value validation
you have to use drop down Id 'Forex' for get the selected value of drop down not option id, like below
var sel = document.getElementById('Forex').value;
Html Code
<form id="send" name="myfrom" action="confrimationPage.php" method="POST" onsubmit="return validateForm(this);" >
<p>
<label for="company">Gender</label>
<select id="gender" name="gender">
<option value="Select One">Select One</option>
<option>Male</option>
<option>Female</option>
</select>
</p>
<p>
<label for="country">Postal Code</label>
<input id="Country" type="text" name="postalCode" />
</p>
<p>
<button id="submit" type="submit">Submit</button>
</p>
</form>
*JavaScript *
<script type="text/javascript">
function validateForm(form)
{
// Gender empty or not
var selectGender=document.getElementById('gender').value;
if(selectGender=="Select One")
{
alert("Please Select gender");
return false;
}
//Postal code empty or not
if(form.postalCode.value=="")
{
alert("Filled the Postal Code Field");
form.postalCode.focus();
return false;
}
}
</script>
Check It
var sel=document.getElementById('Forex').value;
var binary=document.getElementById('Binary').value;
if(sel.match("Forex")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('Forex').style.borderColor = "red";
return false;
}else{
document.getElementById('error').innerHTML = "";
document.getElementById('Forex').style.borderColor = "green";
}
if(binary.match("Binary")){
document.getElementById('error').innerHTML = "Choose Forex Workshop Date";
document.getElementById('Binary').style.borderColor = "red";
return false;
}else{
document.getElementById('error').innerHTML = "";
document.getElementById('Binary').style.borderColor = "green";
}

Categories

Resources