I have an HTML form that takes in values from a dropdown list. When an option is selected the HTML badge is updated to display the status of Good or Bad.
Each badge element span class is the same, but the ID is different as I need to capture the result.
Is there a way that I can use a single JavaScript function against all span classes but only update the span class for where the dropdown box is?
Or do I need to define every element ID within the JavaScript function.
The <span class="badge badge-soft-success" is on every badge.
const changeBadgeColour = document.getElementById('project-tier-entry-level');
changeBadgeColour.addEventListener('change', function() {
var p_status = document.getElementById("project-tier-entry-level");
p_status_value = p_status.options[p_status.selectedIndex].value;
const statusBadge = document.getElementById('project-tier-entry-level-status');
if (p_status_value === "Yes") {
document.getElementById('project-tier-entry-level-status').className = 'badge badge-soft-success'
document.getElementById('project-tier-entry-level-status').textContent = 'Good!'
} else {
document.getElementById('project-tier-entry-level-status').className = 'badge badge-soft-danger'
document.getElementById('project-tier-entry-level-status').textContent = 'Bad!'
}
console.log()
});
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered entry levels?</label>
<span class="badge badge-soft-success" id="project-tier-entry-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-entry-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
You can delegate
document.getElementById('container').addEventListener('change', function(e) {
const tgt = e.target;
if (tgt.tagName === "SELECT" && tgt.id.startsWith("project-tier")) { // in case there are other things that can change in that container
const yes = tgt.value === "Yes"
const statusBadge = tgt.previousElementSibling; // or tgt.closest('div').querySelector('span.badge');
statusBadge.classList.toggle("badge-soft-success", yes)
statusBadge.classList.toggle("badge-soft-danger", !yes)
statusBadge.textContent = yes ? 'Good!' : 'Bad!';
}
});
<div id="container">
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered entry levels?</label>
<span class="badge badge-soft-success" id="project-tier-entry-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-entry-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered normal levels?</label>
<span class="badge badge-soft-success" id="project-tier-normal-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-normal-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
Three options with a result of the selections:
document.getElementById('container').addEventListener('change', function(e) {
const tgt = e.target;
if (tgt.tagName === "SELECT" && tgt.id.startsWith("project-tier")) { // in case there are other things that can change in that container
const badge = tgt.value
const statusBadge = tgt.previousElementSibling; // or tgt.closest('div').querySelector('span.badge');
statusBadge.classList.toggle("badge-soft-success", badge==="Yes")
statusBadge.classList.toggle("badge-soft-danger", badge==="No")
statusBadge.classList.toggle("badge-soft-unknown", badge==="Unknown")
const text = {"Yes":"Good!","No":"Bad!","Unknown":"Unknown!"}[badge] || "What?"
statusBadge.textContent = text;
const res = [...document.querySelectorAll("#container select[id^=project-tier]")]
.reduce((acc, sel) => {
if (acc[sel.value] != undefined) acc[sel.value]++;
else acc["Not set"]++;
return acc
},{"Yes":0,"No":0,"Unknown":0,"Not set":0})
document.getElementById("result").value = Object.entries(res).map(([key,val]) => `${key}: ${val}`).join('\n')
}
});
<form id="tierForm">
<div id="container">
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered entry levels?</label>
<span class="badge badge-soft-success" id="project-tier-entry-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-entry-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
<option>Unknown</option>
</select>
</div>
<div class="col-sm-6">
<label class="form-label" for="project-tier-entry-level-label">Does the project land in our Tiered normal levels?</label>
<span class="badge badge-soft-success" id="project-tier-normal-level-status"></span>
<select class="form-control" name="choices-single-no-sorting" id="project-tier-normal-level">
<option value="" disabled selected hidden>Please Choose...</option>
<option>Yes</option>
<option>No</option>
<option>Unknown</option>
<option></option>
</select>
</div>
</div>
<div>
<textarea readonly id="result"></textarea>
</div>
</form>
How about if you assign the class name directly to your changeBadgeColour variable with querySelectorAll.
const changeBadgeColour = document.querySelectorAll('.badge .badge-soft-success')
Related
In my project i have a select incapsulated into two divs, i have to get the text or value) from the select from a javascript.
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divTtype">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
i try this code:
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
but when i try :
GetElementInsideContainer(divType, ftype).text;
an "undefined" return to me.
How can i get my select value?
so many thanks in advance
Actually there's a typo in your HTML code "divTtype", you meant to write divType
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divType">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
Also you need to use textContent attribute instead of text
Finally please call the function using "id", else you are calling undefined variables divType and ftype
console.log(GetElementInsideContainer("divType", "ftype"));
This will certainly fix your current issue, although please refer to raphael answer for better approach.
Because text doesn't exist into HTMLElement.
You have to do this:
GetElementInsideContainer(divType, ftype).textContent;
Here's the documentation.
You should use quotes when you send string as a parameter:
GetElementInsideContainer('divType', 'ftype').text;
Like Krishna said in the comment above, you should be able to just do:
var select = document.getElementById('ftype')
var val = select.options[select.selectedIndex].value
You don't have to reference the parent node.
Use textContent and pass id in form of string otherwise it take it as a variable
secondly you have id divTtype and you were passing divType
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
var a = GetElementInsideContainer("divType", "ftype").textContent;
console.log(a)
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divType">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
Seems to be working fine overhere.
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divTtype">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
<button onclick="getSelected(GetElementInsideContainer('divTtype', 'ftype'))">Get Selected Value</button>
<script>
function getSelected(objEl)
{
alert(objEl.options[objEl.selectedIndex].text);
}
function GetElementInsideContainer(containerID, childID) {
var elm = document.getElementById(childID);
var parent = elm ? elm.parentNode : {};
return (parent.id && parent.id === containerID) ? elm : {};
}
</script>
do you need the selected value of the select?
I did that snippet and get the HTML of the select.
with this snippet, you can get the value of a select
<div class="col-lg-3 col-xs-6" id="div1">
<div class="form-group" id="divTtype">
<label>Templte Type:</label>
<select class="form-control" id="ftype">
<option value="..All">..All</option>
<option value="Functional">Functional</option>
<option value="Non Functional">Non Functional</option>
</select>
</div>
</div>
function GetElementInsideContainer( childID) {
var elm = document.getElementById(childID);
console.log(elm.value)
return elm.value;
}
GetElementInsideContainer('ftype');
I think that maybe you pass in the argument an incorrect id
I have a multidrop form at this fiddle : Here's a link! . at this form only can add multidrop 3 times, i want to make always add this multidrop, and how to save the array data into sql
<div id="Yes1">
<label for="name" >Name</label>
<input type="text" id="name1" name="name1">
<br><br>
<label for="multiDrop" >Multi Drop</label>
<select name="multiDrop1" id="multiDrop1">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
Check here to add and remove your elements as per your requirement.
You can remove only that block which you selected No for.
$(document).ready(function() {
$(document).on("change", ".multidrop", function() {
if ($(this).val() == 'Y') {
$clone = $(this).closest(".Yes").clone();
var num = parseInt($(".Yes:last").attr("data-index")) + 1;
$clone.attr("data-index", num);
$clone.attr("id", $clone.attr("id").replace(/\d+/, num));
$clone.find("input,select").each(function() {
var name = ($(this).attr("name")).replace(/\d+/, num);
var id = ($(this).attr("id")).replace(/\d+/, num);
$(this).attr("name", name);
$(this).attr("id", id);
});
$clone.insertAfter(".Yes:last"); //Add field html
} else if ($(this).val() == "N" && $(".Yes").length > 1) {
$(this).closest(".Yes").remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Yes1" class="Yes" data-index="1">
<label for="name">Name</label>
<input type="text" id="name1" name="name1" class="name">
<label for="multiDrop">Multi Drop</label>
<select name="multiDrop1" id="multiDrop1" class="multidrop">
<option value="">Select Option</option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
I would recommend to use following approach:
get your repetitive block HTML into a variable;
listen for changes of drop down (using event delegation, selecting by class rather than id);
modify necessary attributes (names, id's, etc) based on global counter to distinguish those dynamic blocks;
const block = `
<div class="block">
<div class="yes">
<label>Name</label>
<input type="text" class="name"></input>
<label>Multi Drop</label>
<select class="multiDrop">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
</div>
</div>
`;
const addAnotherBlock = () => {
$('#wrapper').append(block);
$('.name:last').attr('name',i++);
};
var i = 0;
$(document).ready(() => addAnotherBlock());
$('#wrapper').on('change', '.multiDrop', function(){
if($(this).val() == 'Y') addAnotherBlock();
else if($(this).val() == 'N' && $('.block').length > 1 && !$(this).closest('.block').is('.block:last')){
$(this).closest('.block').remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper"></div>
Working on an app that exports what the user typed on the app to a particular website with the similar components. For example, if the user typed a title on the app, when he presses a button, it imports that value to a webpage which also requests the user to type.
This is the flow chart or something
User --> User inputs a text in the app --> App copies what the user's typed --> App opens a particular website --> App pastes what he copied to the website.
(Website: A google form for an example.)
Now I've already finished all of it except for the latter part where the app pastes what he copied.
The problem is the app do not know where to paste it.
So I want to get the ID's of the code below, it is perfectly fine if you just identify all the id's or something similar and how to call it.
Have imported data from backend successfully, but have zero clue on how to get the id's or the variable names of a textarea, radio buttons, the div.
javascript:
(function () {
function WW(ele, val)
{
if(document.getElementById(ele) && val != "")
{
document.getElementById(ele).value = val;
}
}
WW("story-title", "The Good Peacock");
)();
Copied this from someone.
This works with other sites that have the an id, like:
<textarea id="story-title">
So, need to know the id's of the HTML below.
This is a part of the source code of the website, which is auto-fill.
Tried calling with getElementByClassName(), but didn't work.
<form class="main-edit-form">
<div class="required-form-wrapper">
<div class="form-group title-form">
<label>Title</label>
<span class="empty-warning hidden" id="title-warning">Required</span>
<div contenteditable="true" class="story-title">Untitled Story</div>
</div>
<div class="form-group description-form">
<div class="form-wrapper">
<label>Description</label>
<span data-toggle="popover" class="popover-icon" id="description-tooltip" title="" data-original-title="Add a story description"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="empty-warning hidden" id="description-warning">Required</span>
</div>
<textarea type="text" name="title" class="story-description "></textarea>
</div>
<div class="form-group tags-form">
<div class="form-wrapper">
<label>Tags</label>
<span data-toggle="popover" class="popover-icon" id="tags-tooltip" title="" data-original-title="Help readers find your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="empty-warning hidden" id="tag-empty-warning">Required</span>
</div>
<div class="tag-container">
<div id="editable-tags">
<div class="component-wrapper" id="component-TagGrid-storyTags-/myworks/new"></div>
</div>
<div id="add-tag" class="tag-item with-icon on-add-tag">
<span>Add a tag</span><span class="fa fa-plus fa-wp-black " aria-hidden="true" style="font-size:12px;"></span>
</div>
<span id="tag-input-wrapper">
<input id="tag-input" class="hidden on-tag-input" placeholder="Separate tags with a space" autocomplete="off">
</span>
</div>
</div>
<div class="form-group inline-form">
<div class="form-wrapper">
<label for="categoryselect">Genre</label>
<span data-toggle="popover" class="popover-icon" id="category-tooltip" title="" data-original-title="Tell Wattpad the genre of your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="categoryselect" class="form-control ">
<option value="-1">Select a genre</option>
<option value="14">Action</option>
<option value="11">Adventure</option>
<option value="24">ChickLit</option>
<option value="6">Fanfiction</option>
<option value="3">Fantasy</option>
<option value="21">General Fiction</option>
<option value="23">Historical Fiction</option>
<option value="9">Horror</option>
<option value="7">Humor</option>
<option value="8">Mystery / Thriller</option>
<option value="16">Non-Fiction</option>
<option value="12">Paranormal</option>
<option value="2">Poetry</option>
<option value="19">Random</option>
<option value="4">Romance</option>
<option value="5">Science Fiction</option>
<option value="17">Short Story</option>
<option value="13">Spiritual</option>
<option value="1">Teen Fiction</option>
<option value="18">Vampire</option>
<option value="22">Werewolf</option>
</select>
<span class="empty-warning hidden" id="category-empty-warning">Required</span>
</div>
</div>
</div>
<div class="inline-form-wrapper">
<div class="inline-form-row">
<div class="form-group inline-form">
<div class="form-wrapper">
<label>Language</label>
<span data-toggle="popover" class="popover-icon" id="language-tooltip" title="" data-original-title="What language is your story in?"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="languageselect" class="form-control ">
<option value="1" selected="selected">English</option>
<option value="2">Français</option>
<option value="3">Italiano</option>
<option value="4">Deutsch</option>
<option value="5">Español</option>
<option value="6">Português</option>
<option value="38">Català</option>
<option value="19">Tiếng Việt</option>
<option value="18">Filipino</option>
<option value="20">Bahasa Indonesia</option>
<option value="22">Bahasa Melayu</option>
<option value="32">ภาษาไทย</option>
<option value="7">Русский</option>
<option value="15">Română</option>
<option value="23">Türkçe</option>
<option value="24">Česky</option>
<option value="14">Polski</option>
<option value="28">Magyar</option>
<option value="30">ελληνικά</option>
<option value="35">Eesti</option>
<option value="36">Latviešu</option>
<option value="37">Lietuvių</option>
<option value="39">Босански</option>
<option value="40">Српски</option>
<option value="41">Hrvatski</option>
<option value="43">Български</option>
<option value="44">Slovenčina</option>
<option value="42">Slovenščina</option>
<option value="45">Беларускі</option>
<option value="46">Українська</option>
<option value="26">Svenska</option>
<option value="27">Norsk</option>
<option value="34">Suomi</option>
<option value="29">Dansk</option>
<option value="13">Nederlands</option>
<option value="33">Íslenska</option>
<option value="12">简体中文</option>
<option value="8">繁體中文</option>
<option value="9">日本語</option>
<option value="10">한국어</option>
<option value="16">العربية</option>
<option value="53">ગુજરાતી</option>
<option value="17">עברית</option>
<option value="21">हिन्दी</option>
<option value="25">മലയാളം</option>
<option value="54">ଓଡ଼ିଆ</option>
<option value="31">فارسی</option>
<option value="55">ਪੰਜਾਬੀ</option>
<option value="56">অসমীয়া</option>
<option value="47">বাংলা</option>
<option value="48">اُردُو</option>
<option value="49">தமிழ்</option>
<option value="50">Kiswahili</option>
<option value="51">Afrikaans</option>
<option value="57">मराठी</option>
<option value="11">Other</option>
</select>
</div>
</div>
<div class="form-group inline-form copyright-form">
<div class="form-wrapper">
<label>Copyright</label>
<span data-toggle="popover" class="popover-icon" id="copyright-tooltip" title="" data-original-title="Who owns your story?"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<select id="copyrightSelect" class="form-control ">
<option value="0">Not Specified</option>
<option value="1">All Rights Reserved</option>
<option value="2">Public Domain</option>
<option value="3">Creative Commons (CC) Attribution</option>
<option value="4">(CC) Attrib. NonCommercial</option>
<option value="5">(CC) Attrib. NonComm. NoDerivs</option>
<option value="6">(CC) Attrib. NonComm. ShareAlike</option>
<option value="7">(CC) Attribution-ShareAlike</option>
<option value="8">(CC) Attribution-NoDerivs</option>
</select>
</div>
</div>
</div>
<div class="form-group rating-form">
<div class="form-wrapper">
<label class="rating-label">Rating</label>
<span data-toggle="popover" class="popover-icon" id="rating-tooltip" title="" data-original-title="Rate your story"><span class="fa fa-info fa-wp-lightergrey " aria-hidden="true" style="font-size:16px;"></span></span>
<span class="toggle-prompt">Mature</span>
<div class="onoffswitch ">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="mature-switch">
<label class="onoffswitch-label" for="mature-switch">
<div class="onoffswitch-inner">
<span class="on">ON</span>
<span class="off">OFF</span>
</div>
<span class="onoffswitch-switch"></span>
</label>
</div>
</div>
Thank you in advance!
These id's you are looking for are not generated by them self.
You need to assign id to field that you like.
I don't prefer to use id to implement css. Element id is only to be needed to implement javascript and fetch there value example from input tag.
You need to assign id while writing down your code like in following sample html.
Point to note:
Not all tags have id.
Mostly tags related to user input have id.
No 2 elements / tag have same id.
id's of different type of elements are used for different purpose, like <div>, <span> id's are used for show-hide, where as input id's are used for fetching value.
HTML:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/app.css" />
<link rel="icon" href="logo.jpg" />
<title>Info</title>
</head>
<body>
<div class="col-md-6 offset-md-3">
<div class="col-md-6">
<p class="btn btn-primary form-control" onclick="showForm('#addInfo')">Add Detail</p>
</div>
<div class="col-md-6">
<p class="btn btn-primary form-control" onclick="showForm('#showInfo');getDetail();">Show Detail</p>
</div>
<!-- No need for `form` as will use JavaScript for Single Page Application -->
<div id="addInfo" class="hide">
<div id="data"></div>
<div class="col-md-12 form-group">
<label for="addEmail">Email:</label>
<input id="addEmail" class="form-control" type="email">
<span id="addEmailError" class="hide error">Valid Email Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addFname">First Name:</label>
<input id="addFname" class="form-control" type="text">
<span id="addFnameError" class="hide error">Valid First Name Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addLname">Last Name:</label>
<input id="addLname" class="form-control" type="text">
<span id="addLnameError" class="hide error">Valid Last Name Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addPhone">Phone:</label>
<input id="addPhone" class="form-control" type="text">
<span id="addPhoneError" class="hide error">Valid Phone Required</span>
</div>
<div class="col-md-12 form-group">
<label for="addGender">Gender:</label>
<select id="addGender" class="form-control">
<option value="">Select:</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span id="addGenderError" class="hide error">Gender Required</span>
</div>
<div class="col-md-12 form-group">
<p class="btn btn-primary form-control" onclick="addInfo()">Submit</p>
</div>
</div>
<!-- No need for `form` as will use JavaScript for Single Page Application -->
<div id="showInfo" class="hide">
<div id="showDetails" class="col-md-12"></div>
</div>
</div>
<script type="text/javascript" src="/js/jquery.min.js"></script>
<!-- `login.js` is only used in `login.ejs` -->
<script type="text/javascript" src="/js/addInfo.js"></script>
<script type="text/javascript" src="/js/getInfo.js"></script>
<script type="text/javascript" src="/js/service.js"></script>
</body>
</html>
addInfo.js:
"use strict";
function addInfo() {
// JavaScript uses `id` to fetch value
let email = $("#addEmail").val(),
fName = $("#addFname").val(),
lName = $("#addLname").val(),
phone = $("#addPhone").val(),
gender = $("#addGender").val();
// Show error `span` when email is invalid
if ( validateEmail(email) ) {
$("#addEmailError").addClass("hide");
} else {
$("#addEmailError").removeClass("hide");
return;
}
// Show error `span` when First Name is invalid
if ( validateFname(fName) ) {
$("#addFnameError").addClass("hide");
} else {
$("#addFnameError").removeClass("hide");
return;
}
// Show error `span` when Last Name is invalid
if ( validateLname(lName) ) {
$("#addLnameError").addClass("hide");
} else {
$("#addLnameError").removeClass("hide");
return;
}
// Show error `span` when Phone is invalid
if ( validatePhone(phone) ) {
$("#addPhoneError").addClass("hide");
} else {
$("#addPhoneError").removeClass("hide");
return;
}
// Show error `span` when Gender is invalid
if ( validateGender(gender) ) {
$("#addGenderError").addClass("hide");
} else {
$("#addGenderError").removeClass("hide");
return;
}
// Calling local API to set authentication
// Everything in public is visible for hackers
// Thus to hide auth calling local backend
$.ajax({
"url": "/v1/detail",
"method": "POST",
"data": {email, fName, lName, phone, gender}
})
.then( result => {
// On success empty all the input fields.
$("#addEmail").val('');
$("#addFname").val('');
$("#addLname").val('');
$("#addPhone").val('');
$("#addGender").val("");
// Message to notify success submition
alert("Successfully added user.");
return;
})
.catch( err => {
// Notify in case some error occured
alert("An error occured.");
return;
});
}
getInfo.js:
"use strict";
function getDetail () {
// Request to get details of all user.
$.ajax({
"url": "http://localhost:4000/v1/detail",
"method": "GET"
})
.then( result => {
// On success using table to display data.
// This table is dynamic.
let table = `<div class="alert alert-success" role="alert">
Details fetched successfully.
</div>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>`;
let headers = [];
// Setting dynamic headers to ease work at frontend in case field changes
for ( let key in result[0] ) headers.push(key);
for ( let h of headers ) table += `<th scope="col">` + h + `</th>`;
table += ` </tr>
</thead>
<tbody>`;
let i = 1;
// Dynaic rows of table based upon headers.
for(let row of result) {
table += ` <tr>
<th scope="row">` + i + `</th>`;
for (let key of headers) table += `<td>` + row[key] + `</td>`;
table += ` </tr>`;
i++;
}
table += ` </tbody>
</table>`;
// Loading dynamic table into our static HTML page.
$("#showDetails").html(table);
})
.catch( err => {
// If error setting dynamic error
let data = `<label class="alert alert-warning">Unable to fetch details</label>`;
// Loading dynamic error into our static HTML page
$("#showDetails").html(data);
})
}
service.js:
"use strict";
/**
* Common services used by all the other scripts
* All these are generic functions
*
*/
// To toggle between different views
function showForm (id) {
// Hide all views
$("#addInfo").addClass("hide");
$("#showInfo").addClass("hide");
// Show the view user had clicked
$(id).removeClass("hide");
}
// Validate Email based upon pattern
function validateEmail (email) {
if ( email && email.match(/^([A-z0-9_.]{2,})([#]{1})([A-z]{1,})([.]{1})([A-z.]{1,})*$/) ) {
return true;
}
return false;
}
// Validate First Name based upon pattern
function validateFname (fName) {
if ( fName && fName.match(/^([A-z]{2,})*$/) ) {
return true;
}
return false;
}
// Validate Last Name based upon pattern
function validateLname (lName) {
if ( lName && lName.match(/^([A-z]{2,})*$/) ) {
return true;
}
return false;
}
// Validate Phone based upon pattern
function validatePhone (phone) {
if ( phone && phone.match(/^([0-9]{10})*$/) ) {
return true;
}
return false;
}
// Validate Gender based upon pattern
function validateGender (gender) {
if ( gender && gender.match(/^([A-z]{4,6})*$/) && (gender === "male" || gender === "female") ) {
return true;
}
return false;
}
<div class="control-group">
<label class="control-label">
<span class="red">*</span>Camera name</label>
<div class="controls">
<select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
<option>Select camera:</option>
<option>canon</option>
<option>nicon</option>
<option>sony</option>
<option>pentex</option>
<option>olympus</option>
<option>others</option>
</select>
</div>
</div>
<div class="control-group" id="dvPassport" style="display: none">
<label class="control-label">Your camera name:</label>
<div class="controls">
<input type="text" placeholder="Enter model" name="cam_name" class="input-xlarge">
</div>
</div>
javascript
<script type="text/javascript">
function ShowHideDiv() {
var ddlPassport = document.getElementById("ddlPassport");
var dvPassport = document.getElementById("dvPassport");
dvPassport.style.display = ddlPassport.value == "others" ? "block" : "none";
}
php code
$camname = $_POST['cam_name'];// user name
if(empty($camname)){
$errMSG = "Please enter camera name";
}
When i select "others" from dropdown list...it works fine
but the problem is when i select canon or nicon else...the hidden div's input tag gives error..in php code when cheking with if(empty($camname));
Have different names for select and input tags. And is good practice to add option values
<select name="cam_name" class="span3" id = "ddlPassport" onchange = "ShowHideDiv()">
<option value="">Select camera:</option> // null
<option value="canon">canon</option>
<option value="nicon">nicon</option>
<option value="sony">sony</option>
<option value="pentex">pentex</option>
<option value="olympus">olympus</option>
<option value="others">others</option>
</select>
// give a new name for this input
<input type="text" placeholder="Enter model" name="other_cam_name" class="input-xlarge">
PHP code:
$camname = $_POST['cam_name'];// cam name
$other_camname = $_POST['other_cam_name'];// other cam name
// if both select and input values
if(empty($camname) || ($camname =='others' && empty($other_camname))){
echo $errMSG = "Please enter camera name";
}else{
echo $cam_name = ($camname =='others') ? $other_camname : $camname;
}
You need to explicitly define the option values. For example:
<option value="cannon">canon</option>
I want to disable the Grade 11 and Grade 12, if any BSIT, BSCS, etc (all BS) are selected; but if STEM, TOP, GAS and HUMSS are selected the Grade 11 and Grade 12 will be enabled and all BS will be enabled.
var disable_options = false;
document.getElementById('type').onchange = function () {
//alert("You selected = "+this.value);
if(this.value == "Student")
{
document.getElementById('course').removeAttribute('disabled');
document.getElementById('year_level').removeAttribute('disabled');
}
else
{
document.getElementById('course').setAttribute('disabled', true);
document.getElementById('year_level').setAttribute('disabled', true);
}
}
<div class="control-group">
<label class="control-label" for="inputPassword">Type:</label>
<div class="controls">
<select name="type" id="type" required>
<option></option>
<option>Student</option>
<option>Teacher</option>
<option>Staff</option>
<option></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Course Type:</label>
<div class="controls">
<select name="course" id="course" required>
<option></option>
<option>BSIT</option>
<option>BSCS</option>
<option>BSHRM</option>
<option>BSBM</option>
<option>BSTM</option>
<option>STEM</option>
<option>TOP</option>
<option>GAS</option>
<option>HUMSS</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Year Level:</label>
<div class="controls">
<select name="year_level" id="year_level">
<option> </option>
<option>First Year</option>
<option>Second Year</option>
<option>Third Year</option>
<option>Fourth Year</option>
<option>Grade 11</option>
<option>Grade 12</option>
</select>
</div>
</div>
Thank you for your response and it will help me for my project thank you.
Similar to what you have already, you need to add an onchange listener to the course element.
document.getElementById("course").onchange = function() {}
Then add ID's to the grade 11 and grade 12 options, so that you can find them in the DOM.
<option id="grade-11">Grade 11</option>
<option id="grade-12">Grade 12</option>
Finally, listen to the onchange value and modify the options accordingly.
document.getElementById('course').onchange = function() {
if (["BSCS", "BSIT"].indexOf(this.value) > -1) {
document.getElementById("grade-11").setAttribute("disabled", true);
document.getElementById("grade-12").setAttribute("disabled", true);
} else {
document.getElementById("grade-11").removeAttribute("disabled");
document.getElementById("grade-12").removeAttribute("disabled");
}
}
That's it! The option elements can take the disabled attribute and cannot be selected when the course element is "BSCS" or "BSIT"
Full code
var disable_options = false;
document.getElementById('type').onchange = function () {
//alert("You selected = "+this.value);
if(this.value == "Student")
{
document.getElementById('course').removeAttribute('disabled');
document.getElementById('year_level').removeAttribute('disabled');
}
else
{
document.getElementById('course').setAttribute('disabled', true);
document.getElementById('year_level').setAttribute('disabled', true);
}
}
document.getElementById('course').onchange = function() {
if (["BSCS", "BSIT"].indexOf(this.value) > -1) {
document.getElementById("grade-11").setAttribute("disabled", true);
document.getElementById("grade-12").setAttribute("disabled", true);
} else {
document.getElementById("grade-11").removeAttribute("disabled");
document.getElementById("grade-12").removeAttribute("disabled");
}
}
<div class="control-group">
<label class="control-label" for="inputPassword">Type:</label>
<div class="controls">
<select name="type" id="type" required>
<option></option>
<option>Student</option>
<option>Teacher</option>
<option>Staff</option>
<option></option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Course Type:</label>
<div class="controls">
<select name="course" id="course" required>
<option></option>
<option>BSIT</option>
<option>BSCS</option>
<option>BSHRM</option>
<option>BSBM</option>
<option>BSTM</option>
<option>STEM</option>
<option>TOP</option>
<option>GAS</option>
<option>HUMSS</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Year Level:</label>
<div class="controls">
<select name="year_level" id="year_level">
<option> </option>
<option>First Year</option>
<option>Second Year</option>
<option>Third Year</option>
<option>Fourth Year</option>
<option id="grade-11">Grade 11</option>
<option id="grade-12">Grade 12</option>
</select>
</div>
</div>
First add value="value" to the <option> elements, so you can read the values consistently. ie: <option value="bsit">BSIT</option>, <option value="grade12">Grade 12</option>, etc.
document.getElementById('course').addEventListener('change', function(){
if(this.value && this.value.substr(0, 2) === 'bs'){
// if a "bs" option is selected, disable grade 11 and 12 options
document.querySelector('[value="grade11"]').setAttribute('disabled', '');
document.querySelector('[value="grade12"]').setAttribute('disabled', '');
}else{
// remove all disabled attributes from options
var disabledOptions = document.querySelectorAll('option[disabled]'),
i, l = disabledOptions.length;
for(i = 0; i < l; ++i){
disabledOptions[i].removeAttribute('disabled');
}
}
});