How to get the div id's of this form? - javascript

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;
}

Related

Best way to reuse JavaScript for common html elements

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')

how to show new select input only when select specific option and when select another options don't show by jquery? laravel

i'm trying to show new select input contains (states) options, when user select specific option a (USA) country, and when select another country non (USA) don't show the states select options i want in this case still hidden.
Route
Route::get('/ajax-form', [AjaxController::class, 'index'])->name('ajax.index');
Route::get('/getState/{id}', [AjaxController::class, 'getState'])->name('ajax.state');
Controller
class AjaxController extends Controller
{
public function index()
{
$countries['data'] = Country::orderby('name')
->select('id', 'name')
->get();
return view('ajax.index', compact('countries'));
}
public function getState($countryId = 0)
{
$states['data'] = State::orderby('name')
->select('id', 'name')
->where('country_id', $countryId)
->get();
return response()->json($states);
}
Blade form with script:
#extends('layouts.app')
#section('form')
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
#if ($countries['data'] && $countries['data']->count() > 0)
#foreach ($countries['data'] as $country)
<option value="{{ $country->id }}">{{ $country->name }}</option>
#endforeach
#endif
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
#stop
#section('script')
<script type="text/javascript">
$(document).ready(function () {
$('#inputCountry').change(function() {
var id = $(this).val();
// Empty the States dropdown without first
$('#stateShow').show();
$('#inputState').find('option').not(':first').remove();
// ajax request
$.ajax({
url: 'getState/' + id,
type:'get',
dataType: 'json',
success: function(response) {
var len = 0;
if(response['data'] != null) {
len = response['data'].length;
}
if(len > 0) {
// Read data in the state option that related with country
for(var i = 0; i < len; i++) {
var id = response['data'][i].id;
var name = response['data'][i].name;
var option = "<option value='" + id + "'>" + name + "</option>";
$('#inputState').append(option);
}
}
}
});
});
});
</script>
#stop
the above script doing, when i select any country, the hidden (states) select is shown, i want it shows only when i select (USA) and non that still hidden
could you help me
In your inputCountry select-box i am assuming {{ $country->name }} is country name so you can use $(this).find("option:selected").text() to get this value and then compare it with USA if they are equal show your div else hide it.
Demo Code :
$('#inputCountry').change(function() {
var id = $(this).val();
var text = $(this).find("option:selected").text().trim() //get text
if (text == "USA") {
$('#stateShow').show(); //show
$('#inputState').find('option').not(':first').remove();
//your ajax call put here ....
} else {
$('#stateShow').hide(); //hide
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<div class="form-row">
<div class="form-group col-md-12">
<label for="inputCountry">Country</label>
<select class="country" id="inputCountry" class="form-control">
<option selected>Choose...</option>
<option value="{{ $country->id }}">Abc</option>
<option value="{{ $country->id }}">USA</option>
</select>
</div>
</div>
<div id="stateShow" class="form-row hidden">
<div class="form-group col-md-6">
<label for="inputState">State</label>
<select id="inputState" class="form-control">
<option value='0' selected>Choose...</option>
</select>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>

How can I dynamically update materialize <select>?

I have a select tag with several options. I am using materizlizecss select, and I would like to use javascript to disable certain options based on certain conditions. I have read another post on how to do this, but I need to do it without jquery. When I try it, nothing happens. No errors or warnings in the console either.
<form id="code-form">
<h4 style="color: black;">Generate Code</h4>
<div class="input-field">
<select name="security-select" id="security-select">
<option style="display: none;" id="webmaster-value" value="1">Webmaster</option>
<option id="scoutmaster-value" value="2">Scoutmaster</option>
<option id="general-admin-value" value="3">General Admin</option>
<option id="spl-value" value="4">Senior Patrol Leader</option>
<option selected id="standard-user-value" value="5">Standard User</option>
</select>
</div>
<button class="btn deep-purple" id="add-code">Generate Code</button>
</form>
.
if (security == '2') {
document.querySelector('#webmaster-value').setAttribute('disabled', 'disabled')
}
You have to Re-Initialize a select field after edited it
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
});
document.getElementById("change-code").addEventListener("click", function () {
document.querySelector('#webmaster-value').setAttribute('disabled', 'disabled');
// Re-Initialize select
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<form id="code-form">
<h4 style="color: black;">Generate Code</h4>
<div class="input-field">
<select name="security-select" id="security-select">
<option style="display: none;" id="webmaster-value" value="1">Webmaster</option>
<option id="scoutmaster-value" value="2">Scoutmaster</option>
<option id="general-admin-value" value="3">General Admin</option>
<option id="spl-value" value="4">Senior Patrol Leader</option>
<option selected id="standard-user-value" value="5">Standard User</option>
</select>
</div>
<button type="button" class="btn deep-purple" id="change-code">Press to disable</button>
</form>

HTML Form Select Dropdown Options and Hidden Form Fields Not showing in PHP Form using JS Script

Recently i set up a script in JS with help from Stack to show a Form Row labled "other" when i select an option called "Other" from a dropdown option above. Example is below. This works well for one dropdown. But as soon as I add another dropdown Menu and "other" form row the JS code breaks and neither the 1st or 2nd Form Dropdown Options get posted to the Database and the form row "other" does not show. I hope i have explained the issue correctly. I essentially want one JS script to repeat for all dropdown forms so when "other" option value is selected i want the form row "other" to display below so custom data can be typed in. Using Bootstrap 4.3.1 with all JS querir plugins working. The datbase is connected with no issues posting data when its just a text field. So i was hoping someone might have work around and i will have a lot of dropdowns with the "Other" form row posting different form data in to the database. Many thanks.
<script>
function handleSelect() {
document.getElementById("other").value = document.getElementById("mySelect").value;
var selected = document.getElementById("mySelect").value;
var details = document.getElementById("other-details");
if (selected === "") {
details.classList.remove("d-none");
details.classList.add("d-block");
} else {
details.classList.remove("d-block");
details.classList.add("d-none");
}
}
</script>
<div class="form-row">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<label class="control-label custom_label col-xs-12">Cemetery</label>
<select name="cemetery" class="form-control" id="mySelect" onchange="handleSelect();">
<option value="select" selected="selected">Select Cemetery</option>
<option value="Akatarawa">Akatarawa</option>
<option value="Taita">Taita</option>
<option value="Wainuiomata">Wainuiomata</option>
<option value="Whenua Tapu">Whenua Tapu</option>
<option value="Makara">Makara</option>
<option value="Karori">Karori</option>
<option value="St Johns">St Johns</option>
<option value="Awa Tapu">Awa Tapu</option>
<option value="Paraparaumu">Paraparaumu</option>
<option value="">Other</option>
</select>
</div>
</div>
<div class="form-row d-none" id="other-details">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<input type="text" id="other" class="form-control" name="cemetery" />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<label class="control-label custom_label col-xs-12">Headstone - Stone Color</label>
<select name="headstone_color" class="form-control" id="mySelect" onchange="handleSelect();">
<option value="headstone_color" selected="selected">Select Headstone - Stone Color</option>
<option value="Black">Black</option>
<option value="African Grey">African Grey</option>
<option value="Platinum Blue">Platinum Blue</option>
<option value="Blue Pearl">Blue Pearl</option>
<option value="Emerald Pearl">Emerald Pearl</option>
<option value="White Pearl">White Pearl</option>
<option value="Imperial Red">Imperial Red</option>
<option value="Balmoral Red">Balmoral Red</option>
<option value="G603-Chinese White/Grey">G603-Chinese White/Grey</option>
<option value="">Other</option>
</select>
</div>
</div>
<div class="form-row d-none" id="other-details">
<div class="form-group col-md-6 offset-md-3 mx-auto">
<input type="text" id="other" class="form-control" name="headstone_color" />
</div>
</div>
Please check the select id. both of the select has the same id as myselect. The id must be unique. So please make your code generic and use some unique ids.
Thanks
Something like this?
<script>
function handleSelect() {
document.getElementById("other1").value = document.getElementById("mySelect1").value;
var selected = document.getElementById("mySelect1").value;
var details = document.getElementById("other-details1");
document.getElementById("other2").value = document.getElementById("mySelect2").value;
var selected = document.getElementById("mySelect2").value;
var details = document.getElementById("other-details2");
if (selected === "") {
details.classList.remove("d-none");
details.classList.add("d-block");
} else {
details.classList.remove("d-block");
details.classList.add("d-none");
}
}
</script>
and so on ??

Hiding fields in a form based on selected input in drop down using angular js

We are trying to hide few fields based in the form structure based another selection in the same form field. Here the form is generated based on input from the user using loop (ng-repeat) and is not hard coded.
In the above image if the data source is chosen as S3 then the below two fields should not be visible. If it is chosen as Redshift then it should be visible.
<!-- Block Modified to get additional tag details -->
<div ng-repeat="item in metadataGovernance">
<awsui-control-group validation-message="" label="{{item.governance === 'Required' ? displayName(item.tag) + '*' : displayName(item.tag)}}">
<awsui-textfield ng-hide="item.allowedInputs.length>0" name="{{item.tag}}" data-disabled="false" ng-model="item.value"></awsui-textfield>
<select ng-show="item.allowedInputs.length>0" ng-model="item.value" class="awsui-textfield">
<option value="" selected="selected">Choose one</option>
<option ng-repeat="input in item.allowedInputs" value="{{input}}">{{input}}</option>
</select>
<div class="hoverDesc awsui-button-icon awsui-icon question-circle" style="float: right;margin-left: -67px;margin-right: -28px;">
<span class="hoverDescText">{{item.description}}</span>
</div>
</awsui-control-group>
</div>
<!-- End of Block Modified to get additional tag details -->
!-- Block Modified to get additional tag details -->
<div ng-repeat="item in metadataGovernance">
<awsui-control-group validation-message="" label="{{item.governance === 'Required' ? displayName(item.tag) + '*' : displayName(item.tag)}}">
<awsui-textfield ng-hide="item.allowedInputs.length>0" name="{{item.tag}}" data-disabled="false" ng-model="item.value"></awsui-textfield>
<div ng-if="item.value == 'Redshift'">
<select ng-model="item.value" class="awsui-textfield">
<option value="" selected="selected">Choose one</option>
<option ng-repeat="input in item.allowedInputs" value="{{input}}">{{input}}</option>
</select>
</div>
<div class="hoverDesc awsui-button-icon awsui-icon question-circle" style="float: right;margin-left: -67px;margin-right: -28px;">
<span class="hoverDescText">{{item.description}}</span>
</div>
</awsui-control-group>
</div>
Use ng-if
<div ng-repeat="item in metadataGovernance">
<awsui-control-group validation-message="" label="{{item.governance === 'Required' ? displayName(item.tag) + '*' : displayName(item.tag)}}">
<awsui-textfield ng-hide="item.allowedInputs.length>0" name="{{item.tag}}" data-disabled="false" ng-model="item.value"></awsui-textfield>
<select ng-if="(item.allowedInputs.length > 0) || item.value!== 'S3'" ng-model="item.value" class="awsui-textfield">
<option value="" selected="selected">Choose one</option>
<option ng-repeat="input in item.allowedInputs" value="{{input}}">{{input}}</option>
</select>
<div class="hoverDesc awsui-button-icon awsui-icon question-circle" style="float: right;margin-left: -67px;margin-right: -28px;" ng-if="item.value!== 'S3'">
<span class="hoverDescText">{{item.description}}</span>
</div>
</awsui-control-group>
</div>
Put a ng-show/ng-hide directive and give a condition like ng-show="item.value !== 'S3'"
<!-- Block Modified to get additional tag details -->
<div ng-repeat="item in metadataGovernance">
<awsui-control-group validation-message="" label="{{item.governance === 'Required' ? displayName(item.tag) + '*' : displayName(item.tag)}}">
<awsui-textfield ng-hide="item.allowedInputs.length>0" name="{{item.tag}}" data-disabled="false" ng-model="item.value"></awsui-textfield>
<select ng-show="(item.allowedInputs.length > 0) || item.value!== 'S3'" ng-model="item.value" class="awsui-textfield">
<option value="" selected="selected">Choose one</option>
<option ng-repeat="input in item.allowedInputs" value="{{input}}">{{input}}</option>
</select>
<div class="hoverDesc awsui-button-icon awsui-icon question-circle" style="float: right;margin-left: -67px;margin-right: -28px;" ng-show="item.value!== 'S3'">
<span class="hoverDescText">{{item.description}}</span>
</div>
</awsui-control-group>
</div>
<!-- End of Block Modified to get additional tag details -->

Categories