JSFiddle - React, Tailwind, and code Playground
by wisegorilla
HTML
<div class="home-form">
<form id="home-contact-form" action="/gg" method="post">
<?php wp_nonce_field( 'my_action_nonce' ); ?>
<div class="form-field"><input type="text" name="name" id="name" placeholder="Name" required /></div>
<div class="form-field"><input type="email" name="email" id="email" placeholder="Email" required /></div>
<div class="form-field"><input type="tel" name="mobile" id="mobile" placeholder="Mobile Number" required /></div>
<div class="project-locations">
<div class="form-field">
<select class="location" name="location" id="locations">
<option hidden>Choose your prefered location</option>
<option value="Bangalore">Bangalore</option>
<option value="Chennai">Chennai</option>
<option value="Coimbatore">Coimbatore</option>
</select>
</div>
<div class="form-field">
<select class="projects" name="projects" id="projects" disabled>
<option hidden>Choose your prefered project</option>
</select>
</div>
</div>
<div class="form-field"><input type="textarea" placeholder="Tell us about your desired property"></div>
<input type="hidden" name="action" value="my_action" />
<button type="submit">Submit</button>
</form>
<div class="message"></div>
</div>
CSS
.home-form {
width: 50%;
margin: auto;
}
.home-form input, .home-form select {
border: 1px solid #ccc;
width: 100%;
padding: 10px;
margin: 10px;
box-sizing: border-box;
}
.project-locations {
display: flex;
}
.home-form button {
background-color: #1EA69A;
border: none;
color: #fff;
width: 100%;
padding: 10px;
margin: 10px;
border-radius: 3px;
}
JavaScript
(function ($) {
var projectsList = {
'Bangalore': [
'project 1',
'project 2',
'project 3'
],
'Chennai': [
'project 3',
'project 4',
'project 5'
],
};
function populateProjects(projectArray) {
let projects = document.getElementById('projects');
let options = document.querySelectorAll('#projects option');
// Clear existing options
options.forEach(o => o.remove());
// Add the new options
for (x of projectArray) {
let opt = document.createElement('option');
opt.innerHTML = x;
opt.value = x;
projects.appendChild(opt);
}
}
document.getElementById('locations').addEventListener("change", function() {
document.getElementById('projects').disabled = false;
let locationValue = locations.value;
if (locationValue === 'Bangalore') {
populateProjects(projectsList.Bangalore);
} else if (locationValue === 'Chennai') {
populateProjects(projectsList.Chennai);
}
});
$('#home-contact-form').submit(function(evt) {
evt.preventDefault();
var ajaxurl = 'https://webhook.site/d42335ce-5133-4fc9-b5b9-5ac8a22019f8';
var formData = $( this ).serialize();
$.ajax({
action: 'make_booking',
data: formData,
type: 'post',
url: ajaxurl,
success: function(data) {
console.log(data);
$(".home-form .message").text("Form sent successfully").css("color", "green");
},
error: function() {
$(".home-form .message").text("Error during submision please contact us").css("color", "red");
}
});
});
})(jQuery);