Я создал html форму, которая принимает пользовательский ввод и затем загружает его в текстовый файл. Я отключил поле в соответствии с вводом из предыдущего выпадающего поля. Сейчас я загружаю данные формы в текстовом файле. Все, что я хочу, это чтобы файл имел данные из полей, которые включены, а отключенное поле не должно появляться в текстовом файле.
Например, у меня есть два поля «Протокол» и «iSCSI IPs» в моем веб-приложении. Лог c - это, если Protocol == 'iSCSI', тогда 'iSCSI IPs' включен, и я ввожу текст там. Но в случае, когда Протокол не является iSCSI, тогда поле «iSCSI IPs» становится недоступным, в этом сценарии мне не нужны загруженные данные, чтобы иметь поле «iSCSI IPs» (или, в моем случае, в загруженном текстовом файле). У меня есть весь код, так как я не был уверен, как воспроизвести мою проблему с минимальным блоком кода. Спасибо
document.addEventListener('DOMContentLoaded', function() {
const extra = {};
const oForm = document.forms.myForm;
const oSave = document.querySelector('input[name="save"]');
const oSub = document.querySelector('input[name="submit"]');
const oCtrl = document.querySelector('select[name="controller"]');
const oTest = document.querySelector('select[name="test"]');
const oProto = document.querySelector('select[name="protocol"]');
const oiSCSI = document.querySelector('select[name="iSCSIip"]');
const oTmp = document.querySelector('template');
//Validating the input data and handling the changes made by the user
const changehandler = function(e) {
let option = this.options[this.options.selectedIndex];
if (option.hasAttribute('data-extra')) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
if (Object.keys(extra).length == 2) {
let fieldset = oTmp.content.cloneNode(true);
oForm.insertBefore(fieldset, oProto.parentNode.nextSibling)
} else {
if (document.getElementById('extra')) {
fieldset = document.getElementById('extra')
fieldset.parentNode.removeChild(fieldset);
}
}
if (option.hasAttribute('data-extra')) extra[this.name] = this.value;
else {
if (extra.hasOwnProperty(this.name)) delete extra[this.name];
}
//Enabling the protocol dropdown only if the controller is RAID
if (this.name == 'controller') {
if (this.value == 'RAID') oProto.disabled = false
else oProto.disabled = true
}
if (this.name == 'protocol') {
if (this.value == 'iSCSI') oiSCSI.disabled = false
else oiSCSI.disabled = true
}
}
const dialog = function(msg) {
alert(msg);
return false;
}
const savehandler = function(e) {
e.preventDefault();
let valid = true
/*
if( oForm.test.value =='' || oForm.controller.value =='' || oForm.ip.value == '' || oForm.chassis.value == '' || oForm.lo.value == '' || oForm.ro.value == ''){
alert("Please fill all the fields!");
return;
}
else if(oForm.extra_ip1.value == '' || oForm.extra_ip.value == '' || oForm.netmask_ip1.value == '' || oForm.netmask_ip.value == '' || oForm.gateway_ip1.value == '' || oForm.gateway_ip.value == '' ){
alert("Please fill all the additonal required fields!");
return;
}
const ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipformat.test(oForm.ip.value) == false) {
return dialog('Invalid IP Address');
}
else if (ipformat.test(oForm.extra_ip1.value)== false || ipformat.test(oForm.extra_ip.value)== false ){
return dialog('Invalid MC_IP Address');
}
else if (ipformat.test(oForm.netmask_ip1.value)== false || ipformat.test(oForm.netmask_ip.value)== false){
return dialog('Invalid MC_Netmask Address');
}
else if (ipformat.test(oForm.gateway_ip1.value)== false || ipformat.test(oForm.gateway_ip.value)== false ){
return dialog('Invalid MC_Gateway Address');
}
*/
//Creating the data elements to be cpatured in the downloaded yaml file
let data = {
" PDU:": {
"PDU_IP":[' PDU_IP',' '+oForm.ip.value," #PDU IP",' '+'\n'],
"PDU_LEFT":[' PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",' '+'\n'],
"PDU_RIGHT":[' PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", ' '+'\n']
},
" Controller: # Controller settings \n": {
//'Controller Type': oForm.controller.value,
//'Protocol Type': oForm.protocol.value,
//'Chasis Inputs': oForm.chassis.value,
'Controller_ID#1': [" - # Controller A for RBOD/EBOD",'','',''+'\n'],
"iSCSI_IPs_A":[' iSCSI_IPs',' '+[oForm.iSCSIip1.value],"#iSCSI_IPs",''+'\n'],
"HBA_Ports_A":[" HBA_Ports",oForm.hba_ports1.value,'# SAS/Fiber Channel',''+'\n'],
"Netmask IP_A":[" MC_IP",' '+oForm.extra_ip1.value,' # RBOD MC IP',''+'\n'],
"MC_Netmask_A": [" MC_Netmask",' '+oForm.netmask_ip1.value,' # RBOD MC Netmask',''+'\n'],
'MC_Gateway_A':[' MC_Gateway',' '+oForm.gateway_ip1.value,' # RBOD MC Gateway',''+'\n'],
'MC_A': [' MC',' '+oForm.rbod_mc1.value,' # RBOD MC port',''+'\n'],
'SC_A':[' SC',' '+oForm.rbod_sc1.value,' # RBOD SC port',''+'\n'],
'FU_A':[' FU',' '+oForm.rbod_fu1.value,' # RBOD FU port',''+'\n'],
'EC_A':[" EC",' '+oForm.rbod_ec1.value,' # EC port on RBOD or GEM port on JBOD',''+'\n'],
'Controller_ID#3': [" ID",' '+oForm.Controller_ID1.value," #Controller ID, A or B",''+'\n'],
'Controller_ID#2': [" - # Controller B for RBOD/EBOD",'','','',''+'\n'],
"iSCSI_IPs_B":[' iSCSI_IPs', ' '+[oForm.iSCSIip2.value],"#iSCSI_IPs",''+'\n'],
"HBA_Ports_B":[" HBA_Ports: # SAS/Fiber Channel",' '+[oForm.hba_ports.value],'',''+'\n'],
"Netmask IP_B":[" Netmask IP",' '+oForm.extra_ip.value,'',' # RBOD MC IP'+'\n'],
"MC_Netmask_B": [" MC_Netmask", ' '+oForm.netmask_ip.value,' # RBOD MC Netmask',''+'\n'],
'MC_Gateway_B':[' MC_Gateway',' '+oForm.gateway_ip.value,' # RBOD MC Gateway',''+'\n'],
'MC_B': [' MC',' '+oForm.rbod_mc.value,' # RBOD MC port',''+'\n'],
'SC_B':[' SC',' '+oForm.rbod_sc.value,' # RBOD SC port',''+'\n'],
'FU_B':[' FU',' '+oForm.rbod_fu.value,' # RBOD FU port',''+'\n'],
'EC_B':[" EC",' '+oForm.rbod_ec.value,' # EC port on RBOD or GEM port on JBOD',' '+'\n'],
'Controller_ID#4': [" ID", ' '+oForm.Controller_ID.value," #Controller ID, A or B",''+'\n']
},
};
//Crating the format of the data
let payload = '';
payload+= ' - # UUT 0 configuration'+'\n - # Chassis 0 configuration'+String.fromCharCode(10);
const addToPayload = (object, whitespace) => {
for (const key of Object.keys(object)) {
payload += key + '\n';
const details = object[key];
for (const key1 of Object.keys(details)){
const value = details[key1];
str=value[0];
com=value[2];
val=value[1];
whitespace=value[3];
var input= JSON.stringify(val);
//output.HBA_Ports = input.HBA_Ports[0].split(',');
//var array = string.split(',');
if (Array.isArray(val)){
payload += whitespace + str + ':' + com + input;//JSON.stringify(val);
console.log(payload)
}
else if (val==oForm.hba_ports1.value){
var out= val.split(',');
payload += whitespace + str + ':' + com + JSON.stringify(out);
}
else{payload += whitespace + str + ':' + com + val;}
}
}
}
addToPayload(data, ' ' );
//Converting the data into a yaml file and downloading it on button click
const blob = new Blob([payload], {
type: 'text/yaml'
});
var file = oForm.test.value + "_" + oForm.protocol.value + "_UUT_Config" + '.yaml';
let link = document.createElement('a');
link.download = file;
if (window.webkitURL != null) {
link.href = window.webkitURL.createObjectURL(blob);
} else {
link.href = window.URL.createObjectURL(blob);
link.style.display = "none";
document.body.appendChild(link);
}
link.click();
}
oCtrl.addEventListener('change', changehandler);
oTest.addEventListener('change', changehandler);
oSave.addEventListener('click', savehandler);
})
//To Disable the text boxes based on the specific inputs i.e. HBA Ports and iSCSI IPs
function EnableDisableTextBox(abc) {
var selectedValue = abc.options[abc.selectedIndex].value;
var txt1 = document.getElementById("ip1");
var txt2 = document.getElementById("ip2");
var hbadisabled1 = document.getElementById("hba");
var hbadisabled2 = document.getElementById("hba1");
txt1.disabled = selectedValue == 'iSCSI' ? false : true;
txt2.disabled = selectedValue == 'iSCSI' ? false : true;
hbadisabled1.disabled = selectedValue == 'iSCSI' ? true : false;
hbadisabled2.disabled = selectedValue == 'iSCSI' ? true : false;
if (!txt1.disabled) {
txt1.focus();
}
else if (!txt2.disabled){
txt2.focus();
}
else if (!hbadisabled1.disabled) {
hbadisabled1.focus();
}
else if (!hbadisabled2.disabled){
hbadisabled2.focus();
}
}
<!DOCTYPE html>
<html>
<head>
<title>Save form Data in a Text File using JavaScript</title>
<!--<h1>User Information </h1>-->
<style>
html, html * {
box-sizing:border-box;
border-color: teal;
font-family:calibri;
}
html{
background : radial-gradient(rgba(33, 34, 34, 0.5),rgba(46, 45, 45, 0.5))
}
input[type=button],
input[type=submit]{
padding:1rem;
}
input[type=number]{
width: 240px;
height: 35px;
font-size: 18px;
}
input[type=text],
textarea,
select {
font: 17px Calibri;
width: 100%;
padding: 12px;
border: 1px solid rgb(19, 18, 18);
border-radius: 4px;
color:teal
}
fieldset{
border:none;
padding: 10px;
overflow: hidden;
color: rgb(16, 8, 32);
font-size: 25px;
font-style: initial;
font-family: 'Times New Roman', Times, serif;
}
#extra{border:2px solid black; background:whitesmoke; border-radius:1rem;box-shadow:0 0 5px black;width:calc(100% - 24px);margin:auto;float:none;clear:both;text-indent: 50px;}
#extra h6{margin:0}
#extra style
.invalid{border:2px solid red!important;background:rgba(255,0,0,0.1)}
</style>
<script src="script.js"></script>
</head>
<body>
<template>
<fieldset id='extra'>
<h6>Additional Details Required</h6>
<label for='Controller_ID1'>Controller_ID:</label>
<select name='Controller_ID1' required>
<option value=""> - Select the Controller ID - </option>
<option value='A'>A </select>
<label for='iSCSI1'>iSCSI IPs:</label><input type='text' name='iSCSIip1' id="ip1" placeholder='Enter iSCSI ips' disabled="disabled" required />
<label for='HBA_Ports_A'>HBA_Ports:</label><input type='text' id="hba" name='hba_ports1' placeholder='Enter the HBA Ports' />
<label for='MC_IP_A'>MC_IP:</label><input type='text' name='extra_ip1' placeholder='Enter the MC_IP' />
<label for='MC_Netmask_A'>MC_Netmask:</label><input type='text' name='netmask_ip1' placeholder='Enter the MC_Netmask' />
<label for='MC_Gateway_A'>MC_Gateway:</label><input type='text' name='gateway_ip1' placeholder='Enter the MC_Gateway' />
<label for='MC_A'>MC:</label><input type='text' name='rbod_mc1' placeholder='Enter the MC Port' />
<label for='SC_A'>SC:</label><input type='text' name='rbod_sc1' placeholder='Enter the SC Port' />
<label for='FU_A'>FU:</label><input type='text' name='rbod_fu1' placeholder='Enter the FU Port' />
<label for='EC_A'>EC:</label><input type='text' name='rbod_ec1' placeholder='Enter the EC Port' />
<br>
<br>
<label for='Controller_ID2'>Controller_ID:</label>
<select name='Controller_ID' required>
<option value=""> - Select the Controller ID - </option>
<option value='B'>B </select>
<label for='iSCSI2'>iSCSI IPs:</label><input type='text' name='iSCSIip2' id="ip2" placeholder='Enter iSCSI ips' disabled="disabled" />
<label for='HBA_Ports'>HBA_Ports:</label><input type='text' id="hba1" name='hba_ports' placeholder='Enter the HBA Ports' />
<label for='MC_IP'>MC_IP:</label><input type='text' name='extra_ip' placeholder='Enter the MC_IP' />
<label for='MC_Netmask'>MC_Netmask:</label><input type='text' name='netmask_ip' placeholder='Enter the MC_Netmask' />
<label for='MC_Gateway'>MC_Gateway:</label><input type='text' name='gateway_ip' placeholder='Enter the MC_Gateway' />
<label for='MC'>MC:</label><input type='text' name='rbod_mc' placeholder='Enter the MC Port' />
<label for='SC'>SC:</label><input type='text' name='rbod_sc' placeholder='Enter the SC Port' />
<label for='FU'>FU:</label><input type='text' name='rbod_fu' placeholder='Enter the FU Port' />
<label for='EC'>EC:</label><input type='text' name='rbod_ec' placeholder='Enter the EC Port' />
</fieldset>
</template>
<form name='myForm' method='POST' >
<fieldset>
<label for='Controller Type'><strong>Controller Type </strong></label>
<select name='controller' required>
<option value=""> - Select the Controller - </option>
<option data-extra=true value='RAID'>RAID
<option data-extra=true value='JBOD'>JBOD
<option data-extra=true value='AP'>AP
</select>
</fieldset>
<fieldset>
<label for='Test Type'><strong>Test Type</strong></label>
<select name='test' required>
<option value=""> - Select The Test - </option>
<option data-extra=true value='BFT'>BFT
<option data-extra=true value='CTO'>CTO
<option data-extra=true value='RAID Generic'>RAID Generic
<option data-extra=true value='Port Check' >Port Check
<option data-extra=true value='FW Generic' >FW Generic
<option data-extra=true value='JBOD Generic' >JBOD Generic
</select>
</fieldset>
<!-- insert templated additional details here -->
<fieldset>
<label for='Protocol Type'><strong> Protocol Type</strong></label>
<select name='protocol' id="abc" onchange="EnableDisableTextBox(this);" required>
<option value=""> - Select The Protocol - </option>
<option data-extra=true value='SAS'>SAS</option>
<option data-extra=true value='iSCSI'>iSCSI</option>
<option data-extra=true value='FC'>FC</option>
</select>
</fieldset>
<fieldset>
<label for='IP Address'><strong> IP Address </strong></label>
<input type='text' name='ip' placeholder='Enter your IP address' required />
</fieldset>
<fieldset>
<label for='Left Outlets'><strong>Left Outlets </strong></label>
<input type='number' name='lo' placeholder='Enter left outlets' required />
</fieldset>
<fieldset>
<label for='Right Outlets'><strong>Right Outlets</strong></label>
<input type='number' name='ro' placeholder='Enter right outlets' required />
</fieldset>
<fieldset>
<label for='Chasis Input'><strong>Chasis Inputs</strong></label>
<input type='number' name='chassis' placeholder='Enter Number of Chasis' required />
</fieldset>
<fieldset>
<input type='submit' name='save' value='Save data to file' />
</fieldset>
</form>
</body>
</html>