Dynamically create or remove form elements - javascript

I'm creating a Dynamic Form Elements in which I have to add multiple dependents.
My code is below.
In my project, I have to add at least one dependent which I have created using HTML, but user is allowed to add as much as the user wants, therefore I am using jQuery for this and creating the same form dynamically, on user button click, and also user have the choice to remove it.
I have applied some validation too, before adding up a new dependent, the user must fill out all the fields on a click of Add Dependant button. Further, on Add Dependant button I'm just validating the previous form using counter.
I'm using a Counter variable and checking the last added form using it, and incrementing it when user have created a form, and on remove I'm just decrementing it.
On Next button, I'm validating the whole form controls, because user may have deleted or left any field empty, therefore I'm checking this on the click of next button.
The problem is when add up 2 or more than 2 forms and then I remove the middle one or the 2nd one, Add Dependant and Next button stop doing anything, which is causing me problem. I want this form like user may add and delete anytime.
How can I achieve that?
var counter = 0;
var regexDoB = new RegExp('([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
$("#btAdd").on('click', function(e) {
e.preventDefault();
$('#errorDepFirstName' + counter).html("");
$('#errorDepLastName' + counter).html("");
$('#errorDepDateOfBirth' + counter).html("");
$('#errorDepGender' + counter).html("");
$('#errorDepRelationship' + counter).html("");
if ($('#txtDepFirstName' + counter).val() == '') {
$('#errorDepFirstName' + counter).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + counter).focus();
return false;
} else if ($('#txtDepLastName' + counter).val() == '') {
$('#errorDepLastName' + counter).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + counter).focus();
return false;
} else if ($('#txtDepDateOfBirth' + counter).val() == '') {
$('#errorDepDateOfBirth' + counter).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter).focus();
return false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + counter).val())) {
$('#errorDepDateOfBirth' + counter).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter).focus();
return false;
} else if ($('#ddDepGender' + counter).val() == -1) {
$('#errorDepGender' + counter).html("Please select Dependent's Gender");
$('#ddDepGender' + counter).focus();
return false;
} else if ($('#ddDepRelationship' + counter).val() == -1) {
$('#errorDepRelationship' + counter).html("Please select relation with Dependent");
$('#ddDepRelationship' + counter).focus();
return false;
} else if ($('#ddDepRelationship' + counter).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter).val()) > 25) {
$('#errorDepDateOfBirth' + counter).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + counter).focus();
return false;
} else {
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
}
});
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$("#btnNext").on('click', function(e) {
e.preventDefault();
for (var j = 0; j <= counter; j++) {
$('#errorDepFirstName' + j).html("");
$('#errorDepLastName' + j).html("");
$('#errorDepDateOfBirth' + j).html("");
$('#errorDepGender' + j).html("");
$('#errorDepRelationship' + j).html("");
}
flag = true;
for (var i = 0; i <= counter; i++) {
if ($('#txtDepFirstName' + i).val() == '') {
$('#errorDepFirstName' + i).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + i).focus();
flag = false;
} else if ($('#txtDepLastName' + i).val() == '') {
$('#errorDepLastName' + i).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + i).focus();
flag = false;
} else if ($('#txtDepDateOfBirth' + i).val() == '') {
$('#errorDepDateOfBirth' + i).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + i).val())) {
$('#errorDepDateOfBirth' + i).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
} else if ($('#ddDepGender' + i).val() == -1) {
$('#errorDepGender' + i).html("Please select Dependent's Gender");
$('#ddDepGender' + i).focus();
flag = false;
} else if ($('#ddDepRelationship' + i).val() == -1) {
$('#errorDepRelationship' + i).html("Please select relation with Dependent");
$('#ddDepRelationship' + i).focus();
flag = false;
} else if ($('#ddDepRelationship' + i).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter).val()) > 25) {
$('#errorDepDateOfBirth' + i).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
}
}
if (flag == true) {
alert("No Error Found, Redirecting");
//submission of data
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
counter--;
$(this).parent().parent().remove();
});
function GetDynamicTextBox() {
counter = counter + 1;
var div = $("<div />");
div.attr("class", 'my-3 border border-dark rounded p-3');
var header = '<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details<button class="removeitem btn btn-link text-danger float-right" type="button"><span class="fas fa-times"></span></button></p>';
var divFormRow = $("<div />");
divFormRow.attr("class", "form-row");
var divRow1Col1 = $("<div />");
divRow1Col1.attr("class", "form-group col-md-4");
//FirstName
var lblDepFName = $("<label />").attr("for", "txtDepFirstName" + counter);
lblDepFName.attr("class", "font-weight-bold small");
lblDepFName.html("First Name");
var txtDepFName = $("<input />").attr("type", "text").attr("name", "DependentFName");
txtDepFName.attr("placeholder", "First Name").attr("class", "form-control dep-name");
txtDepFName.attr("id", "txtDepFirstName" + counter)
var errorDepFName = $('<span />');
errorDepFName.attr("class", "form-text text-danger small").attr("id", "errorDepFirstName" + counter);
divRow1Col1.append(lblDepFName);
divRow1Col1.append(txtDepFName);
divRow1Col1.append(errorDepFName);
divFormRow.append(divRow1Col1);
var divRow1Col2 = $("<div />");
divRow1Col2.attr("class", "form-group col-md-4");
//Middle Name
var lblDepMName = $("<label />").attr("for", "txtDepMiddleName" + counter);
lblDepMName.attr("class", "font-weight-bold small");
lblDepMName.html("Middle Name");
var txtDepMName = $("<input />").attr("type", "text").attr("name", "DependentMName");
txtDepMName.attr("placeholder", "Middle Name").attr("class", "form-control");
txtDepMName.attr("id", "txtDepMiddleName" + counter)
var errorDepMiddleName = $('<span />');
errorDepMiddleName.attr("class", "form-text text-danger small").attr("id", "errorDepMiddleName" + counter);
divRow1Col2.append(lblDepMName);
divRow1Col2.append(txtDepMName);
divRow1Col2.append(errorDepMiddleName);
divFormRow.append(divRow1Col2);
var divRow1Col3 = $("<div />");
divRow1Col3.attr("class", "form-group col-md-4");
//Last Name
var lblDepLName = $("<label />").attr("for", "txtDepLastName" + counter);
lblDepLName.attr("class", "font-weight-bold small");
lblDepLName.html("Last Name");
var txtDepLName = $("<input />").attr("type", "text").attr("name", "DependentLName");
txtDepLName.attr("placeholder", "Last Name").attr("class", "form-control");
txtDepLName.attr("id", "txtDepLastName" + counter)
var errorDepLastName = $('<span />');
errorDepLastName.attr("class", "form-text text-danger small").attr("id", "errorDepLastName" + counter);
divRow1Col3.append(lblDepLName);
divRow1Col3.append(txtDepLName);
divRow1Col3.append(errorDepLastName);
divFormRow.append(divRow1Col3);
var divRow2Col1 = $("<div />");
divRow2Col1.attr("class", "form-group col-md-4");
//Date of Birth
var lblDepDateOfBirth = $("<label />").attr("for", "DepDateOfBirth" + counter);
lblDepDateOfBirth.attr("class", "font-weight-bold small");
lblDepDateOfBirth.html('Date of Birth <span class="small">(MM/DD/YYYY)</span>');
var txtDepDateOfBirth = $("<input />").attr("type", "text").attr("name", "DependentDateOfBirth");
txtDepDateOfBirth.attr("placeholder", "MM/DD/YYYY").attr("class", "form-control");
txtDepDateOfBirth.attr("id", "txtDepDateOfBirth" + counter)
var errorDepDateOfBirth = $('<span />');
errorDepDateOfBirth.attr("class", "form-text text-danger small").attr("id", "errorDepDateOfBirth" + counter);
divRow2Col1.append(lblDepDateOfBirth);
divRow2Col1.append(txtDepDateOfBirth);
divRow2Col1.append(errorDepDateOfBirth);
divFormRow.append(divRow2Col1);
var divRow2Col2 = $("<div />");
divRow2Col2.attr("class", "form-group col-md-4");
//Gender
var lblDepGender = $("<label />").attr("for", "ddDepGender" + counter);
lblDepGender.attr("class", "font-weight-bold small");
lblDepGender.html("Gender");
var ddDepGender = $("<select></select>");
ddDepGender.attr("name", "DepGender").attr("class", "form-control");
ddDepGender.attr("id", "ddDepGender" + counter);
var optnGender = $('<option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option>');
ddDepGender.append(optnGender);
var errorDepGender = $('<span />');
errorDepGender.attr("class", "form-text text-danger small").attr("id", "errorDepGender" + counter);
divRow2Col2.append(lblDepGender);
divRow2Col2.append(ddDepGender);
divRow2Col2.append(errorDepGender);
divFormRow.append(divRow2Col2);
var divRow2Col3 = $("<div />");
divRow2Col3.attr("class", "form-group col-md-4");
//Relationship
var lblDepRelationship = $("<label />").attr("for", "ddDepRelationship" + counter);
lblDepRelationship.attr("class", "font-weight-bold small");
lblDepRelationship.html("Relationship to Primary Applicant");
var ddDepRelationship = $("<select></select>");
ddDepRelationship.attr("name", "DependantRelationship").attr("class", "form-control");
ddDepRelationship.attr("id", "ddDepRelationship" + counter);
var optnRelationship = $('<option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option>');
ddDepRelationship.append(optnRelationship);
var errorDepRelationship = $('<span />');
errorDepRelationship.attr("class", "form-text text-danger small").attr("id", "errorDepRelationship" + counter);
divRow2Col3.append(lblDepRelationship);
divRow2Col3.append(ddDepRelationship);
divRow2Col3.append(errorDepRelationship);
divFormRow.append(divRow2Col3);
div.append(header);
div.append(divFormRow);
return div;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container mt-4">
<div id="DependentContainer">
<div id="TextBoxContainer" class="border rounded border-dark p-3 mb-3">
<div class="border rounded border-dark p-3">
<p class="lead font-weight-bold bg-light text-center p-1">
Dependant Details
</p>
<div class="form-row">
<div class="form-group col-md-4">
<label for="txtDepFirstName0" class="small font-weight-bold">
First Name</label>
<input type="text" class="form-control dep-name" id="txtDepFirstName0" name="DependentFName" placeholder="First Name" />
<span id="errorDepFirstName0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepMiddleName0" class="small font-weight-bold">
Middle Name</label>
<input type="text" class="form-control" id="txtDepMiddleName0" name="DependentMName" placeholder="Middle Name" />
<span id="errorDepMiddleName0" class="form-text text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepLastName0" class="small font-weight-bold">
Last Name</label>
<input type="text" class="form-control" id="txtDepLastName0" name="DependentLName" placeholder="Last Name" />
<span id="errorDepLastName0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepDateOfBirth0" class="small font-weight-bold">
Date of Birth <span class="small">(MM/DD/YYYY)</span></label>
<input type="text" class="form-control" id="txtDepDateOfBirth0" name="DependentDateOfBirth" placeholder="MM/DD/YYYY" />
<span id="errorDepDateOfBirth0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="ddDepGender0" class="small font-weight-bold">
Gender</label>
<select id="ddDepGender0" class="form-control" name="DepGender">
<option value="-1" selected="selected">Select Gender</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
<span id="errorDepGender0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="ddDepRelationship0" class="small font-weight-bold">
Relationship to Primary Applicant</label>
<select id="ddDepRelationship0" class="form-control" name="DependantRelationship">
<option value="-1" selected="selected">Select Relationship</option>
<option value="SP">Spouse or Domestic Partner</option>
<option value="CH">Child</option>
</select>
<span id="errorDepRelationship0" class="form-text text-danger small"></span>
</div>
</div>
</div>
<!--Textboxes will be added here -->
</div>
</div>
<div class="form-group text-center mt-3">
<input type="button" id="btAdd" value="Add Dependant" class="btn btn-primary" />
<br />
<input type="button" id="btnNext" value="Next" class="btn btn-primary float-right" />
</div>
<asp:Button Text="Save" ID="btnSave" CssClass="btn btn-danger btn-lg mt-5" OnClick="Process" runat="server" />
</div>
View on jsFiddle

I think you have a problem with your counter variable.
When you remove a form in the middle, you decrement your counter ... but the previous form is still the same as before the removing.
Instead of using a counter, why don't you use previous and next function of Jquery?

As others have mentioned, decrementing counter throws off ID references when validating.
I suggest using classes rather than IDs. Then you can iterate through each .form-row and validate inputs within each block by using selector context or find(). Like this:
$('.errorFirstName', this)
Here's a demonstration:
var counter = 0;
var regexDoB = new RegExp('(0[1-9]|1[012])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
function validateAll() {
// set to valid by default, in case no forms exist.
var valid = true;
// select all form blocks and errors
var $forms = $('.form-row');
var $errors = $('.text-danger', $forms);
// clear all errors
$errors.empty();
// iterate through all form blocks
$forms.each(function() {
// set block to invalid by default
valid = false;
// identify errors
if ($('.inputFirstName', this).val() == '') {
$('.errorFirstName', this).html("Please provide Dependent's First Name");
$('.inputFirstName', this).focus();
} else if ($('.inputLastName', this).val() == '') {
$('.errorLastName', this).html("Please provide Dependent's Last Name");
$('.inputLastName', this).focus();
} else if ($('.inputDOB', this).val() == '') {
$('.errorDOB', this).html("Please provide Dependent's Date of Birth");
$('.inputDOB', this).focus();
} else if (!regexDoB.test($('.inputDOB', this).val())) {
$('.errorDOB').html("Invalid Dependent's Date of Birth");
$('.inputDOB', this).focus();
} else if ($('.inputGender', this).val() == -1) {
$('.errorGender', this).html("Please select Dependent's Gender");
$('.inputGender', this).focus();
} else if ($('.inputRelationship', this).val() == -1) {
$('.errorRelationship', this).html("Please select relation with Dependent");
$('.inputRelationship', this).focus();
} else if ($('.inputRelationship', this).val() == 'CH' && getAge($('.inputDOB', this).val()) > 25) {
$('.errorDOB', this).html("Child Dependent's must be age 25 or younger");
$('.inputDOB', this).focus();
} else {
// set block to valid
valid = true;
}
// stop or continue block iteration
return valid;
});
// return validity state
return valid;
}
function GetDynamicTextBox() {
var div = $("<div>", {
'class': 'my-3 border border-dark rounded p-3'
});
var header = '<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details<button class="removeitem btn btn-link text-danger float-right" type="button"><span class="fas fa-times"></span></button></p>';
var divFormRow = $("<div>", {
"class": "form-row"
});
//FirstName
var divRow1Col1 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepFName = $("<label>", {
"class": "font-weight-bold small",
"html": "First Name"
});
var txtDepFName = $("<input>", {
"type": "text",
"name": "DependentFName",
"placeholder": "First Name",
"class": "form-control inputFirstName"
});
var errorDepFName = $('<span>', {
"class": "form-text text-danger small errorFirstName"
});
lblDepFName.append(txtDepFName);
divRow1Col1.append(lblDepFName).append(errorDepFName);
divFormRow.append(divRow1Col1);
//Middle Name
var divRow1Col2 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepMName = $("<label>", {
"class": "font-weight-bold small",
"html": "Middle Name"
});
var txtDepMName = $("<input>", {
"type": "text",
"name": "DependentMName",
"placeholder": "Middle Name",
"class": "form-control inputMiddleName"
});
var errorDepMiddleName = $('<span>', {
"class": "form-text text-danger small errorMiddleName"
});
lblDepMName.append(txtDepMName);
divRow1Col2.append(lblDepMName).append(errorDepMiddleName);
divFormRow.append(divRow1Col2);
//Last Name
var divRow1Col3 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepLName = $("<label>", {
"class": "font-weight-bold small",
"html": "Last Name"
});
var txtDepLName = $("<input>", {
"type": "text",
"name": "DependentLName",
"placeholder": "Last Name",
"class": "form-control inputLastName"
});
var errorDepLastName = $('<span>', {
"class": "form-text text-danger small errorLastName"
});
lblDepLName.append(txtDepLName);
divRow1Col3.append(lblDepLName).append(errorDepLastName);
divFormRow.append(divRow1Col3);
//Date of Birth
var divRow2Col1 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepDateOfBirth = $("<label>", {
"class": "font-weight-bold small",
"html": 'Date of Birth <span class="small">(MM/DD/YYYY)</span>'
});
var txtDepDateOfBirth = $("<input>", {
"type": "text",
"name": "DependentDateOfBirth",
"placeholder": "MM/DD/YYYY",
"class": "form-control inputDOB"
});
var errorDepDateOfBirth = $('<span>', {
"class": "form-text text-danger small errorDOB"
});
lblDepDateOfBirth.append(txtDepDateOfBirth);
divRow2Col1.append(lblDepDateOfBirth).append(errorDepDateOfBirth);
divFormRow.append(divRow2Col1);
//Gender
var divRow2Col2 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepGender = $("<label>", {
"class": "font-weight-bold small",
"html": "Gender"
});
var ddDepGender = $("<select>", {
"name": "DepGender",
"class": "form-control inputGender"
});
var optnGender = $('<option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option>');
var errorDepGender = $('<span>', {
"class": "form-text text-danger small errorGender"
});
ddDepGender.append(optnGender);
lblDepGender.append(ddDepGender);
divRow2Col2.append(lblDepGender).append(errorDepGender);
divFormRow.append(divRow2Col2);
//Relationship
var divRow2Col3 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepRelationship = $("<label>", {
"class": "font-weight-bold small",
"html": "Relationship to Primary Applicant"
});
var ddDepRelationship = $("<select>", {
"name": "DependantRelationship",
"class": "form-control inputRelationship"
});
var optnRelationship = $('<option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option>');
var errorDepRelationship = $('<span>', {
"class": "form-text text-danger small errorRelationship"
});
ddDepRelationship.append(optnRelationship);
lblDepRelationship.append(ddDepRelationship);
divRow2Col3.append(lblDepRelationship).append(errorDepRelationship);
divFormRow.append(divRow2Col3);
div.append(header);
div.append(divFormRow);
return div;
}
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$("#btAdd").on('click', function(e) {
e.preventDefault();
var allValid = validateAll();
if (allValid) {
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
}
});
$("#btnNext").on('click', function(e) {
e.preventDefault();
var allValid = validateAll();
if (allValid) {
alert("No Error Found, Redirecting");
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
counter--;
$(this).closest('.my-3').remove();
});
// add initial form block
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container mt-4">
<div id="DependentContainer">
<div id="TextBoxContainer" class="border rounded border-dark p-3 mb-3"></div>
</div>
<div class="form-group text-center mt-3">
<input type="button" id="btAdd" value="Add Dependant" class="btn btn-primary">
<br>
<input type="button" id="btnNext" value="Next" class="btn btn-primary float-right">
</div>
</div>
I've associated labels and inputs implicitly, by nesting inputs inside of their labels. That allowed me to get rid of counter altogether. If you prefer, you can associate them explicitly using incremented IDs (for=""). The idea is just not to use those IDs for validation iteration.
Edit
Above, I'm generating the initial form block from JavaScript, using the same function the "Add Button" uses. If you like, you can include the initial form block in your HTML, like you originally had it.
Like this:
var counter = 0;
var regexDoB = new RegExp('(0[1-9]|1[012])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
function validateAll() {
// set to valid by default, in case no forms exist.
var valid = true;
// select all form blocks and errors
var $forms = $('.form-row');
var $errors = $('.text-danger', $forms);
// clear all errors
$errors.empty();
// iterate through all form blocks
$forms.each(function() {
// set block to invalid by default
valid = false;
// identify errors
if ($('.inputFirstName', this).val() == '') {
$('.errorFirstName', this).html("Please provide Dependent's First Name");
$('.inputFirstName', this).focus();
} else if ($('.inputLastName', this).val() == '') {
$('.errorLastName', this).html("Please provide Dependent's Last Name");
$('.inputLastName', this).focus();
} else if ($('.inputDOB', this).val() == '') {
$('.errorDOB', this).html("Please provide Dependent's Date of Birth");
$('.inputDOB', this).focus();
} else if (!regexDoB.test($('.inputDOB', this).val())) {
$('.errorDOB').html("Invalid Dependent's Date of Birth");
$('.inputDOB', this).focus();
} else if ($('.inputGender', this).val() == -1) {
$('.errorGender', this).html("Please select Dependent's Gender");
$('.inputGender', this).focus();
} else if ($('.inputRelationship', this).val() == -1) {
$('.errorRelationship', this).html("Please select relation with Dependent");
$('.inputRelationship', this).focus();
} else if ($('.inputRelationship', this).val() == 'CH' && getAge($('.inputDOB', this).val()) > 25) {
$('.errorDOB', this).html("Child Dependent's must be age 25 or younger");
$('.inputDOB', this).focus();
} else {
// set block to valid
valid = true;
}
// stop or continue block iteration
return valid;
});
// return validity state
return valid;
}
function GetDynamicTextBox() {
var div = $("<div>", {
'class': 'my-3 border border-dark rounded p-3'
});
var header = '<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details<button class="removeitem btn btn-link text-danger float-right" type="button"><span class="fas fa-times"></span></button></p>';
var divFormRow = $("<div>", {
"class": "form-row"
});
//FirstName
var divRow1Col1 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepFName = $("<label>", {
"class": "font-weight-bold small",
"html": "First Name"
});
var txtDepFName = $("<input>", {
"type": "text",
"name": "DependentFName",
"placeholder": "First Name",
"class": "form-control inputFirstName"
});
var errorDepFName = $('<span>', {
"class": "form-text text-danger small errorFirstName"
});
lblDepFName.append(txtDepFName);
divRow1Col1.append(lblDepFName).append(errorDepFName);
divFormRow.append(divRow1Col1);
//Middle Name
var divRow1Col2 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepMName = $("<label>", {
"class": "font-weight-bold small",
"html": "Middle Name"
});
var txtDepMName = $("<input>", {
"type": "text",
"name": "DependentMName",
"placeholder": "Middle Name",
"class": "form-control inputMiddleName"
});
var errorDepMiddleName = $('<span>', {
"class": "form-text text-danger small errorMiddleName"
});
lblDepMName.append(txtDepMName);
divRow1Col2.append(lblDepMName).append(errorDepMiddleName);
divFormRow.append(divRow1Col2);
//Last Name
var divRow1Col3 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepLName = $("<label>", {
"class": "font-weight-bold small",
"html": "Last Name"
});
var txtDepLName = $("<input>", {
"type": "text",
"name": "DependentLName",
"placeholder": "Last Name",
"class": "form-control inputLastName"
});
var errorDepLastName = $('<span>', {
"class": "form-text text-danger small errorLastName"
});
lblDepLName.append(txtDepLName);
divRow1Col3.append(lblDepLName).append(errorDepLastName);
divFormRow.append(divRow1Col3);
//Date of Birth
var divRow2Col1 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepDateOfBirth = $("<label>", {
"class": "font-weight-bold small",
"html": 'Date of Birth <span class="small">(MM/DD/YYYY)</span>'
});
var txtDepDateOfBirth = $("<input>", {
"type": "text",
"name": "DependentDateOfBirth",
"placeholder": "MM/DD/YYYY",
"class": "form-control inputDOB"
});
var errorDepDateOfBirth = $('<span>', {
"class": "form-text text-danger small errorDOB"
});
lblDepDateOfBirth.append(txtDepDateOfBirth);
divRow2Col1.append(lblDepDateOfBirth).append(errorDepDateOfBirth);
divFormRow.append(divRow2Col1);
//Gender
var divRow2Col2 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepGender = $("<label>", {
"class": "font-weight-bold small",
"html": "Gender"
});
var ddDepGender = $("<select>", {
"name": "DepGender",
"class": "form-control inputGender"
});
var optnGender = $('<option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option>');
var errorDepGender = $('<span>', {
"class": "form-text text-danger small errorGender"
});
ddDepGender.append(optnGender);
lblDepGender.append(ddDepGender);
divRow2Col2.append(lblDepGender).append(errorDepGender);
divFormRow.append(divRow2Col2);
//Relationship
var divRow2Col3 = $("<div>", {
"class": "form-group col-md-4"
});
var lblDepRelationship = $("<label>", {
"class": "font-weight-bold small",
"html": "Relationship to Primary Applicant"
});
var ddDepRelationship = $("<select>", {
"name": "DependantRelationship",
"class": "form-control inputRelationship"
});
var optnRelationship = $('<option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option>');
var errorDepRelationship = $('<span>', {
"class": "form-text text-danger small errorRelationship"
});
ddDepRelationship.append(optnRelationship);
lblDepRelationship.append(ddDepRelationship);
divRow2Col3.append(lblDepRelationship).append(errorDepRelationship);
divFormRow.append(divRow2Col3);
div.append(header);
div.append(divFormRow);
return div;
}
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$("#btAdd").on('click', function(e) {
e.preventDefault();
var allValid = validateAll();
if (allValid) {
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
}
});
$("#btnNext").on('click', function(e) {
e.preventDefault();
var allValid = validateAll();
if (allValid) {
alert("No Error Found, Redirecting");
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
counter--;
$(this).closest('.my-3').remove();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container mt-4">
<div id="DependentContainer">
<div id="TextBoxContainer" class="border rounded border-dark p-3 mb-3">
<div class="my-3 border border-dark rounded p-3">
<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details</p>
<div class="form-row">
<div class="form-group col-md-4"><label class="font-weight-bold small">First Name<input type="text" name="DependentFName" placeholder="First Name" class="form-control inputFirstName"></label><span class="form-text text-danger small errorFirstName"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Middle Name<input type="text" name="DependentMName" placeholder="Middle Name" class="form-control inputMiddleName"></label><span class="form-text text-danger small errorMiddleName"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Last Name<input type="text" name="DependentLName" placeholder="Last Name" class="form-control inputLastName"></label><span class="form-text text-danger small errorLastName"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Date of Birth <span class="small">(MM/DD/YYYY)</span><input type="text" name="DependentDateOfBirth" placeholder="MM/DD/YYYY" class="form-control inputDOB"></label><span class="form-text text-danger small errorDOB"></span></div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Gender<select name="DepGender" class="form-control inputGender"><option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option></select></label>
<span class="form-text text-danger small errorGender"></span>
</div>
<div class="form-group col-md-4"><label class="font-weight-bold small">Relationship to Primary Applicant<select name="DependantRelationship" class="form-control inputRelationship"><option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option></select></label>
<span class="form-text text-danger small errorRelationship"></span>
</div>
</div>
</div>
</div>
</div>
<div class="form-group text-center mt-3">
<input type="button" id="btAdd" value="Add Dependant" class="btn btn-primary">
<br>
<input type="button" id="btnNext" value="Next" class="btn btn-primary float-right">
</div>
</div>

You are having a problem in counter variable and id of your fields.
Basically you are trying to get a form that does not exist.
This happens when you are adding 2 extra forms witch result in input elements with id 1,2 and 3 but when you delete the middle one witch is 2 the counter is still at 3. So when you want to validate you inputs input 2 does not exist. Witch stop the JavaScript execution.
I fixed it by adding if elements in both loops in the next element button click event. witch they check if the element exist and then try to access it.
As you mentioned. Also delete counter-- when you are removing the form
var counter = 0;
var regexDoB = new RegExp('([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})');
var getLastValidId = function(){
var lastId = $('#TextBoxContainer').children().last().find("input").first().attr("id").match(/\d+/);
return lastId;
}
$("#btAdd").on('click', function(e) {
e.preventDefault();
var counter1 = getLastValidId()
$('#errorDepFirstName' + counter1).html("");
$('#errorDepLastName' + counter1).html("");
$('#errorDepDateOfBirth' + counter1).html("");
$('#errorDepGender' + counter1).html("");
$('#errorDepRelationship' + counter1).html("");
if ($('#txtDepFirstName' + counter1).val() == '') {
$('#errorDepFirstName' + counter1).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + counter1).focus();
return false;
} else if ($('#txtDepLastName' + counter1).val() == '') {
$('#errorDepLastName' + counter1).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + counter1).focus();
return false;
} else if ($('#txtDepDateOfBirth' + counter1).val() == '') {
$('#errorDepDateOfBirth' + counter1).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter1).focus();
return false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + counter1).val())) {
$('#errorDepDateOfBirth' + counter1).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + counter1).focus();
return false;
} else if ($('#ddDepGender' + counter1).val() == -1) {
$('#errorDepGender' + counter1).html("Please select Dependent's Gender");
$('#ddDepGender' + counter1).focus();
return false;
} else if ($('#ddDepRelationship' + counter1).val() == -1) {
$('#errorDepRelationship' + counter1).html("Please select relation with Dependent");
$('#ddDepRelationship' + counter1).focus();
return false;
} else if ($('#ddDepRelationship' + counter1).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter1).val()) > 25) {
$('#errorDepDateOfBirth' + counter1).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + counter1).focus();
return false;
} else {
var div = GetDynamicTextBox();
$("#TextBoxContainer").append(div);
}
});
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
$("#btnNext").on('click', function(e) {
e.preventDefault();
for (var j = 0; j <= counter; j++) {
if($('#errorDepFirstName' + j).length > 0){
$('#errorDepFirstName' + j).html("");
$('#errorDepLastName' + j).html("");
$('#errorDepDateOfBirth' + j).html("");
$('#errorDepGender' + j).html("");
$('#errorDepRelationship' + j).html("");
}}
flag = true;
for (var i = 0; i <= counter; i++) {
if($('#errorDepFirstName' + i).length > 0){
if ($('#txtDepFirstName' + i).val() == '') {
$('#errorDepFirstName' + i).html("Please provide Dependent's First Name");
$('#txtDepFirstName' + i).focus();
flag = false;
} else if ($('#txtDepLastName' + i).val() == '') {
$('#errorDepLastName' + i).html("Please provide Dependent's Last Name");
$('#txtDepLastName' + i).focus();
flag = false;
} else if ($('#txtDepDateOfBirth' + i).val() == '') {
$('#errorDepDateOfBirth' + i).html("Please provide Dependent's Date of Birth");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
} else if (!regexDoB.test($('#txtDepDateOfBirth' + i).val())) {
$('#errorDepDateOfBirth' + i).html("Invalid Dependent's Date of Birth");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
} else if ($('#ddDepGender' + i).val() == -1) {
$('#errorDepGender' + i).html("Please select Dependent's Gender");
$('#ddDepGender' + i).focus();
flag = false;
} else if ($('#ddDepRelationship' + i).val() == -1) {
$('#errorDepRelationship' + i).html("Please select relation with Dependent");
$('#ddDepRelationship' + i).focus();
flag = false;
} else if ($('#ddDepRelationship' + i).val() == 'CH' && getAge($('#txtDepDateOfBirth' + counter).val()) > 25) {
$('#errorDepDateOfBirth' + i).html("Child Dependent's must be age 25 or younger");
$('#txtDepDateOfBirth' + i).focus();
flag = false;
}}
}
if (flag == true) {
alert("No Error Found, Redirecting");
//submission of data
}
});
$("body").on("click", ".removeitem", function(e) {
e.preventDefault();
$(this).parent().parent().remove();
});
function GetDynamicTextBox() {
counter = counter + 1;
var div = $("<div />");
div.attr("class", 'my-3 border border-dark rounded p-3');
var header = '<p class="lead font-weight-bold bg-light text-center p-1">Dependant Details<button class="removeitem btn btn-link text-danger float-right" type="button"><span class="fas fa-times"></span></button></p>';
var divFormRow = $("<div />");
divFormRow.attr("class", "form-row");
var divRow1Col1 = $("<div />");
divRow1Col1.attr("class", "form-group col-md-4");
//FirstName
var lblDepFName = $("<label />").attr("for", "txtDepFirstName" + counter);
lblDepFName.attr("class", "font-weight-bold small");
lblDepFName.html("First Name");
var txtDepFName = $("<input />").attr("type", "text").attr("name", "DependentFName");
txtDepFName.attr("placeholder", "First Name").attr("class", "form-control dep-name");
txtDepFName.attr("id", "txtDepFirstName" + counter)
var errorDepFName = $('<span />');
errorDepFName.attr("class", "form-text text-danger small").attr("id", "errorDepFirstName" + counter);
divRow1Col1.append(lblDepFName);
divRow1Col1.append(txtDepFName);
divRow1Col1.append(errorDepFName);
divFormRow.append(divRow1Col1);
var divRow1Col2 = $("<div />");
divRow1Col2.attr("class", "form-group col-md-4");
//Middle Name
var lblDepMName = $("<label />").attr("for", "txtDepMiddleName" + counter);
lblDepMName.attr("class", "font-weight-bold small");
lblDepMName.html("Middle Name");
var txtDepMName = $("<input />").attr("type", "text").attr("name", "DependentMName");
txtDepMName.attr("placeholder", "Middle Name").attr("class", "form-control");
txtDepMName.attr("id", "txtDepMiddleName" + counter)
var errorDepMiddleName = $('<span />');
errorDepMiddleName.attr("class", "form-text text-danger small").attr("id", "errorDepMiddleName" + counter);
divRow1Col2.append(lblDepMName);
divRow1Col2.append(txtDepMName);
divRow1Col2.append(errorDepMiddleName);
divFormRow.append(divRow1Col2);
var divRow1Col3 = $("<div />");
divRow1Col3.attr("class", "form-group col-md-4");
//Last Name
var lblDepLName = $("<label />").attr("for", "txtDepLastName" + counter);
lblDepLName.attr("class", "font-weight-bold small");
lblDepLName.html("Last Name");
var txtDepLName = $("<input />").attr("type", "text").attr("name", "DependentLName");
txtDepLName.attr("placeholder", "Last Name").attr("class", "form-control");
txtDepLName.attr("id", "txtDepLastName" + counter)
var errorDepLastName = $('<span />');
errorDepLastName.attr("class", "form-text text-danger small").attr("id", "errorDepLastName" + counter);
divRow1Col3.append(lblDepLName);
divRow1Col3.append(txtDepLName);
divRow1Col3.append(errorDepLastName);
divFormRow.append(divRow1Col3);
var divRow2Col1 = $("<div />");
divRow2Col1.attr("class", "form-group col-md-4");
//Date of Birth
var lblDepDateOfBirth = $("<label />").attr("for", "DepDateOfBirth" + counter);
lblDepDateOfBirth.attr("class", "font-weight-bold small");
lblDepDateOfBirth.html('Date of Birth <span class="small">(MM/DD/YYYY)</span>');
var txtDepDateOfBirth = $("<input />").attr("type", "text").attr("name", "DependentDateOfBirth");
txtDepDateOfBirth.attr("placeholder", "MM/DD/YYYY").attr("class", "form-control");
txtDepDateOfBirth.attr("id", "txtDepDateOfBirth" + counter)
var errorDepDateOfBirth = $('<span />');
errorDepDateOfBirth.attr("class", "form-text text-danger small").attr("id", "errorDepDateOfBirth" + counter);
divRow2Col1.append(lblDepDateOfBirth);
divRow2Col1.append(txtDepDateOfBirth);
divRow2Col1.append(errorDepDateOfBirth);
divFormRow.append(divRow2Col1);
var divRow2Col2 = $("<div />");
divRow2Col2.attr("class", "form-group col-md-4");
//Gender
var lblDepGender = $("<label />").attr("for", "ddDepGender" + counter);
lblDepGender.attr("class", "font-weight-bold small");
lblDepGender.html("Gender");
var ddDepGender = $("<select></select>");
ddDepGender.attr("name", "DepGender").attr("class", "form-control");
ddDepGender.attr("id", "ddDepGender" + counter);
var optnGender = $('<option value="-1" selected="selected">Select Gender</option><option value="M">Male</option><option value="F">Female</option>');
ddDepGender.append(optnGender);
var errorDepGender = $('<span />');
errorDepGender.attr("class", "form-text text-danger small").attr("id", "errorDepGender" + counter);
divRow2Col2.append(lblDepGender);
divRow2Col2.append(ddDepGender);
divRow2Col2.append(errorDepGender);
divFormRow.append(divRow2Col2);
var divRow2Col3 = $("<div />");
divRow2Col3.attr("class", "form-group col-md-4");
//Relationship
var lblDepRelationship = $("<label />").attr("for", "ddDepRelationship" + counter);
lblDepRelationship.attr("class", "font-weight-bold small");
lblDepRelationship.html("Relationship to Primary Applicant");
var ddDepRelationship = $("<select></select>");
ddDepRelationship.attr("name", "DependantRelationship").attr("class", "form-control");
ddDepRelationship.attr("id", "ddDepRelationship" + counter);
var optnRelationship = $('<option value="-1" selected="selected">Select Relationship</option><option value="SP">Spouse or Domestic Partner</option><option value="CH">Child</option>');
ddDepRelationship.append(optnRelationship);
var errorDepRelationship = $('<span />');
errorDepRelationship.attr("class", "form-text text-danger small").attr("id", "errorDepRelationship" + counter);
divRow2Col3.append(lblDepRelationship);
divRow2Col3.append(ddDepRelationship);
divRow2Col3.append(errorDepRelationship);
divFormRow.append(divRow2Col3);
div.append(header);
div.append(divFormRow);
return div;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<div class="container mt-4">
<div id="DependentContainer">
<div id="TextBoxContainer" class="border rounded border-dark p-3 mb-3">
<div class="border rounded border-dark p-3">
<p class="lead font-weight-bold bg-light text-center p-1">
Dependant Details
</p>
<div class="form-row">
<div class="form-group col-md-4">
<label for="txtDepFirstName0" class="small font-weight-bold">
First Name</label>
<input type="text" class="form-control dep-name" id="txtDepFirstName0" name="DependentFName" placeholder="First Name" />
<span id="errorDepFirstName0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepMiddleName0" class="small font-weight-bold">
Middle Name</label>
<input type="text" class="form-control" id="txtDepMiddleName0" name="DependentMName" placeholder="Middle Name" />
<span id="errorDepMiddleName0" class="form-text text-danger"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepLastName0" class="small font-weight-bold">
Last Name</label>
<input type="text" class="form-control" id="txtDepLastName0" name="DependentLName" placeholder="Last Name" />
<span id="errorDepLastName0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="txtDepDateOfBirth0" class="small font-weight-bold">
Date of Birth <span class="small">(MM/DD/YYYY)</span></label>
<input type="text" class="form-control" id="txtDepDateOfBirth0" name="DependentDateOfBirth" placeholder="MM/DD/YYYY" />
<span id="errorDepDateOfBirth0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="ddDepGender0" class="small font-weight-bold">
Gender</label>
<select id="ddDepGender0" class="form-control" name="DepGender">
<option value="-1" selected="selected">Select Gender</option>
<option value="M">Male</option>
<option value="F">Female</option>
</select>
<span id="errorDepGender0" class="form-text text-danger small"></span>
</div>
<div class="form-group col-md-4">
<label for="ddDepRelationship0" class="small font-weight-bold">
Relationship to Primary Applicant</label>
<select id="ddDepRelationship0" class="form-control" name="DependantRelationship">
<option value="-1" selected="selected">Select Relationship</option>
<option value="SP">Spouse or Domestic Partner</option>
<option value="CH">Child</option>
</select>
<span id="errorDepRelationship0" class="form-text text-danger small"></span>
</div>
</div>
</div>
<!--Textboxes will be added here -->
</div>
</div>
<div class="form-group text-center mt-3">
<input type="button" id="btAdd" value="Add Dependant" class="btn btn-primary" />
<br />
<input type="button" id="btnNext" value="Next" class="btn btn-primary float-right" />
</div>
<asp:Button Text="Save" ID="btnSave" CssClass="btn btn-danger btn-lg mt-5" OnClick="Process" runat="server" />
</div>
<button onclick="getLastValidId()">A</button>

Related

Updated: How do I pass a default value into my modal input element

UPdated: have been stuck on this for 3 day's now and I cannot find an answer anywhere.
I have a model that contains -input type="text" name="mycardname" id="CardName"/-
I want to post the card name into the value of the input box.
I can put it in a label or a span, but cannot find a way or example to add it to the input box.
My code is below.
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '');
$target('#CardName')('value try This');
});
});
$('#settingsModal,#monthModal').on('show.bs.modal', function (event) {
alert("this alert");
var $card = $(event.relatedTarget).closest('.card');
var $modal = $(this);
var data = $card.data();
Document.getElementById('#CardName').val("try This");
for (var item in data) {
$modal.find('[name="' + item + '"]').val(data[item]);
}
});
$('#monthModal .btn-primary').click(function () {
var $modal = $(this).closest('.modal');
var searchType = $modal.find('input[name="SearchTypeRadio"]:checked').val();
var metric = $modal.find('[name="metric"]').val();
var month = $modal.find('[name="month"]').val();
var cdName = $modal.find('[name="mycardname"]').val();
alert("SearchType: " + searchType + " Metric: " + metric + " Month: " + month + " Card Name: " + cdName);
});
$('.btnApplyColors').on('click', function () {
var $modal = $(this).closest('.modal');
var cardName = $modal.find('[name="name"]').val();
var grMin = $modal.find('[name="greenmin"]').val();
var grMax = $modal.find('[name="greenmax"]').val();
var yMin = $modal.find('[name="yellowmin"]').val();
var yMax = $modal.find('[name="yellowmax"]').val();
var rMin = $modal.find('[name="redmin"]').val();
var rMax = $modal.find('[name="redmax"]').val();
var cardTR = cardName + 'TR';
var elements = document.getElementsByClassName(cardTR); // get all elements
for (var i = 0; i < elements.length; i++) {
var tsd1 = cardName + i + 'TD1';
var tsd2 = cardName + i + 'TD2';
var td1 = document.getElementById(tsd1).innerHTML;
var td2 = parseInt(document.getElementById(tsd2).innerHTML);
alert(td1 + " - " + td2);
switch (true) {
case (td2 >= yMin && td2 <= yMax):
alert(td1 + " - " + td2 + " YMin " + yMin + " yMax " + yMax);
elements[i].style.backgroundColor = "lightyellow";
elements[i].style.color = 'brown';
break;
case (td2 >= grMin && td2 <= grMax):
alert(td1 + " - " + td2 + " grMin " + grMin + " grMax " + grMax);
elements[i].style.backgroundColor = "#E7FCE3";
elements[i].style.color = 'darkgreen';
break;
case (td2 >= rMin && td2 <= rMax):
alert(td1 + " - " + td2 + " rMin " + rMin + " rMax " + rMax);
elements[i].style.backgroundColor = "mistyrose";
elements[i].style.color = 'red';
break;
default:
alert("Hit the Default because " + td2 + " not found");
break;
}
}
$('#ScoreCardDefaults').modal('hide');
});
$(document).ready(function () {
$('input[type="radio"]').click(function () {
var inputValue = $(this).attr("value");
var targetBox = $("." + inputValue);
$(".box").not(targetBox).hide();
$(targetBox).show();
});
});
// clean this up //
let startYear = 2000;
let endYear = new Date().getFullYear();
for (i = endYear; i > startYear; i--) {
$('#yearpicker').append($('<option />').val(i).html(i));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row row-cols-1 row-cols-md-2 row-cols-xl-4">
<div class="col mb-4" data-mincoolscale="71">
<div class="card text-center" data-metric="14" data-month="2020-10" data-mincoolscale="71" data-maxcoolscale="100" data-minwarmscale="51" data-maxwarmscale="70" data-minhotscale="0" data-maxhotscale="50">
<div class="card-img-top d-flex align-items-center justify-content-center bg-primary text-light metric-header">
<span class="h5 my-1">my card</span>
</div>
<div class="card-body pt-3">
<h6 class="card-title">
my card title
</h6>
<p>
<span class="metric-date">#DateTime.Now.ToString("MMMM yyyy")</span>
<button type="button" class="btn btn-sm btn-link CardModal" data-cardname="The Card Name" data-toggle="modal" data-target="#monthModal" title="Edit" aria-title="Edit">
Ccc
</button>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="modal fade" id="monthModal" tabindex="-1" aria-labelledby="monthModalTitle" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="monthModalTitle">Display Statistics For</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<span id="modal-cardname"></span>
<input type="text" name="mycardname" id="CardName" />
<div class="myRadios">
<label><input type="radio" name="SearchTypeRadio" value="Monthly"> Monthly</label>
<label><input type="radio" name="SearchTypeRadio" value="Quarterly"> Quarterly</label>
</div>
<div style="display:none" class="Monthly box">You have selected Monthly</div>
<div style="display:none" class="Quarterly box">You have selected quarterly</div>
<div style="display:none" class="Monthly box form-group">
<input type="month" id="month" name="month" class="form-control w-auto" placeholder="mm/yyyy" max="#DateTime.Now.ToString("yyyy-MM")" min="2010-01" />
</div>
<div style="display:none" class="Quarterly box form-group">
#*<label for="month">Yearly Quarter of</label>*#
<select id="QTRS">
<option value="1" selected>1st Quarter</option>
<option value="2">2nd Quarter</option>
<option value="3">3rd Quarter</option>
<option value="4">4th Quarter</option>
</select>
<select name="yearpicker" id="yearpicker"></select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
#*<a class=" btn btn-primary" asp-controller="Home" asp-action="updateSSOA"> Apply</a>*#
<button type="button" class="btn btn-primary" data-dismiss="modal">Apply</button>
</div>
</div>
</div>
</div>
I don’t know if there are multiple text boxes and buttons that are the same on this page. Do you mean to traverse all ATTRIBUTES to the text box corresponding to this button or to pass the ATTRIBUTES corresponding to the modal value into the text box?
If you pass in a corresponding ATTRIBUTES, please refer to the following example:
<input type="text" name="mycardname" id="CardName" />
<button type="button" class="btn btn-sm btn-link CardModal"
data-cardname="kls01" data-toggle="modal" data-target="#monthModal"
title="Edit" aria-title="Edit">
Launch Modal
</button>
#section Scripts{
<script>
$(function () {
var ATTRIBUTES = ['cardname', 'metric', 'month'];
$('.CardModal').on('click', function (e) {
var $target = $(e.target);
var modalSelector = $target.data('target');
ATTRIBUTES.forEach(function (attributeName) {
var $modalAttribute = $(modalSelector + ' #modal-' + attributeName);
var dataValue = $target.data(attributeName);
$modalAttribute.text(dataValue || '00');
if ($target.prev().val() == '' || $target.prev().val == null) {
$target.prev().val(attributeName || '')
}
});
});
})
</script>
}
Result:
I finally figured it out:
Change:
$target('#CardName')('value try This');
to:
var myCardName = $(this).data('cardname');
$(".modal-body #mycardname").val(myCardName);

JQuery | How to display variables when associated checkbox is checked

I'm creating a website that grabs weather information based on the location entered by the user. At the moment there are some features on the page with no functionality, it is still a work in progress. I apologies for the sloppy code.
I have 9 checkboxes at the top of my form that have the info that should be displayed and I'm not sure of the best method to edit the output accordingly.
In my JS file there is a block that grabs all of the relevant weather data and assigns it to variables. These variables are then used to generate a <p> element containing all of this info. How can I edit it to only display the variables that are selected via checkboxes?
$(document).ready(function() {
var inputType = 1;
$("#Radio1").click(function() {
$("#lbl1").text("City Name:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2,}",
"placeholder": "Regina"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 1;
});
$("#Radio2").click(function() {
$("#lbl1").text("Postal Code:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[A-Z][0-9][A-Z]",
"placeholder": "S4X"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 2;
});
$("#Radio3").click(function() {
$("#lbl1").text("Latitude:");
$("#lbl2").text("Longitude:");
$("#Firstbox").removeAttr("pattern");
$("#Secondbox").removeAttr("pattern");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "number",
"min": "-90",
"max": "90",
"step": "any",
"placeholder": "50.4"
});
$("#Secondbox").attr({
"type": "number",
"min": "-180",
"max": "180",
"step": "any",
"placeholder": "-105.5"
});
inputType = 3;
});
$("#SearchButton").click(function() {
if (checkValidity()) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var SearchResponse = this.responseText;
var obj = JSON.parse(SearchResponse);
var city_name = obj["name"];
var country_name = obj["sys"]["country"];
var longitude = obj["coord"]["lon"];
var latitude = obj["coord"]["lat"];
var weather_description = obj["weather"][0]["description"];
var temp = obj["main"]["temp"] - 273.15;
var pressure = obj["main"]["pressure"];
var humidity = obj["main"]["humidity"];
var wind_speed = obj["wind"]["speed"];
var wind_direction = obj["wind"]["deg"];
var sunrise = new Date(obj["sys"]["sunrise"] * 1000);
var sunset = new Date(obj["sys"]["sunset"] * 1000);
var SearchResultsHTML = "City: " + city_name + "<br />" +
"Country: " + country_name + "<br />" +
"Longitude: " + longitude + "<br />" +
"Latitude: " + latitude + "<br />" +
"Weather: " + weather_description + "<br />" +
"Temperature: " + temp + "<br />" +
"Pressure: " + pressure + "<br />" +
"Humidity: " + humidity + "<br />" +
"Wind Speed: " + wind_speed + "<br />" +
"Wind Direction: " + wind_direction + "<br />" +
"Sunrise: " + sunrise.toLocaleTimeString() + "<br />" +
"Sunset: " + sunset.toLocaleTimeString() + "<br />";
$("#SearchResults").html(SearchResultsHTML);
}
}
var Firstbox = $("#Firstbox").val();
var Secondbox = $("#Secondbox").val();
var apiKey = "52453f34dee0d65b1a41a02656142c6b";
if (inputType == 1) {
var SearchString = "https://api.openweathermap.org/data/2.5/weather" +
"?q=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 2) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?zip=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 3) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?lat=" + Firstbox + "&lon=" + Secondbox +
"&APPID=" + apiKey;
}
xhttp.open("GET", SearchString, true);
xhttp.send();
}
});
function displayError() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid) {
if (inputType == 1 || inputType == 2) {
alert("Country code must be 2 characters in length.");
} else {
alert("Longitude must be between -180 and 180");
}
} else {
if (inputType == 1) {
alert("City name must be longer than 1 character.");
} else if (inputType == 2) {
alert("Postal code must be 3 characters in length, following the format 'S4X'");
} else {
alert("Latitude must be between -90 and 90");
}
}
}
function checkValidity() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid && second.validity.valid) {
return true;
} else {
displayError();
return false;
}
}
function checksSelected() {
}
});
.validated:valid {
background-color: #BDF0A8;
}
.validated:invalid {
background-color: #FAC3C9;
}
.row {
margin-bottom: 10px;
}
.ticksel {
border: solid black 1px;
}
tr,
td {
border: solid black 1px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="weather.css">
<form id="searchForm" method="POST" action="URL">
<div class="row col-md-12">
<h2>OpenWeatherMap Weather Search</h2>
</div>
<div class="row">
<div class="col-md-6">
<h4>Search by:</h4>
<input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
<input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
<input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
</div>
<div class="col-md-6">
<h4>Show in search results:</h4>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Longitude</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Latitude</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Temperature</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Pressure</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Humidity</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Wind Speed</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Wind Direction</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Sunrise</div>
<div class="col ticksel"><input type="checkbox" checked id="" value=""> Sunset</div>
</div>
</div>
</div>
<div class="row col-md-12">
<label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" placeholder="Regina" />
<label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" placeholder="ca" />
<input id="SearchButton" type="button" value="Search" />
</div>
</form>
<div class="row col-md-12">
<h4>Current Weather</h4>
</div>
<div class="row col-md-12">
<p id="SearchResults"></p>
</div>
<div class="row col-md-12">
<table width="100%">
<thead>
<tr>
<th>City</th>
<th>Country</th>
<th>Longitude</th>
<th>Latitude</th>
<th>Weather</th>
<th>Temperature</th>
<th>Pressure</th>
<th>Humidity</th>
<th>Wind Speed</th>
<th>Wind Direction</th>
<th>Sunrise</th>
<th>Sunst</th>
<th><a class="deleteAll" href="#">Clear Log</a></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
Here is a version that will take the checked boxes and show their corresponding values
I changed your xmlhttp to getJSON
You can do
let SearchResultsHTML = []
SearchResultsHTML.push("City: " + city_name);
SearchResultsHTML.push("Country: " + country_name);
SearchResultsHTML.push("Weather: " + weather_description);
if ($("#long").is(":checked")) SearchResultsHTML.push("Longitude: " + longitude);
if ($("#lat").is(":checked")) SearchResultsHTML.push("Latitude: " + latitude);
if ($("#temp").is(":checked")) SearchResultsHTML.push("Temperature: " + temp);
if ($("#pres").is(":checked")) SearchResultsHTML.push("Pressure: " + pressure);
if ($("#hum").is(":checked")) SearchResultsHTML.push("Humidity: " + humidity);
if ($("#ws").is(":checked")) SearchResultsHTML.push("Wind Speed: " + wind_speed);
if ($("#wd").is(":checked")) SearchResultsHTML.push("Wind Direction: " + wind_direction);
if ($("#sunup").is(":checked")) SearchResultsHTML.push("Sunrise: " + sunrise.toLocaleTimeString());
if ($("#sundown").is(":checked")) SearchResultsHTML.push("Sunset: " + sunset.toLocaleTimeString());
$("#SearchResults").html(SearchResultsHTML.join("<br/>"));
or more elegantly add a span and toggle this at show time or even after
let SearchResultsHTML = []
SearchResultsHTML.push("City: " + city_name);
SearchResultsHTML.push("Country: " + country_name);
SearchResultsHTML.push("Weather: " + weather_description);
SearchResultsHTML.push("<span id='longSpan'>Longitude: " + longitude + "</span>");
SearchResultsHTML.push("<span id='latSpan'>Latitude: " + latitude + "</span>");
SearchResultsHTML.push("<span id='tempSpan'>Temperature: " + temp + "</span>");
SearchResultsHTML.push("<span id='pressSpan'>Pressure: " + pressure + "</span>");
SearchResultsHTML.push("<span id='humSpan'>Humidity: " + humidity + "</span>");
SearchResultsHTML.push("<span id='wsSpan'>Wind Speed: " + wind_speed + "</span>");
SearchResultsHTML.push("<span id='wdSpan'>Wind Direction: " + wind_direction + "</span>");
SearchResultsHTML.push("<span id='sunupSpan'>Sunrise: " + sunrise.toLocaleTimeString + "</span>");
SearchResultsHTML.push("<span id='sundownSpan'>Sunset: " + sunset.toLocaleTimeString() + "</span>");
$("#SearchResults").html(SearchResultsHTML.join("<br/>"));
showSpans();
})
}
using
$(".ticksel").on("change", showSpans);
function showSpans() {
$(".ticksel input").each(function() {
const id = this.id;
const checked = this.checked;
if (id) {
const $span = $("#" + id + "span");
if ($span) $span.toggle(checked);
}
})
}
$(document).ready(function() {
var inputType = 1;
$("#Radio1").click(function() {
$("#lbl1").text("City Name:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2,}",
"placeholder": "Regina"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 1;
});
$("#Radio2").click(function() {
$("#lbl1").text("Postal Code:");
$("#lbl2").text("Country Code:");
$("#Firstbox").removeAttr("min max step");
$("#Secondbox").removeAttr("min max step");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "text",
"pattern": "[A-Z][0-9][A-Z]",
"placeholder": "S4X"
});
$("#Secondbox").attr({
"type": "text",
"pattern": "[a-zA-Z]{2}",
"placeholder": "ca"
});
inputType = 2;
});
$("#Radio3").click(function() {
$("#lbl1").text("Latitude:");
$("#lbl2").text("Longitude:");
$("#Firstbox").removeAttr("pattern");
$("#Secondbox").removeAttr("pattern");
document.getElementById('Firstbox').value = '';
document.getElementById('Secondbox').value = '';
$("#Firstbox").attr({
"type": "number",
"min": "-90",
"max": "90",
"step": "any",
"placeholder": "50.4"
});
$("#Secondbox").attr({
"type": "number",
"min": "-180",
"max": "180",
"step": "any",
"placeholder": "-105.5"
});
inputType = 3;
});
$("#SearchButton").click(function() {
if (checkValidity()) {
var Firstbox = $("#Firstbox").val();
var Secondbox = $("#Secondbox").val();
var apiKey = "52453f34dee0d65b1a41a02656142c6b";
if (inputType == 1) {
var SearchString = "https://api.openweathermap.org/data/2.5/weather" +
"?q=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 2) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?zip=" + Firstbox + "," + Secondbox +
"&APPID=" + apiKey;
} else if (inputType == 3) {
var SearchString = "http://api.openweathermap.org/data/2.5/weather" +
"?lat=" + Firstbox + "&lon=" + Secondbox +
"&APPID=" + apiKey;
}
$.getJSON(SearchString, function(obj) {
var city_name = obj["name"];
var country_name = obj["sys"]["country"];
var longitude = obj["coord"]["lon"];
var latitude = obj["coord"]["lat"];
var weather_description = obj["weather"][0]["description"];
var temp = obj["main"]["temp"] - 273.15;
var pressure = obj["main"]["pressure"];
var humidity = obj["main"]["humidity"];
var wind_speed = obj["wind"]["speed"];
var wind_direction = obj["wind"]["deg"];
var sunrise = new Date(obj["sys"]["sunrise"] * 1000);
var sunset = new Date(obj["sys"]["sunset"] * 1000);
let SearchResultsHTML = []
SearchResultsHTML.push("City: " + city_name);
SearchResultsHTML.push("Country: " + country_name);
SearchResultsHTML.push("Weather: " + weather_description);
SearchResultsHTML.push("<span id='longSpan'>Longitude: " + longitude + "</span>");
SearchResultsHTML.push("<span id='latSpan'>Latitude: " + latitude + "</span>");
SearchResultsHTML.push("<span id='tempSpan'>Temperature: " + temp + "</span>");
SearchResultsHTML.push("<span id='pressSpan'>Pressure: " + pressure + "</span>");
SearchResultsHTML.push("<span id='humSpan'>Humidity: " + humidity + "</span>");
SearchResultsHTML.push("<span id='wsSpan'>Wind Speed: " + wind_speed + "</span>");
SearchResultsHTML.push("<span id='wdSpan'>Wind Direction: " + wind_direction + "</span>");
SearchResultsHTML.push("<span id='sunupSpan'>Sunrise: " + sunrise.toLocaleTimeString + "</span>");
SearchResultsHTML.push("<span id='sundownSpan'>Sunset: " + sunset.toLocaleTimeString() + "</span>");
$("#SearchResults").html(SearchResultsHTML.join("<br/>"));
showSpans();
})
}
});
$(".ticksel").on("change", showSpans);
function showSpans() {
$(".ticksel input").each(function() {
const id = this.id;
const checked = this.checked;
if (id) {
const $span = $("#" + id + "span");
if ($span) $span.toggle(checked);
}
})
}
function displayError() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid) {
if (inputType == 1 || inputType == 2) {
alert("Country code must be 2 characters in length.");
} else {
alert("Longitude must be between -180 and 180");
}
} else {
if (inputType == 1) {
alert("City name must be longer than 1 character.");
} else if (inputType == 2) {
alert("Postal code must be 3 characters in length, following the format 'S4X'");
} else {
alert("Latitude must be between -90 and 90");
}
}
}
function checkValidity() {
var first = document.getElementById('Firstbox');
var second = document.getElementById('Secondbox');
if (first.validity.valid && second.validity.valid) {
return true;
} else {
displayError();
return false;
}
}
function checksSelected() {
}
});
.validated:valid {
background-color: #BDF0A8;
}
.validated:invalid {
background-color: #FAC3C9;
}
.row {
margin-bottom: 10px;
}
.ticksel {
border: solid black 1px;
}
tr,
td {
border: solid black 1px;
}
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>
<title>Final Project</title>
<link rel="stylesheet" type="text/css" href="weather.css">
<form id="searchForm" method="POST" action="URL">
<div class="row col-md-12">
<h2>OpenWeatherMap Weather Search</h2>
</div>
<div class="row">
<div class="col-md-6">
<h4>Search by:</h4>
<input id="Radio1" name="searchBy" type="radio" checked /> City Name<br/>
<input id="Radio2" name="searchBy" type="radio"> Postal Code<br/>
<input id="Radio3" name="searchBy" type="radio" /> Latitude / Longitude<br/>
</div>
<div class="col-md-6">
<h4>Show in search results:</h4>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="long" value="yes"> Longitude</div>
<div class="col ticksel"><input type="checkbox" checked id="lat" value=""> Latitude</div>
<div class="col ticksel"><input type="checkbox" checked id="temp" value=""> Temperature</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="press" value=""> Pressure</div>
<div class="col ticksel"><input type="checkbox" checked id="hum" value=""> Humidity</div>
<div class="col ticksel"><input type="checkbox" checked id="ws" value=""> Wind Speed</div>
</div>
<div class="row">
<div class="col ticksel"><input type="checkbox" checked id="wd" value=""> Wind Direction</div>
<div class="col ticksel"><input type="checkbox" checked id="sunup" value=""> Sunrise</div>
<div class="col ticksel"><input type="checkbox" checked id="sundown" value=""> Sunset</div>
</div>
</div>
</div>
<div class="row col-md-12">
<label id="lbl1">City Name:</label><input id="Firstbox" class="validated" type="text" required pattern=".{2,}" placeholder="Regina" />
<label id="lbl2">Country Code:</label><input id="Secondbox" class="validated" type="text" required pattern="[a-zA-Z]{2}" placeholder="ca" />
<input id="SearchButton" type="button" value="Search" />
</div>
</form>
<div class="row col-md-12">
<h4>Current Weather</h4>
</div>
<div class="row col-md-12">
<p id="SearchResults"></p>
</div>
<div class="row col-md-12">
<table width="100%">
<thead>
<tr>
<th>City</th>
<th>Country</th>
<th>Longitude</th>
<th>Latitude</th>
<th>Weather</th>
<th>Temperature</th>
<th>Pressure</th>
<th>Humidity</th>
<th>Wind Speed</th>
<th>Wind Direction</th>
<th>Sunrise</th>
<th>Sunst</th>
<th><a class="deleteAll" href="#">Clear Log</a></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>

form with dynamic time intervals and depending disabledTimeIntervals-settings

Using eonasdan/bootstrapdatetimepicker, I try to solve this:
How to set disabledTimeIntervals, minDate and maxDate for each dynamically created time-input-field? minDate and maxDate has to be set to the corresponding field, while disabledTimeIntervals has to be set to all fields, except the edited fields - also on every edit.
I do not have any glue to get this done.
Has anyone a solution for this?
$(document).ready(function() {
$("#timeday0from").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#timeday0until").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#timeday0from").on("dp.change", function(e) {
$("#timeday0until")
.data("DateTimePicker")
.minDate(e.date);
});
$("#timeday0until").on("dp.change", function(e) {
$("#timeday0from")
.data("DateTimePicker")
.maxDate(e.date);
});
});
var i = 0;
var day = "day_";
var original = document.getElementById(day + i);
function duplicateElement() {
var clone = original.cloneNode(true);
i++;
clone.id = day + i; // there can only be one element with an ID
clone.childNodes;
for (var input of $(".timeday0from", clone)) {
input.id = "time" + clone.id + "from";
}
for (var input of $(".timeday0until", clone)) {
input.id = "time" + clone.id + "until";
}
for (var select of $(".timeday0type", clone)) {
select.id = "time" + clone.id + "info";
}
for (var input of $(".timeday0from", clone)) {
input.name = "time[" + day + "][" + i + "][from]";
}
for (var input of $(".timeday0until", clone)) {
input.name = "time[" + day + "][" + i + "][until]";
}
for (var select of $(".timeday0type", clone)) {
select.name = "time[" + day + "][" + i + "][type]";
}
for (var input of $(".timeday0from", clone)) {
input.value = "";
}
for (var input of $(".timeday0until", clone)) {
input.value = "";
}
for (var select of $(".timeday0type", clone)) {
select.value = "";
}
original.parentNode.appendChild(clone);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<div class="col-lg-6 col-md-12">
<div class="well">
<h3>Day</h3>
<div class="row" id="day_0">
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0from" class="control-label">Interval starts</label>
<div class='input-group date' id='timeday0from'>
<input type="text" class="form-control datepicker timeday0from" name="time[day][0][from]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0until" class="control-label">Interval ends</label>
<div class='input-group date' id='timeday0until'>
<input type="text" class="form-control datepicker timeday0until" name="time[day][0][until]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-12">
<label for="timeday0info" class="control-label">Interval-Option</label>
<select name="time[day][0][info]" class="form-control timeday0type" id="timeday0info">
<option>Bitte auswählen</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default" onclick="duplicateElement();"><span class="glyphicon glyphicon-plus"></span></button>
Creating works. But I do not have any idea, how to set maxDate, minDate and disabledTimeIntervals (overlapping of ranges should prevented) on clone/remove of elemen and update of a time-field.
What a mess - but it works!
$.fn.datetimepicker.defaults.tooltips = {
today: 'Heute',
clear: 'Auswahl leeren',
incrementMinute: 'später',
decrementMinute: 'früher',
incrementHour: 'später',
decrementHour: 'früher',
pickHour: 'Stunde wählen',
pickMinute: 'Minute wählen'
};
$.fn.datetimepicker.defaults.useCurrent = false;
$.fn.datetimepicker.defaults.ignoreReadonly = true;
$.fn.datetimepicker.defaults.allowInputToggle = true;
$.fn.datetimepicker.defaults.locale = 'de';
$.fn.datetimepicker.defaults.showClear = true;
$(document).ready(function() {
initDateTimePair('day',0);
updateMin('day',0);
updateMax('day',0);
});
var i = 0;
var original = document.getElementById('day' +'_'+ i);
function initDateTimePair(day, item){
$("#time"+day+item+"from").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
$("#time"+day+item+"until").datetimepicker({
format: "LT",
allowInputToggle: true,
ignoreReadonly: true
});
}
function updateMax(day, item){
$("#time"+day+item+"from").on("dp.change", function(e) {
$("#time"+day+item+"until").data("DateTimePicker").minDate(e.date);
if($('#time'+day+item+'until').data("DateTimePicker")){
updateDisabledTimes(day, item);
}
});
}
function updateMin(day, item){
$("#time"+day+item+"until").on("dp.change", function(e) {
$("#time"+day+item+"from").data("DateTimePicker").maxDate(e.date);
if($('#time'+day+item+'from').data("DateTimePicker")){
updateDisabledTimes(day, item);
}
});
}
function initDisabledTimes(day, item){
var arr = collectDisabledTime(day, null);
$('#time'+day+item+'from').data("DateTimePicker").disabledTimeIntervals(arr);
$('#time'+day+item+'until').data("DateTimePicker").disabledTimeIntervals(arr);
}
function updateDisabledTimes(day, item){
for(l=0; l<=i; l++) {
var arr = collectDisabledTime(day, item);
if(l!=item){
$('#time'+day+l+'from').data("DateTimePicker").disabledTimeIntervals(arr);
$('#time'+day+l+'until').data("DateTimePicker").disabledTimeIntervals(arr);
}
}
}
function collectDisabledTime(day, item){
var arr = [];
for(j=0; j<=i; j++){
if(j!=item){
var from = $('#time'+day+j+'from').data("DateTimePicker");
var until = $('#time'+day+j+'until').data("DateTimePicker");
if(until !== undefined && until.date() !== null && from !== undefined && from.date() !== null){
arr.push([$('#time'+day+j+'from').data("DateTimePicker").date().add(1,'minute'), $('#time'+day+j+'until').data("DateTimePicker").date().add(-1,'minute')]);
}
}
}
return arr;
}
function duplicateElement(day) {
var clone = original.cloneNode(true);
i++;
clone.id = day + '_' + i; // there can only be one element with an ID
clone.childNodes;
for (var input of $(".time"+day+"from", clone)) {
input.id = "time" + day + i + "from";
}
for (var input of $(".time"+day+"until", clone)) {
input.id = "time" + day + i + "until";
}
for (var select of $(".time"+day+"type", clone)) {
select.id = "time" + day + i + "info";
}
for (var input of $(".time"+day+"from", clone)) {
input.name = "time[" + day + "][" + i + "][from]";
}
for (var input of $(".time"+day+"until", clone)) {
input.name = "time[" + day + "][" + i + "][until]";
}
for (var select of $(".time"+day+"type", clone)) {
select.name = "time[" + day + "][" + i + "][type]";
}
for (var input of $(".time"+day+"from", clone)) {
input.value = "";
}
for (var input of $(".time"+day+"until", clone)) {
input.value = "";
}
for (var select of $(".time"+day+"type", clone)) {
select.value = "-1";
}
original.parentNode.appendChild(clone);
initDateTimePair(day, i);
updateMin(day, i);
updateMax(day, i);
initDisabledTimes(day, i);
updateDisabledTimes(day, i);
console.log($('#timeday'+i+'from').data("DateTimePicker").disabledTimeIntervals())
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/de.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<div class="col-lg-6 col-md-12">
<div class="well">
<h3>Day</h3>
<div class="row" id="day_0">
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0from" class="control-label">Interval starts</label>
<div class='input-group date' id='timeday0from'>
<input type="text" class="form-control datepicker timedayfrom" name="time[day][0][from]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-6">
<label for="timeday0until" class="control-label">Interval ends</label>
<div class='input-group date' id='timeday0until'>
<input type="text" class="form-control datepicker timedayuntil" name="time[day][0][until]" readonly="readonly"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
<div class="form-group col-sm-4 col-xs-12">
<label for="timeday0info" class="control-label">Interval-Option</label>
<select name="time[day][0][info]" class="form-control timedaytype" id="timeday0info">
<option value="-1">Bitte auswählen</option>
</select>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-default" onclick="duplicateElement('day');"><span class="glyphicon glyphicon-plus"></span></button>

php ajax based form displaying blank page

I have created a eBay Item search form. I want to make form.html to form.php but when I change it to .php the form doesn't work and display blank page. you can see form.html here:
<script>
function showDetail(name){
$("."+name).collapse('toggle');
}
function getPage(num){
var data = {
"action": "test",
"pageNumber": num
};
data = $('form').serialize() + "&" + $.param(data);
// jQuery AJAX call to PHP Script with JSON Return
$.ajax({
type: "GET",
dataType: "json",
url: "advancedItemSearchTest.php", //Relative or absolute path to response.php file
data: data,
success: function(new_data) {
$( ".container" ).hide();
$( ".the-return" ).html( "" );// clear all the contents first
if(new_data['ack'] != 'Success' || new_data['resultCount'] <= 0){
$( ".the-return" ).html( "<h2>No Results were found</h2>" );
}
else{
for ( var i = 0; i < new_data.itemCount; i++ ) {
var $media = $( '<div class = "media"></div>');
var $media_body = $( '<div class = "media-body"></div>');
var $a_class = $('<a class= "pull-left"></a>');
var $name = 'name' + i;
//<img class = "media-object" src = alt = "Item Image" />
//<?php echo $item->title ?>
var $item = new_data['item'][i];
var $imageURL = $item['basicInfo']['galleryURL'];
var $price = $item['basicInfo']['convertedCurrentPrice']
var $title = '<a href = '+ $item['basicInfo']['viewItemURL']+ '>' + $item['basicInfo']['title'] + '</a>';
var $image = '<img class = "media-object" src =' + $imageURL +'alt = "Item Image" style="width:96px;height:96px" data-toggle="modal" data-target="#myModal'+ $name +'"/>';// concatenating string must use+ for variable!!
var $modal = $('<div class="modal fade" id="myModal'+ $name +'" role="dialog"></div>');
var $modalDialog = $('<div class="modal-dialog"></div>');
var $modalContent = $('<div class="modal-content"></div>');
$modalContent.append($('<div class="modal-header"></div>').append('<h4 class="modal-title">'+$item['basicInfo']['title']+'</h4>'));
$modalContent.append($('<div class="modal-body"></div>').append('<img src='+$item['basicInfo']['pictureURLSuperSize']+' alt="Item image" style="width:512px;height:512px" align="middle">'));
$modalContent.append($('<div class="modal-footer"></div>').append('<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>'));
$modalDialog.append($modalContent);
$modal.append($modalDialog);
var $shippingCost = "(Free Shipping)";
if($item['basicInfo']['shippingServiceCost'] > 0){
$shippingCost = "(+$" + $item['basicInfo']['shippingServiceCost'] + ")";
}
$price = "<b>" + "Price:$" + $price + "</b>";
var $location = "<i>" + "Location:"+ $item['basicInfo']['location'] + "</i>";
var $topRated = "";
if($item['basicInfo']['topRatedListing']){
$topRated = '<img src =' + 'http://cs-server.usc.edu:45678/hw/hw8/itemTopRated.jpg' +' alt = "Top Rated" style="width:32px;height:24px" />';
}
var $collapse = $('<div class="collapse '+ $name +'"></div>');//
var $ul = $('<ul class="nav nav-tabs"></ul>');
$ul.append($('<li class="active"><a data-toggle="tab" href="#basic'+ $name +'">Basic Info</a></li>'));
$ul.append($('<li><a data-toggle="tab" href="#seller'+ $name +'">Seller Info</a></li>'));
$ul.append($('<li><a data-toggle="tab" href="#shipping'+ $name +'">Shipping Info</a></li>'));
$collapse.append($ul);
var $tabContend = $('<div class="tab-content"></div>');
var $basic = $('<div id="basic'+ $name +'" class="tab-pane fade in active"></div>');
var $table = $('<tbody></tbody>');//$('<table class = "table table-striped" ></table>');
var $tr = $('<tr></tr>');
$tr.append('<td><b>Condition</b></td>' + '<td>'+$item['basicInfo']['conditionDisplayName']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Category Name</b></td>' + '<td>'+$item['basicInfo']['categoryName']+'</td>');
$table.append($tr);
$tabContend.append($basic.append($('<table class = "table table-striped" ></table>').append($table)));
var $seller = $('<div id="seller'+ $name +'" class="tab-pane fade"></div>');
$table = $('<tbody></tbody>');//$('<table class = "table table-striped""></table>');
$tr = $('<tr></tr>');
$tr.append('<td><b>User name</b></td>' + '<td>'+$item['sellerInfo']['sellerUserName']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Feedback score</b></td>' + '<td>'+$item['sellerInfo']['feedbackScore']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Positive feedback</b></td>' + '<td>'+$item['sellerInfo']['positiveFeedbackPercent']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
var $storeName = 'N/A';
if($item['sellerInfo']['sellerStoreName']!=''){
$storeName = $item['sellerInfo']['sellerStoreName'];
}
$tr.append('<td><b>Store name</b></td>' + '<td>'+$storeName+'</td>');
$table.append($tr);
$tabContend.append($seller.append($('<table class = "table table-striped" ></table>').append($table)));
var $shipping = $('<div id="shipping'+ $name +'" class="tab-pane fade"></div>');
$table = $('<tbody></tbody>');//$('<table class = "table table-striped""></table>');
$tr = $('<tr></tr>');
$tr.append('<td><b>Shipping type</b></td>' + '<td>'+$item['shippingInfo']['shippingType']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Handling time</b></td>' + '<td>'+$item['shippingInfo']['handlingTime']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
$tr.append('<td><b>Shipping locations</b></td>' + '<td>'+$item['shippingInfo']['shipToLocations']+'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//&#10004(correct) &#10008(wrong)
var $mark = "&#10008";
if($item['shippingInfo']['expeditedShipping']){
$mark = "&#10004";
}
$tr.append('<td><b>Expedited shipping</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//&#10004(correct) &#10008(wrong)
var $mark = "&#10008";
if($item['shippingInfo']['returnsAccepted']){
$mark = "&#10004";
}
$tr.append('<td><b>Return accepted</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tr = $('<tr></tr>');
//&#10004(correct) &#10008(wrong)
var $mark = "&#10008";
if($item['shippingInfo']['oneDayShippingAvailable']){
$mark = "&#10004";
}
$tr.append('<td><b>One day shipping</b></td>' + '<td>'+ $mark +'</td>');
$table.append($tr);
$tabContend.append($shipping.append($('<table class = "table table-striped" ></table>').append($table)));
$collapse.append($tabContend);
var $viewDetail= '<a onclick="showDetail(\'' + $name +'\')">View Detail</a>';//'+$name+'
$media.append($a_class.html( $image));
$media_body.append($collapse);
$media_body.prepend( '<font size="4">' + $title + '</font>' + '<br/>' + $price + $shippingCost + ' ' + $location + ' ' + $topRated + ' ' + $viewDetail );
$media.append($media_body);
$media.appendTo( $( ".the-return" ) );
$modal.appendTo( $( ".the-return" ) );
}
var $pagination = $('<div class = "pagination"></div>');
var $ul = $('<ul class="pagination"></ul>');
var $prev = num - 1;
if( num == 1){
$pagination.append($ul.append('<li class="disabled">' + '<<' + '</li>'));
}
else{
$pagination.append($ul.append('<li>' + '<<' + '</li>'));
}
for( var i = num; i < num+5; i++ ){
$pagination.append($ul.append('<li>' + i + '</li>'));
}
var $next = num + 1;
if( num == new_data['totalPages']){
$pagination.append($ul.append('<li class="disabled">' + '>>' + '</li>'));
}
else{
$pagination.append($ul.append('<li>' + '>>' + '</li>'));
}
var $itemFrom = (num-1) * Number(new_data.itemCount) + 1;
var $itemTo = $itemFrom + Number(new_data.itemCount) - 1;
var $resultNum = $( '<div class = "resultNum" ></div>').append( '<b><font size="5">'+$itemFrom +'-'+ $itemTo + ' items out of ' + new_data['resultCount'] +'</font></b>');
$resultNum.prependTo($( ".the-return" ));
$pagination.appendTo( $( ".the-return" ) );
}
},
error: function(jqXHR, textStatus, errorThrown){
//alert('error: ' + textStatus + ': ' + errorThrown);
}
});
}
$(document).ready(function(){
$('form').validate({
rules: {
keyword: { // should be name, not id!
required: true
},
priceLow: {
number: true,
digits: true
},
priceHigh: {
number: true,
digits: true
},
shippingTime:{
number: true,
digits: true
}
},
messages:{
keyword: { // should be name, not id!
required: "Please enter a keyword"
},
priceLow: {
number: "Price should be a valid number",
digits: "Price should be a valid number",
min : "Minimum price cannot be below 0"
},
priceHigh: {
number: "Price should be a valid number",
digits: "Price should be a valid number",
min : "Maximum price cannot be less than minimum price or below 0"
},
shippingTime:{
number: "Max handling time should be a valid digit",
digits: "Max handling time should be a valid digit",
min: "Max handling time should be greater than or equal to 1"
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-error');
},
errorElement: 'span',
errorClass: 'help-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$('form').submit(function(){
//var num = 1;
getPage(1);
return false;
});
}); // end document.ready
</script>
</head>
<body>
<style>
.center_div{
margin: 0 auto;
width:80%;
}
</style>
<div class = "container center_div" >
<img src = " http://cs-server.usc.edu:45678/hw/hw8/ebay.jpg" class="img-responsive"><br>
<form class = "form-horizontal" action = "advancedItemSearchTest.php" method="GET" role = "form" id = "myForm" accept-charset="utf-8">
<div class = "form-group">
<label class="control-label col-sm-2" for="keyword">Key words:*</label>
<div class="col-sm-8">
<input type = "text" class="form-control" id = "keyword" name = "keyword" placeholder="Enter keyword">
</div>
<label class="control-label col-sm-2" for="keyword">APP ID</label>
<div class="col-sm-8">
<input type = "text" class="form-control" id = "appid" name = "appid" placeholder="Enter appID">
</div>
</div>
<div class = "form-group row">
<label class="control-label col-sm-2" for="priceLow">Price range: </label>
<div class="col-sm-4">
<input type = "number" class="form-control" name = "priceLow" id = "priceLow" min="0" placeholder="from($)">
</div>
<label class="control-label " for="priceHigh"> </label>
<div class="col-sm-4">
<input type = "number" class="form-control" name = "priceHigh" id = "priceHigh" min="0" placeholder="to($)">
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="conditionNew">Condition: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "conditionNew" name = "condition[]" value=1000>New</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=3000>Used</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=4000>Very Good</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=3000>Good</label>
<label class="checkbox-inline"><input type="checkbox" name = "condition[]" value=4000>Acceptable</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="formats">Buying formats: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "formats" name = "BuyFormat[]" value="FixedPrice">Buy It Now</label>
<label class="checkbox-inline"><input type="checkbox" name = "BuyFormat[]" value="Auction">Auction</label>
<label class="checkbox-inline"><input type="checkbox" name = "BuyFormat[]" value="Classified">Classified Ad</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="shipping">Shipping: </label>
<div class="col-sm-8">
<label class="checkbox-inline"><input type="checkbox" id = "shipping" name = "FreeShippingOnly" value="true">Free Shipping</label>
<label class="checkbox-inline"><input type="checkbox" name = "ExpeditedShippingType" value="Expedited">Expedited shipping</label>
</div>
</div>
<div class = "form-group">
<label class="control-label col-sm-2" for="shippingTime"> </label>
<div class="col-sm-8">
<input type = "number" class="form-control" name = "shippingTime" id = "shippingTime" min="1" placeholder="Max handling time(days)">
</div>
</div>
</div>
</div>
<div class="form-group col-sm-10" align="right">
<input type="reset" class="btn btn-default" value="Clear" >
<input type="submit" class="btn btn-primary" value="Search">
</div>
</form>
when form is in .html extension it works fine but when I change it to .php it display blank page.
Change the last button type from submit to button.
In submit It will redirect on new page.

selecting both radio buttons

NO JQUERY! I have two radio buttons and for some reason I can select both of them and I only want to be able to select one. For example, if you select Have a Baby, you can choose both radio buttons. Is there a simple way to fix this? Can someone help me achieve this by fixing the error in my code?
http://jsfiddle.net/LuzkA/
<html>
<head>
<title>Life Event Picker Calendar</title>
<script>
function changeMessage(oElement) {
var rd1 = document.getElementById("rd1");
var rd1Text = rd1.parentNode.getElementsByTagName('span')[0];
var rd2 = document.getElementById("rd2");
var rd2Text = rd2.parentNode.getElementsByTagName('span')[0];
document.getElementById('choice').innerHTML = "Radio Choice=";
rd1.checked = false;
rd2.checked = false;
//nothing
if (oElement.value == "0") {
document.getElementById("btn").style.display = "none";
document.getElementById("radio").style.display = "none";
document.getElementById("day").innerHTML = "Date";
//have a baby
} else if (oElement.value == "100") {
document.getElementById("btn").style.display = "none";
document.getElementById("radio").style.clear = "both";
document.getElementById("radio").style.display = "inline-block";
rd1Text.innerHTML = "C-Section";
rd2Text.innerHTML = "Regular Birth";
rd1.value = "C-Section";
rd2.value = "Regular Birth";
document.getElementById("day").innerHTML = "Anticipated Due Date";
//military leave
} else if (oElement.value == "15") {
document.getElementById("btn").style.display = "none";
document.getElementById("radio").style.clear = "both";
document.getElementById("radio").style.display = "inline-block";
rd1Text.innerHTML = "Training";
rd2Text.innerHTML = "Active Duty";
rd1.value = "Training";
rd2.value = "Active Duty";
document.getElementById("day").innerHTML = "Anticipated Leave Date";
//get married
} else if (oElement.value == "5") {
document.getElementById("btn").style.display = "inline-block";
document.getElementById("radio").style.display = "none";
document.getElementById("day").innerHTML = "Marriage Date";
//adopt a child
} else if (oElement.value == "90") {
document.getElementById("btn").style.display = "inline-block";
document.getElementById("radio").style.display = "none";
document.getElementById("day").innerHTML = "Anticipated Adoption Date";
//retire
} else if (oElement.value == "35") {
document.getElementById("btn").style.display = "inline-block";
document.getElementById("radio").style.display = "none";
document.getElementById("day").innerHTML = "Anticipated Retirement Date";
//medical leave
} else if (oElement.value == "25") {
//document.getElementById("btn").style.display = "inline-block";
document.getElementById("radio").style.display = "none";
document.getElementById("day").innerHTML = "Anticipated Disability Date";
} else {}
return;
}
function showChoice(input) {
document.getElementById('choice').innerHTML = "Radio Choice=" + input.value;
document.getElementById("btn").style.display = "inline-block";
}
//gets info picked and displays messages
function getInfo() {
var myDate=new Date();
var ev_num = parseInt(document.getElementById("leave").value)
myDate.setFullYear(sel_year.value,sel_month.value,sel_day.value);
var event_value = document.getElementById("leave").value;
//document.getElementById("date").innerHTML = "The date you have selected to begin your time of absence is ..." + "<b>" + myDate + "</b>";
//if ((document.getElementById("rd1").checked) == true) {
//document.write(document.getElementById("rd1").value);}
//get married
if (event_value == 5) {
//have a baby
} else if (event_value == 100) {
var first_number = new Date(myDate);
first_number.setDate(myDate.getDate() + 31);
var second_number = new Date(myDate);
second_number.setDate(myDate.getDate() - 30);
var third_number = myDate.getDate() + 7;
var fourth_number;
var fifth_number1;
var fifth_number2;
//if the first radio button has been selected
if ((document.getElementById("rd1").checked) == true) {
fourth_number = myDate.getDate() + 56;
fifth_number1 = myDate.getDate() + 57;
fifth_number2 = myDate.getDate() + 91;
//if the second radio button has been selected
} else {
fourth_number = myDate.getDate() + 42;
fifth_number1 = myDate.getDate() + 43;
fifth_number2 = myDate.getDate() + 91;
}
document.getElementById("message1").innerHTML = "From " + myDate + " through " + first_number + "<br/>" + "You are eligible to update coverage and personal information through your 'Have a Baby' Life Event.";
document.getElementById("message2").innerHTML = "From " + second_number + " through " + myDate + "<br/>" + "1) Call 1-877-968-7762 to initiate your leave. <br/>" + "2) Complete Authorization Release Form.";
//adopt a child
} else if (event_value == 90) {
//retire
} else if (event_value == 35) {
//military leave
} else if (event_value == 15) {
//medical leave
} else if (event_value == 25) {
} else {}
//document.getElementById("event").innerHTML = "Based on the event you have selected you will miss ... " + "<b>" + document.getElementById("leave").value + " days." + "</b>";
//myDate.setDate(myDate.getDate() + ev_num);
//document.getElementById("return").innerHTML = "You will be expected back on ..." + "<b>" + myDate + "</b>";
}
</script>
</head>
<body>
Life Event Picker Calendar<br>
<hr align="left" width="200px"/>
<div id="life" style="display:inline-block;">Life Event</div><div id="day" style="display:inline-block; margin-left:100px;">Date</div><br>
<select style="float:left;" id="leave" onchange="changeMessage(this);">
<option value="0"></option>
<option value="5">Get Married</option>
<option value="100">Have a Baby</option>
<option value="90">Adopt a Child</option>
<option value="35">Retire</option>
<option value="15">Military Leave</option>
<option value="25">Medical Leave</option>
</select>
<div id="calendar-container" style="float:left;" ></div>
<button id="btn" style="display:none;" onclick="getInfo()"type="button">Process</button>
<br>
<div id="radio" style="display:none">
<label><span></span><input type="radio" name="" id="rd1" value="" onclick="showChoice(this)"/></label>
<label><span></span><input type="radio" name="" id="rd2" value="" onclick="showChoice(this)"/></label>
</div>
<div id="choice">Radio Choice</div><br>
<div id="date"></div>
<div id="event"></div>
<div id="return"></div>
<div id="yourdate"></div>
<div id="message1">Message 1</div><br>
<div id="message2">Message 2</div><br>
<div id="message3">Message 3</div><br>
<div id="message4">Message 4</div><br>
<div id="message5">Message 5</div>
You have no name so that is why you can select both of them. Give them the same name! The browser will take care of only letting the user select one.
<input type="radio" name="radiobtn" id="rd1" value="" onclick="showChoice(this)"/>
<input type="radio" name="radiobtn" id="rd2" value="" onclick="showChoice(this)"/>
You have to give the radio buttons a name. easy Peasy
<div id="radio">
<label><span></span><input type="radio" name="boom" id="rd1" value="" onclick="showChoice(this)"/></label>
<label><span></span><input type="radio" name="boom" id="rd2" value="" onclick="showChoice(this)"/></label>
Your radio buttons need the "name" attribute to not be empty.
http://jsfiddle.net/LuzkA/1/
<label><span></span><input type="radio" name="something" id="rd1" value="" onclick="showChoice(this)"/></label>
<label><span></span><input type="radio" name="something" id="rd2" value="" onclick="showChoice(this)"/></label>
Your radio buttons don't have name values.
Only if they have name values they can be grouped as radio buttons
Without name
<form>
<input type="radio" id="id1" name="" value="aa" />aa<br>
<input type="radio" id="id2" name="" value="bb" />bb<br>
</form>
<hr />
With name
<form>
<input type="radio" id="id3" name="a" value="aa" />aa<br>
<input type="radio" id="id4" name="a" value="bb" />bb<br>
</form>

Categories

Resources