I need some help. I need to reset all li elements again which are auto created by chosen-select jQuery plug-in.
<link href="css/chosen.css" rel="stylesheet">
<script type="text/javascript" src="js/chosen.jquery.js"></script>
<div class="popover-content">
<p>
<select class="chosen-select text-left" style="width:100%;" onchange="setCountry();" id="conid">
<option value="" selected>Select Country</option>
<?php
foreach ($country as $v) {
?>
<option value="<?php echo $v['country_id']; ?>"><?php echo $v['country_name']; ?></option>
<?php
}
?>
</select>
</p>
</div>
<div id="popupcity" class="popover" style="width:270px">
<div class="arrow"></div>
<h3 class="popover-title">Select City</h3>
<div class="popover-content" id="ctchoosen">
<p>
<select class="text-left" style="width:100%;" id="ctid" onchange="setCity();">
<option value="" selected>Select City</option>
</select>
</p>
</div>
</div>
When the user selects the country, the city values will be added into the city select list.
function setCountry(){
var conval=document.getElementById('conid');
var selectVal='';
if (conval.selectedIndex == -1){
return null;
}else{
selectVal=conval.options[conval.selectedIndex].text;
$("#popupcountry").removeClass("in");
}
document.getElementById('bindCon').innerHTML=selectVal;
$('#borderCon').css('border', '');
//console.log('contr',conval.options[conval.selectedIndex].value);
var url="common.php?action=getCity";
$.post(url,{"con_data":conval.options[conval.selectedIndex].value},function(data){
var obj=JSON.parse(data);
console.log('data1',obj);
var ctData='';
$('#ctid').find('option').not(':first').remove();
$('#ctid').removeClass('chosen-select');
$('.chosen-select').chosen();
if(obj.isData==1){
ctData=obj.cid;
$.each(ctData, function(idx, o) {
$("#ctid").append("<option value="+o.city_id+">"+o.city_name+"</option>");
//$("#ctchoosen > ul").append('<li class="active-result" data-option-array-index='+this.city_id+'>'+this.city_name+'</li>');
})
$('#ctid').addClass('chosen-select');
$('.chosen-select').chosen();
}
})
}
When the user selects any option in the country select list, the cities are appending and I need the cities in the select box/auto created list item elements to update.
I can reset the select box but am unable to reset the auto created list item elements for which when user is selecting any new country the cities belongs to this is not displaying to user. I am also using PHP for the database operations.
Chosen offers an event that can be triggered. From the documentation:
Updating Chosen Dynamically
If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.
$("#form_field").trigger("chosen:updated");
1
When the city list has options, instead of just calling
$('.chosen-select').chosen();
after adding the cities, trigger the updated event on it:
$('#ctid').trigger("chosen:updated");
See a demonstration of this below.
//track whether options have been added to the list
var cityOptionsAdded = false;
function setCountry() {
var conval = document.getElementById('conid');
var selectVal = '';
if (conval.selectedIndex == -1) {
return null;
} else {
selectVal = conval.options[conval.selectedIndex].text;
$("#popupcountry").removeClass("in");
}
$('#borderCon').css('border', '');
var url = conval.options[conval.selectedIndex].value + ".json";
$.post(url, function(obj) {
var ctData = '';
$('#ctid').find('option').not(':first').remove();
$('#ctid').removeClass('chosen-select');
chosenSelect = $('.chosen-select').chosen();
if (obj.isData == 1) {
ctData = obj.cid;
$.each(ctData, function(idx, o) {
$("#ctid").append("<option value=" + o.city_id + ">" + o.city_name + "</option>");
});
if (cityOptionsAdded) { //subsequent addition of cities to list
$('#ctid').trigger("chosen:updated");
} else { //first time adding cities to list
cityOptionsAdded = true;
$('#ctid').addClass('chosen-select');
chosenSelect = $('.chosen-select').chosen();
}
}
});
}
/**override jQuery ajax for this sandbox
because real AJAX requests are disabled
in this environment
*/
$.post = function(url, callback) {
var data;
if ($('#conid').val() == 'CA') {
data = {
"isData": true,
"cid": [{
"city_id": "OT",
"city_name": "Ottowa"
}, {
"city_id": "VA",
"city_name": "Vancouver"
}]
};
}
if ($('#conid').val() == 'SE') {
data = {
"isData": true,
"cid": [{
"city_id": "ST",
"city_name": "Stockholm"
}, {
"city_id": "LU",
"city_name": "Lund"
}]
};
}
callback(data);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.7.0/chosen.min.css" />
<div class="popover-content">
<p>
<select class="chosen-select text-left" style="width:100%;" onchange="setCountry()" id="conid">
<option value="" selected>Select Country</option>
<option value="CA">Canada</option>
<option value="SE">Sweden</option>
</select>
</p>
</div>
<div id="popupcity" class="popover" style="width:270px">
<div class="arrow"></div>
<h3 class="popover-title">Select City</h3>
<div class="popover-content" id="ctchoosen">
<p>
<select class="text-left" style="width:100%;" id="ctid">
<option value="" selected>Select City</option>
</select>
</p>
</div>
</div>
1https://harvesthq.github.io/chosen/#change-update-events
Related
The multiselect dependent dropdown code below works perfectly. The issue is that I need this to be displayed in a "Select Option Box," similar to a Pillbox, and when the user clicks on it, it should show a value option in a dropdown from which the user can choose a value from Country and State ..
Need this to be displayed and work like a "Select Option Box," similar to this Example - ( Multiselect → Basic example) Link → https://mdbootstrap.com/docs/standard/extended/multiselect/#example2
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form-signin" method="post" id="serchform" action="search-profile-result.php?page_id=1">
<label for="country">Country</label>
<select class="form-control" id="country" name="country[]" required="required" multiple>
<option value="USA" label="USA">USA</option>
<option value="UK" label="UK">UK</option>
<option value="Canada" label="Canada">Canada</option>
</select>
<label for="state">State</label>
<select id="state" name="state[]" class="form-control" required="required" multiple>
<option disabled>Select Country First</option>
</select>
</form>
<script>
$(function() {
//Populate an Object: { Country: [ States... ] }
var states = {};
states['USA'] = new Array('Alabama', 'Alaska', 'Arizona', 'Other');
states['UK'] = new Array('Aberdeenshire', 'Angus', 'Antrim', 'Other');
states['Canada'] = new Array('Alberta', 'British-Columbia', 'Manitoba', 'Other');
$("#country").change(function() {
// Array Variable to contain all selected
var selected = [];
// Iterate all selected items
$.each($(this).val(), function(i, country) {
selected = selected.concat(states[country]);
});
// Remove previous options
$("#state > option").remove();
if (selected.length === 0) {
// Add placeholder and Stop
$("#state").append("<option disabled>Select Country First</option>");
return false;
}
selected.sort();
// Populate Options
$.each(selected, function(i, state) {
$("<option>").html(state).appendTo("#state");
});
});
});
</script>
I'm very new to JavaScript, so I'm having a hard time with this relatively simple problem:
I wrote a function that dynamically adds or removes dropdown fields to the DOM if the user clicks the add or remove button. So far so good, everything is working fine until here.
Now I want to collect the data in an Array to send it to the api.
With the following code I can collect it, but I have a hard time to figure out how I can remove specific values from the array.
<div class="container mt-2" id="stores">
<div class="row">
<div class="col">
<h2>Marktet</h2>
<div class="col-form-label storesHint">Select at least one market</div>
</div>
</div>
<div id="form">
<div>
<div id="addAnotherMarket">
<div class="marketRow">
<select class="form-control" id="market" name="market">
<option value="1"> market1</option>
<option value="2"> market2</option>
<option value="3"> market3</option>
<option value="4"> market4</option>
<option value="5"> market5</option>
</select>
<input class="deleteButton" type="button" id="remove" value="" style="display: none; font-family: FontAwesome, 'Helvetica Neue', Helvetica, Arial, sans-serif;">
</div>
</div>
</div>
</div>
<div>
<div class="addBtnContainer">
<div class="centerBtn">
<a class=" button btn_gray buttonWithIcon" id="add">
<i class=" fa fa-plus icn" id="btnIcon" style="font-size: 16px;" aria-hidden="true"></i>
<span class="btnText spn" style="top:0px !important">Add another market</span>
</a>
</div>
</div>
</div>
</div>
$(document).ready(function () {
let index = 0;
let store = {};
let stores = [];
var oldValue = [];
window.Stores = stores;
//set initial value for the first dropdown element
store = { "store_id": parseInt($('#market').val(), 10) };
stores.push(store);
oldValue[index] = store;
//update value if user changes first element
$('#market').on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add a new dropwdown element
$("#add").click(function () {
index++;
$(this).parent().parent().before($("#form").clone().attr("id", "form" + index));
$("#form" + index + " :input").each(function () {
$(this).attr("name", $(this).attr("name") + index);
$(this).attr("id", $(this).attr("id") + index);
});
//set initial value of the new dropdown element
store = { "store_id": parseInt($('#market' + index).val(), 10) };
stores.push(store);
oldValue[index] = store;
//set new value if user changes value
$('#market' + index).on('change', function () {
store = { "store_id": parseInt($(this).val(), 10) };
var eleIndex = stores.indexOf(oldValue[index]);
if (eleIndex !== -1) {
stores.splice(eleIndex, 1, store);
oldValue[index] = store;
}
});
//add remove button
$("#remove" + index).css("display", "inline-flex");
$(".marketRow").css({
'display': 'flex',
'align-items': 'center',
'margin-top': '5px'
});
//if user clicks remove button delete value from array
$("#remove" + index).click(function () {
var eleIndex = stores.indexOf({ "store_id": parseInt($('#market' + index).val(), 10) });
if (index !== -1) {
stores.splice(eleIndex, 1);
oldValue.splice(eleIndex);
}
$(this).closest("div").remove();
});
});
});
The following code also outputs -1 always, so I think indexOf makes no sense.
var eleIndex = stores.indexOf({"store_id": parseInt($('#market' + index).val(), 10)});
EDIT: I updated the post with the HTML part as requested. In short: When clicking on button(#add) div(#form) will be cloned, remove button will be added, and id's will be updated with index.
Values of all these selects will be stored and updated in the stores array. I just can't delete them.
I have also provided a working jsfiddel https://jsfiddle.net/proach1995/h1gtmyen/
With plain js you can add class to the dropdown you wish to collect from. in the code below it will build the array only if value was selected.
if you use jQuery you can replace document.querySelectorAll('.store'); with $('.store');
function saveArray() {
const selected = document.querySelectorAll('.store');
const stores = [];
selected.forEach(prop => {
if (!!prop.value) {
stores.push({store_id: parseInt(prop.value, 10)})
}
});
console.log(stores);
}
<select class="store">
<option disabled selected value>select value</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<select class="store">
<option disabled selected value>select value</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
<button onclick="saveArray()">save array</button>
I have 2 multi-select boxes like this
<div class="form-group mb-3">
<p class="mb-1 font-weight-bold text-muted mt-3 mt-md-0">Addons</p>
<p class="text-muted font-13">Select multiple Addons</p>
<select class="form-control select2-multiple" id="multi-select-add-ons" data-toggle="select2"
multiple="multiple" data-placeholder="Choose ..." style="width: 100%;">
<optgroup label="Select addons..">
#foreach ($addons as $a)
<option value="{{$a->id}}">{{ $a->name }}</option>
#endforeach
</optgroup>
</select>
<div class="form-group">
<input id="resultAddons" type="hidden" name="addons_id">
</div>
</div>
<div class="form-group mb-3">
<label for="simpleinput">SubAddons</label>
<select name="" id="subAddons" class="form-control select2-multiple" data-toggle="select2" multiple="multiple" data-placeholder="Choose ..." style="width: 100%;">
<optgroup label="Select subaddons..">
<option value="0"></option>
</optgroup>
</select>
<div class="form-group">
<input id="resultSubAddons" type="hidden" name="sub_addons_id">
</div>
</div>
Ok so I am using the following code in Script section to get data from Api
<script>
$('select').change(function () {
var addons = $("#multi-select-add-ons").val();
//console.log(addons);
$('#subAddons').find('option').not(':first').remove();
addons.map(item => getSubAddonsByAddon(item)) //call subaddons by addon id api
addons = addons.join(", ");
document.getElementById('resultAddons').value = addons;
});
function getSubAddonsByAddon(id) {
let baseUrl = 'http://localhost.test/add-ons/'
var xhr = new XMLHttpRequest();
xhr.open("GET", `${baseUrl}show/${id}/sub-add-ons`, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
let data = JSON.parse(this.response);
let complexArr = [data][0].data;
complexArr.forEach(element => {
// console.log(element.name);
getSubAddonIdAndName(element);
});
}
}
xhr.send();
}
let subAddonID, name;
function getSubAddonIdAndName(data) {
this.subAddonID = data.id;
this.name = data.name;
$("#subAddons").append($('<option>', {
value: data.id ,
text: data.name
}));
}
</script>
Here's how it looks, the code works fine, the 2nd select (sub-addons) dropdown is updated as per the selection of addons, how the name is not displayed inside the select box text field
After selecting a value from 2nd select box, the value is not displayed like the first select box value's
It goes back to "Choose..." instead of displaying name like first box
To show option inside select-box textfield you can add selected: true line when you append new option inside your select2 and then $("#subAddons").trigger("change") to update your select2 plugin .
Then , your second issue is because of $('select').change(function () { line as you have use select as selector so when you change option inside your second select-box this event gets called and option are getting again updated . So , to avoid this just use more specific selector i.e : select#multi-select-add-ons
Demo Code :
$("#multi-select-add-ons ,#subAddons").select2()
//be more specific here
$('select#multi-select-add-ons').change(function() {
var addons = $("#multi-select-add-ons").val();
$('#subAddons').find('option:not(:first)').remove();
addons.map(item => getSubAddonsByAddon(item))
addons = addons.join(", ");
document.getElementById('resultAddons').value = addons;
});
function getSubAddonsByAddon(id) {
/*let baseUrl = 'http://localhost.test/add-ons/'
var xhr = new XMLHttpRequest();
xhr.open("GET", `${baseUrl}show/${id}/sub-add-ons`, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
let data = JSON.parse(this.response);*/
//suppose this is data came from server
let data = [{
"data": [{
"id": 1,
"name": "abc"
}, {
"id": 2,
"name": "ace"
}]
}]
let complexArr = data[0].data;
complexArr.forEach(element => {
getSubAddonIdAndName(element);
});
$("#subAddons").trigger("change") //after appending options refresh select2
/*}
}
xhr.send();*/
}
let subAddonID, name;
function getSubAddonIdAndName(data) {
this.subAddonID = data.id;
this.name = data.name;
$("#subAddons").append($('<option>', {
value: data.id,
text: data.name,
selected: true //add this
}));
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>
<div class="form-group mb-3">
<p class="mb-1 font-weight-bold text-muted mt-3 mt-md-0">Addons</p>
<p class="text-muted font-13">Select multiple Addons</p>
<select class="form-control select2-multiple" id="multi-select-add-ons" data-toggle="select2" multiple="multiple" data-placeholder="Choose ..." style="width: 100%;">
<optgroup label="Select addons..">
<option value="1">A</option>
<option value="2">A2</option>
<option value="3">A3</option>
</optgroup>
</select>
<div class="form-group">
<input id="resultAddons" type="hidden" name="addons_id">
</div>
</div>
<div class="form-group mb-3">
<label for="simpleinput">SubAddons</label>
<select name="" id="subAddons" class="form-control select2-multiple" data-toggle="select2" multiple="multiple" data-placeholder="Choose ..." style="width: 100%;">
<optgroup label="Select subaddons..">
<option value="0"></option>
</optgroup>
</select>
<div class="form-group">
<input id="resultSubAddons" type="hidden" name="sub_addons_id">
</div>
</div>
if you are using a library for the multiple select, what happens is the library runs a handling method on your inputs for whatever data it has for the first time, if you append more data to it you need to re-call the handle method of that library.
I'm having a problem upon changing the code below "${region.code}" into "${region.name}"
regOpt += `<option value='${region.code}'> ${region.altName}</option>`;
What I want is to get the names of the region instead of the value on submit form but the problem is when I change the value into name I'm getting errors and the 2nd & 3rd dropdown won't show. probably because I'm using multiple JSON file and it filter the values to connect the files.
JS
$(function(){
let regOpt = "";
let provOption = "";
let cityOption = "";
//FOR REGION
$.getJSON('regions.json', function(result){
regOpt += `<option value="" disabled selected hidden>Region</option>`;
$.each(result.sort(), function(i, region){
regOpt += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regOpt);
});
//FOR PROVINCE
$('#region').change(function(){
let values = $(this).val();
$.getJSON('provinces.json', function(result){
let items = $(result).filter(function(i, n){
return n.region === values;
});
provOption += `<option value="" disabled selected hidden>Province</option>`;
//loop through dates
$.each(items, function(region, province){
provOption += `<option value='${province.code}'> ${province.name}</option>`;
});
$('#province').html(provOption);
});
});
//FOR CITY
$('#province').change(function(){
let values = $(this).val();
$.getJSON('citiesMunicipalities.json', function(result){
let items = $(result).filter(function(i, n){
return n.province === values;
});
cityOption += `<option value="" disabled selected hidden>City</option>`;
$.each(items, function(province, city){
cityOption += `<option value='${city.code}'> ${city.name}</option>`;
});
$('#city').html(cityOption);
});
});
});
</script>
HTML code
<div class="container form-group">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region">
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province">
<option value=""> Select Province</option>
</select>
</div>
<div class="form-group">
<select name="city" id="city">
<option value="">City</option>
</select>
</div>
<div class="form-group">
<button type="submit" form="addform" value="Submit">Submit</button>
</div>
</form>
</div>
JSON files i'm using is here
You can store value of region code as data-attribute . So, whenever your region dropdown gets changed get value of this data attribute using $(this).find('option:selected').data("code"); and then pass same to your filter method .
Demo Code :
//this is for demo
var regions = [{
"code": "130000000",
"name": "National Capital Region",
"altName": "NCR"
},
{
"code": "140000000",
"name": "Cordillera Administrative Region",
"altName": "CAR"
}
]
var provinces = [{
"code": "130100000",
"name": "Ab",
"altName": null,
"region": "130000000"
},
{
"code": "140100000",
"name": "Cd",
"altName": null,
"region": "140000000"
},
{
"code": "142700000",
"name": "Mn",
"altName": null,
"region": "140000000"
}
]
$(function() {
var regOpt = "";
//FOR REGION
/*$.getJSON('regions.json', function(result) {*/
regOpt += `<option value="" disabled selected hidden>Region</option>`;
$.each(regions.sort(), function(i, region) {
//use data attr here..
regOpt += `<option data-code ='${region.code}' value='${region.name}'> ${region.altName}</option>`;
});
$('#region').html(regOpt);
/* });*/
//FOR PROVINCE
$('#region').change(function() {
var provOption = "";
//get data attribute values..
let values = $(this).find('option:selected').data("code");
console.log(values)
/*$.getJSON('provinces.json', function(result) {*/
let items = $(provinces).filter(function(i, n) {
return n.region === $.trim(values);
});
provOption += `<option value="" disabled selected hidden>Province</option>`;
//loop through dates
$.each(items, function(region, province) {
provOption += `<option value='${province.code}'> ${province.name}</option>`;
});
$('#province').html(provOption);
/*});*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container form-group">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region">
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province">
<option value=""> Select Province</option>
</select>
</div>
<div class="form-group">
<select name="city" id="city">
<option value="">City</option>
</select>
</div>
<div class="form-group">
<button type="submit" form="addform" value="Submit">Submit</button>
</div>
</form>
</div>
I have a multi-element and dependent div that asks the user to first pick a state. Once the state is picked, then it will provide users with the appropriate city in the state.
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
jQuery:
$(document).ready(function() {
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a city</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).eq(current).val() == 'California') {
$(".city").eq(current).html("<option>San Francisco</option><option>Los Angeles</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(".city").eq(current).html("<option>New York City</option><option>Albany</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
if (maxAppend >= 4) return;
var additional = $(".trip").html();
$(".trip").after(additional);
maxAppend++;
});
});
I want to allow the users to add the class "trip" up to four times. When I use append() or after() as show above. The index of the newly added item rests to 1, which cause the selected in the first trip to reset because it has the same index. What is the proper and elegant way of implementing this?
here is the link to the jsfiddle: https://jsfiddle.net/L2bfmo69/
Here you go with the solution https://jsfiddle.net/L2bfmo69/5/
$(document).ready(function() {
var additional = $(".trip").html();
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a fare</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).val() == 'California') {
$(this).next().html("<option>San Francisco</option><option>Los Angeles</option>");
$(this).next().attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(this).next().html("<option>New York City</option><option>Albany</option>");
$(this).next().attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
$(".summary").append('<div class="trip">' + additional + "</div>");
if ($('.summary').children().length >= 4) {
$('#add').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
<div id="nexttrip"></div>
<button type="button" id="add">Add another trip</button>
<br><br>
<input type="submit">
</form>
After 4 insert by the user I have disabled the add button.