я могу получить значения данных формы, когда я вызываю класс javascript в первом случае, но не в последующих - PullRequest
0 голосов
/ 12 января 2020

Я знаю, что отправил довольно длинный код и мог бы его сократить, однако я чувствую, что лучше поставить все это, потому что это связано.

Я потратил последние четыре дни, выясняя, что может быть не так, безуспешно. Я даже пытался отредактировать код в chrome инструментах разработчика и безуспешно вставлять разрывы строк. У меня есть четыре варианта типов свойств, которые пользователь может выбрать при посещении нашего сайта. т.е. дом или земля. Это показано ниже.

<div class="container">
<div class="house">            
<img src="../house_image.jfif" alt="house image" class="square-image" id="house-image">
<h3 class="list-type" id ="list-type-house">Looking for a house to let, buy or fullyFurnished ?</h3>
</div>
<div class="land">                    
<img src="../land_image.jpg" alt="land image" class="square-image">
<h3 class="list-type" id ="list-type-land">Looking for Land or a plot ?</h3>
</div>
<div class="hotel">                        
<img src="../hotel_image.jfif" alt="hotel image" class="square-image">
<h3 class="list-type" id ="list-type-hotel">Looking for  hotel ?</h3>
</div>
<div class="godown">                        
<img src="../godown_image.jpg" alt="godown image" class="square-image">
<h3 class="list-type" id ="list-type-godown">Looking for a commercial space or a down ?</h3>
</div>             
</div><!---container-->

когда пользователь щелкает дом, например, я слушаю щелчок, используя прослушиватель addEvent.

, затем я запускаю этот код

const propertyChoice = document.querySelectorAll('.list-type');

for (const propertyType of propertyChoice) {
propertyType.addEventListener('click',propertyChoiceObj);

}

function propertyChoiceObj(e) {
e.stopPropagation();
const choice = e.target.id;     
switch(choice) {
case "list-type-house":
App.init();
break;
case "list-type-land":
listTypeLand();
break;
case "list-type-hotel":
listTypeHotel();
break;
case "list-type-godown":
listTypeGodown();
break;

default:
alert("select one type of property to list");
break;
} 

}

Класс App.init, приведенный выше, инициализирует класс, показанный ниже, называемый modalOne, класс Modal one запускает метод listTypeHouse, который открывает модальное всплывающее окно. модальное всплывающее окно, которое создает наложение на всю страницу, управляется css, как показано ниже.

позвольте мне начать с экземпляров класса

class ModalPopUp{
constructor(modal_wrapper,modal_window,overlay,modal_close,expand,submit,formId){
this.modalWrapper = document.getElementById(modal_wrapper);
this.modalWindow  = document.getElementById(modal_window);
this.overlay = overlay;
this.modalClose = modal_close;
this.expand = expand;
this.clicK = 'click';
this.keyDown= 'keydown';
this.submit = submit;
this.formId = formId;
document.getElementById(this.modalClose).addEventListener(this.clicK, this.closeModal.bind(this, 
this.modalWrapper));
document.getElementById(this.expand).addEventListener(this.clicK, expandModalTwo.bind(this));                               
document.getElementById(this.formId).addEventListener(this.submit, this.validate);                
document.addEventListener(this.clicK, this.clickHandler.bind(this)); 
document.addEventListener(this.keyDown, this.keyHandler);
}

listTypeHouse(e){
this.modalWrapper.className = this.overlay;                         
this.modalWindow.style.marginTop = (-this.modalWindow.offsetHeight)/2 + "px";
this.modalWindow.style.marginLeft = (-this.modalWindow.offsetWidth)/2 + "px";

};

closeModal(th)
{
this.modalWrapper.className = "";
};

clickHandler(e) {                           
console.log(e);                             
if(e.target.tagName == "DIV") {                                     
if(e.target.id != this.modal_window){
modal_wrapper.className = "";                       

}
e.preventDefault();  
}                    
};

keyHandler (e) {                 
if(e.keyCode == 27) {
modal_wrapper.className = "";
e.preventDefault();
}
}

validate(e){                
e.preventDefault();                                                                           
const formData = new FormData(this)        
for (const formDat of formData) {
console.log(formDat);                        

}
}
}



function expandModalTwo(e){
e.preventDefault();
console.log('expand model'); 
e.stopPropagation();
if(this.overlay == 'overlay'){ 
this.modalWrapper.className = "";           
let modalTwo = new 
ModalPopUp('modal_wrapper_two','modal_window_two','overlay_two','modal_close_two','expand- 
two','submit-two','modal_feedback_two');
modalTwo.listTypeHouse();
}else if(this.overlay == 'overlay_two'){            
this.modalWrapper.className = "";
let modalThree = new 
ModalPopUp('modal_wrapper_three','modal_window_three','overlay_three','modal_close_three','expand- 
three','submit-three','modal_feedback_three');
modalThree.listTypeHouse();
} 
}

class App {
static init(){
let modalOne = new ModalPopUp('modal_wrapper','modal_window','overlay','modal_close','expand','submit','modal_feedback');
modalOne.listTypeHouse();
}
}

Форма HTML, которая открывается modalPopup показано ниже. Я удалил некоторые формы ввода, чтобы сделать его короче.

<div id="modal_wrapper" class="modal_wrapper">
<div id="modal_window">
<div style="text-align: right;"><a id="modal_close" href="#">close <b>X</b></a></div>
<p class="better-exp-p" id="better-exp-p">Select House Type:</p>
<form id="modal_feedback" method="POST" action="<?php echo url_for('/landing_page.php') ;?>">
<span class="buy-let-furnished">
<label for="buy" class="buy-let-furnished-label">Buy</label>
<input class="selector" id="buy" name="buy-let-furnished" type="radio" value="1">
<label for="let" class="buy-let-furnished-label">Let</label>
<input class="selector" id="let" name="buy-let-furnished" type="radio" value="2">
<label for="let" class="buy-let-furnished-label">Fully Furnished</label>
<input class="selector" id="furnished" name="buy-let-furnished" type="radio" value="3">
</span>
<button type="submit" class="better-exp-p submit" id="submit"  name="feedbackForm" value="submit">Search</button>           
<input type="button" id="expand" name="feedback-expand-Form" value="More Detailed Search">
</form>

</div> <!-- #modal_window -->
</div> <!-- #modal_wrapper -->


<!-- modal two ----------------------------------------->
<div id="modal_wrapper_two">
<div id="modal_window_two">
<div style="text-align: right;"><a id="modal_close_two" href="#">close <b>X</b></a></div>
<p class="better-exp-p-two" id="better-exp-p-two">Select more options here:</p>
<form id="modal_feedback_two" method="POST" action="<?php echo url_for('/landing_page.php') ;?>">
<span>
<label for="swimming-Pool" class="check-boxes">Swimming Pool</label>
<input class="selector check " id="swimming-Pool" name="swimming-Pool" type="checkbox" value="1">
</span>                    
<span>
<label for="Fiber-Cable" class="check-boxes">Fibre cable</label>
<input class="selector check" id="Fiber-Cable" name="Fiber-Cable" type="checkbox"  value="1">
</span>                    

<button class="better-exp-p-two submit" id="submit-two" type="submit" name="feedbackForm-two" 
value="Search"> Search </button>            
<input type="button" id="expand-two" name="feedback-expand-Form-two"  value="Narrow Down your search 
further">

</form>
</div> <!-- #modal_window_two -->
</div> <!-- #modal_wrapper_two -->

<!-- modal three ----------------------------------------->
<div id="modal_wrapper_three">
<div id="modal_window_three">
<div style="text-align: right;"><a id="modal_close_three" href="#">close <b>X</b></a></div>
<h3 class="better-exp-p-three" id="better-exp-p-three">Select more options here:</h3>
<form id="modal_feedback_three" method="POST" action="#" accept-charset="UTF-8">
<section class="modal-feedback-three-top">
<span>
<label for="bathrooms" class="check-boxes">Bath Rooms</label>
<input class="selector" id="bathrooms" name="bathrooms" type="text" value="">
</span>                    
<span>
<label for="bed-with-bath" class="text-boxes">Bedrooms with Bathrooms</label>
<input class="selector" id="bedwithbath" name="bedwithbath" type="text"  value="">
</span>

</section>
<section class="modal-feedback-three-search">

<button id="submit-three" type="submit" name="feedback-expand-Form-three" 
value="submit">submit</button>
<input type="hidden" id="expand-three" name="feedback-expand-Form-three"  value=""><!-- hidden to 
allow use of class-->
</section>
</form>
</div> <!-- #modal_window_three -->
</div> <!-- #modal_wrapper_three -->

Простой класс css, открывающий модальное всплывающее окно, показан ниже.

/* the first modal pop up */

#modal_wrapper.overlay::before {
content: " ";
width: 100%;
height: 100%;
position: fixed;
z-index: 100;
top: 0;
left: 0; 
background: rgba(0,0,0,0.7);
}

#modal_window {
display: none;
z-index: 200;
position: fixed;
left: 50%;
top: 50%;
width: 400px;
overflow: auto;
padding: 10px 20px;
background: #fff;
border: 5px solid #999;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}

#modal_wrapper.overlay #modal_window {
display: block;
}

#modal_feedback{
display: grid;
justify-content: center;
align-items: center;  
grid-auto-rows: 2.5em;  
font-size: medium;  
background-color:  rgb(235, 236, 238); 
color:  rgb(219, 76, 76);  
font-weight: normal;
justify-items: center;

}

/* .buy-let-furnished{
display: grid;
/* grid-template-columns: 20px auto; 
} */

.better-exp-p{
color: brown;
font-size: large;
font-weight: normal;
display: flex;
justify-content: center;


}

#expand{
color: rgb(85, 24, 24);
font-size: medium;
font-weight: small;
display: flex;
justify-content: center;
text-align: center;

}
.min-max-cost{
display: grid;
grid-auto-flow: column;
grid-auto-columns: repeat(auto-fill, 100px);
justify-items: center;
align-items: center;

}


.Bedrooms{
display: grid;
grid-auto-flow: column;
justify-items: center;
align-items: center;
}
.complete-offplan{
display: grid;
grid-auto-flow: column;
justify-items: center;
align-items: center;

}
.gated-slone-apart{
display: grid;
grid-auto-flow: column;
justify-items: center;
align-items: center;

}
.buy-let-furnished{
display: grid;
grid-auto-flow: column;
justify-items: center;
align-items: center;

}
/* second modal pop up */
#modal_wrapper_two.overlay_two::before {
content: " ";
width: 100%;
height: 100%;
position: fixed;
z-index: 100;
top: 0;
left: 0; 
background: rgba(0,0,0,0.7);
}

#modal_window_two {
display: none;
z-index: 200;
position: fixed;
left: 50%;
top: 50%;
width: 400px;
overflow: auto;
padding: 10px 20px;
background: #fff;
border: 5px solid #999;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}

#modal_wrapper_two.overlay_two #modal_window_two {
display: block;
}


#modal_feedback_two{
display: grid;
justify-content: center;
grid-template-columns: 1fr 1fr;
align-items: center;  
grid-auto-rows: 2.5em;  
font-size: medium;  
background-color:  rgb(235, 236, 238); 
color:  rgb(219, 76, 76);  
font-weight: normal;
justify-items: start;

}

.area{
display: grid;

} 
.better-exp-p-two{
display: grid;
grid-column:span 2 ;
color: brown;
font-size: large;
font-weight: normal;
align-self:center;
justify-self: center;
}
#expand-two{
color: rgb(85, 24, 24);
font-size: medium;
font-weight: small;
display: grid;
grid-column:span 2 ;
align-self:center;
justify-self: center;
}

/* third modal pop up */
#modal_wrapper_three.overlay_three::before{
content: " ";
width: 100%;
height: 100%;
position: fixed;
z-index: 100;
top: 0;
left: 0; 
background: rgba(0,0,0,0.7);
}

#modal_window_three {
display: none;
z-index: 200;
position: fixed;
left: 50%;
top: 50%;
width: 400px;
overflow: auto;
padding: 10px 20px;
background: #fff;
border: 5px solid #999;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}

#modal_wrapper_three.overlay_three #modal_window_three {
display: block;
}
#test{

display: none;
}

.modal-feedback-three-top{
display: grid;
justify-content: center;
grid-template-columns: auto ;
align-items: center;  
grid-auto-rows: 2.5em;  
font-size: medium;  
background-color:  rgb(235, 236, 238); 
color:  rgb(219, 76, 76);  
font-weight: normal;
justify-items: start;

}
.modal-feedback-three-top 
.selector{

max-width: 100px;

}

.modal-feedback-three-lower{
display: grid;
grid-template-columns: 1fr;
/* justify-content: center;
align-items: center; */

}

Код работает Хорошо, когда пользователь нажимает кнопку отправки с идентификатором отправки, я получаю значения данных формы. когда пользователь нажимает кнопку расширения, чтобы отобразить вторую всплывающую модальную форму, когда я пытаюсь отправить туда форму, используя идентификатор submit-two, форма внезапно исчезает, как если бы она была отправлена, и я не получаю значения данных формы. Та же проблема происходит в модальной три, где я не получаю значения формы. Я сделал три необязательных всплывающих формы, чтобы пользователь мог отправить форму на любой стадии, которую он заполняет, например, из трех, кроме того, я не хотел иметь очень большую форму ввода, которая заставила бы пользователя чувствовать, что он запрашивает слишком много информации. .

Код доступен здесь

https://codepen.io/gitaumartin/pen/QWwrYgx?editors=1111

...