This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 months ago.
Here Is My HTML Code
<div class="form-group col-md-12">
<label for="inputPassword4">Category</label>
<select name="cat" id="cat" class="form-control">
<option value=" ">Choose Category</option>
#foreach ($cat as $data)
<option value="{{ $data->id }}">{{ $data->cname }}</option>
#endforeach
</select>
</div>
<div id="serv"></div>
<div id="repair"></div>
And Here is my javascript code and in this code first one was working fine that is #serv block but
the second one that is #repair section its not working onChange so please help e with this.
<script>
$('#cat').change(function() {
if (this.value == 6 || this.value == 7) {
$('#serv').append(`<div class="form-group col-md-12">
<label for="inputEmail4">Service</label>
<select class="form-control" id="servic" name="serv" required>
<option value=" ">Choose Services</option>
<option value="service">Service</option>
<option value="repair">Repair</option>
<option value="installation">Installation</option>
<option value="uninstallation">Uninstallation</option>
</select>
</div>`);
}
else
$('#serv').empty();
});
This below Block is not working please help me with it.
$('#servic').change(function() {
console.log('in');
if (this.value == 'repair') {
$('#repair').append(`<div class="form-group col-md-12">
<label for="inputEmail4">Repair</label>
<select class="form-control" id="repar" name="rep" required>
<option value="power_issue">Power Issue</option>
<option value="less_cooling">Less Cooling</option>
<option value="water_leakage">Water Leakage</option>
</select>
</div>`);
}
else
$('#repair').empty();
});
</script>
at the first, when the page is loaded, you don't have an element with id "service" in the DOM. so your event will not be bound.
you should put your second event into the first if condition. like this:
$('#cat').change(function() {
if (this.value == 6 || this.value == 7) {
$('#serv').append(`<div class="form-group col-md-12">
<label for="inputEmail4">Service</label>
<select class="form-control" id="servic" name="serv" required>
<option value=" ">Choose Services</option>
<option value="service">Service</option>
<option value="repair">Repair</option>
<option value="installation">Installation</option>
<option value="uninstallation">Uninstallation</option>
</select>
</div>`);
$('#servic').change(function() {
console.log('in');
if (this.value == 'repair') {
$('#repair').append(`<div class="form-group col-md-12">
<label for="inputEmail4">Repair</label>
<select class="form-control" id="repar" name="rep" required>
<option value="power_issue">Power Issue</option>
<option value="less_cooling">Less Cooling</option>
<option value="water_leakage">Water Leakage</option>
</select>
</div>`);
}
else
$('#repair').empty();
});
}
else
$('#serv').empty();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-md-12">
<label for="inputPassword4">Category</label>
<select name="cat" id="cat" class="form-control">
<option value="">Choose Category</option>
<option value="6">value is 6</option>
</select>
</div>
<div id="serv"></div>
<div id="repair"></div>
You're creating the select with id "servic" dynamically, so you have to attach the change handler only after it's appended to #serv.
if (this.value == 6 || this.value == 7) {
$('#serv').append(`...`);
$('#servic').change(function() {
// listener code...
});
}
$('#cat').change(function() {
if (this.value == 6 || this.value == 7) {
$('#serv').append(`<div class="form-group col-md-12">
<label for="inputEmail4">Service</label>
<select class="form-control" id="servic" name="serv" required>
<option value=" ">Choose Services</option>
<option value="service">Service</option>
<option value="repair">Repair</option>
<option value="installation">Installation</option>
<option value="uninstallation">Uninstallation</option>
</select>
</div>`);
$('#servic').change(function() {
console.log('in');
if (this.value == 'repair') {
$('#repair').append(`<div class="form-group col-md-12">
<label for="inputEmail4">Repair</label>
<select class="form-control" id="repar" name="rep" required>
<option value="power_issue">Power Issue</option>
<option value="less_cooling">Less Cooling</option>
<option value="water_leakage">Water Leakage</option>
</select>
</div>`);
}
else
$('#repair').empty();
});
}
else
$('#serv').empty();
});
Related
I'm making a form for setting data. so when I select by department and I select the IT department. the data ends there, but here when I select the IT department, what appears instead selects the option by employee. Which part is wrong?
this is the code for addsetting.blade.php:
and this is how the form Mode Alokasi
dropdown form for "by departement":
display when selected By department
value for departemen name:
value for department name
when one of the department names is clicked, what appears instead is Employee Tags
department names is clicked,Employee Tags appears
even though the employee tags dropdown should only be for allocation mode "By Tags karyawan"
and this is the dropdown menu for the correct employee tags
$(function() {
$('#mode_company').prop("hidden", true);
$('#mode_departemen').prop("hidden", true);
$('#mode_employee').prop("hidden", true);
$('#jk_employee').prop("hidden", true);
$('#sm_employee').prop("hidden", true);
$('#modealokasi').on('change', function(e) {
if (e.target.value == 'By Karyawan') {
$('#mode_company').prop("hidden", true);
$('#mode_departemen').prop("hidden", true);
$('#mode_employee').prop("hidden", false);
$('#mode_employee').on('change', function(a) {
if (a.target.value == 'Jenis Kelamin') {
$('#jk_employee').prop("hidden", false);
$('#sm_employee').prop("hidden", true);
} else {
$('#jk_employee').prop("hidden", true);
$('#sm_employee').prop("hidden", false);
};
});
} else if (e.target.value == 'By Company') {
$('#mode_company').prop("hidden", false);
$('#mode_departemen').prop("hidden", true);
$('#mode_employee').prop("hidden", true);
} else {
$('#mode_company').prop("hidden", true);
$('#mode_departemen').prop("hidden", false);
$('#mode_employee').prop("hidden", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6" id="modealokasi">
<div class="form-group">
<div class="form-group col-sm" id="modealokasi">
<label for="mode" class="col-form-label">Mode Alokasi</label>
<select name="mode" id="mode" class="form-control">
<option value="">-- Pilih Mode Alokasi --</option>
<option value="By Company">By Company</option>
<option value="By Departemen">By Departemen</option>
<option value="By Karyawan">By Tags Karyawan</option>
</select>
</div>
</div>
<div class="form-group col-sm" id="mode_company">
<label for="company" class="col-form-label">Company</label>
<select name="company" id="company" class="form-control">
<option value="">-- Pilih Company --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
<div class="form-group col-sm" id="mode_departemen">
<label for="id_departemen" class="col-form-label">Departemen</label>
<select name="id_departemen" id="id_departemen" class="form-control">
<option value="">-- Pilih Departemen --</option>
<option value="KONVENSIONAL">KONVENSIONAL</option>
<option value="IT DEPARTEMEN">IT DEPARTEMEN</option>
<option value="KEUANGAN">KEUANGAN</option>
</select>
</div>
<div class="form-group col-sm" id="mode_employee">
<label for="tags" class="col-form-label">Tags Karyawan</label>
<select name="tags" id="tags" class="form-control">
<option value="">-- Pilih Tags --</option>
<option value="Jenis Kelamin">Jenis Kelamin</option>
<option value="Status">Status</option>
</select>
</div>
<div class="form-group col-sm" id="jk_employee">
<label for="tags" class="col-form-label">Jenis Kelamin</label>
<select name="tags" id="tags" class="form-control">
<option value="">-- Pilih Jenis Kelamin --</option>
<option value="Laki-laki">Laki-laki</option>
<option value="Perempuan">Perempuan</option>
</select>
</div>
<div class="form-group col-sm" id="sm_employee">
<label for="tags" class="col-form-label">Stat. Menikah</label>
<select name="tags" id="tags" class="form-control">
<option value="">-- Pilih Status Menikah --</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</div>
</div>
This is not complete because I do not speak your language
But it shows you how to do this
$(function() {
$('#mode_company').prop("hidden", true);
$('#mode_departemen').prop("hidden", true);
$('#mode_employee').prop("hidden", true);
$('#jk_employee').prop("hidden", true);
$('#sm_employee').prop("hidden", true);
$('#mode').on('change', function(e) {
const val = this.value;
$('#mode_employee').prop("hidden", val !== 'By Karyawan');
$('#mode_company').prop("hidden", val !== 'By Company');
$('#mode_departemen').prop("hidden", val !== 'By Departemen');
});
$('#mode_employee').on('change', function(a) {
const val = this.value
$('#jk_employee').prop("hidden", val !== 'Jenis Kelamin');
$('#sm_employee').prop("hidden", val !== 'Status');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-6" id="modealokasi">
<div class="form-group">
<div class="form-group col-sm">
<label for="mode" class="col-form-label">Mode Alokasi</label>
<select name="mode" id="mode" class="form-control">
<option value="">-- Pilih Mode Alokasi --</option>
<option value="By Company">By Company</option>
<option value="By Departemen">By Departemen</option>
<option value="By Karyawan">By Tags Karyawan</option>
</select>
</div>
</div>
<div class="form-group col-sm" id="mode_company">
<label for="company" class="col-form-label">Company</label>
<select name="company" id="company" class="form-control">
<option value="">-- Pilih Company --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
<div class="form-group col-sm" id="mode_departemen">
<label for="id_departemen" class="col-form-label">Departemen</label>
<select name="id_departemen" id="id_departemen" class="form-control">
<option value="">-- Pilih Departemen --</option>
<option value="KONVENSIONAL">KONVENSIONAL</option>
<option value="IT DEPARTEMEN">IT DEPARTEMEN</option>
<option value="KEUANGAN">KEUANGAN</option>
</select>
</div>
<div class="form-group col-sm" id="mode_employee">
<label for="tags" class="col-form-label">Tags Karyawan</label>
<select name="tags" id="tags" class="form-control">
<option value="">-- Pilih Tags --</option>
<option value="Jenis Kelamin">Jenis Kelamin</option>
<option value="Status">Status</option>
</select>
</div>
<div class="form-group col-sm" id="jk_employee">
<label for="tags" class="col-form-label">Jenis Kelamin</label>
<select name="tags" id="tags" class="form-control">
<option value="">-- Pilih Jenis Kelamin --</option>
<option value="Laki-laki">Laki-laki</option>
<option value="Perempuan">Perempuan</option>
</select>
</div>
<div class="form-group col-sm" id="sm_employee">
<label for="tags" class="col-form-label">Stat. Menikah</label>
<select name="tags" id="tags" class="form-control">
<option value="">-- Pilih Status Menikah --</option>
<option value="Sudah">Sudah</option>
<option value="Belum">Belum</option>
</select>
</div>
</div>
I'm having a hard time with this, basically I have 2 Select with same options. The 2 Select Inputs named as registrationdiscounttype1 and registrationdiscounttype2
So First I choose a discount for registrationdiscounttype1 then if I will add a discount for registrationdiscounttype2 if the option is already selected in discount number 1 it will show an error that will say the discount is already selected.
I've already made a javascript based on what I've search so far, but I can't make it work, can you help me what is wrong with my code, or what should I use?
This is the sample photo
// Change in Discount 2
$("#registrationdiscounttype2").unbind('change').bind('change', function()
if ($('#registrationdiscounttype2').closest('table').find('option[value=' + $('#registrationdiscounttype1').val() + ']:selected').length > 1)
{
alert('Discount is already selected, Please choose another one');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="form-group">
<label for="registrationdiscounttype1" class="col-sm-4 control-label">Discount 1: </label>
<div class="col-sm-8">
<select class="form-control" name="registrationdiscounttype1" id="registrationdiscounttype1">
<option value="">Select Discount </option>
<?php foreach ($discounttypeData as $discounttype)
{
?>
<option value="<?php echo $discounttype['discounttype_id']; ?>"> <?php echo $discounttype['discounttype_name']; ?> </option>
<?php
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="registrationdiscounttype2" class="col-sm-4 control-label">Discount 2: </label>
<div class="col-sm-8">
<select class="form-control" name="registrationdiscounttype2" id="registrationdiscounttype2">
<option value="">Select Discount </option>
<?php foreach ($discounttypeData as $discounttype)
{
?>
<option value="<?php echo $discounttype['discounttype_id']; ?>"> <?php echo $discounttype['discounttype_name']; ?> </option>
<?php
}
?>
</select>
</div>
</div>
u can try
$(document).ready(function(){
$("#registrationdiscounttype2").unbind('change').bind('change', function() {
if ($('#registrationdiscounttype2').val() == $('#registrationdiscounttype1').val())
{
alert('Discount is already selected, Please choose another one');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="registrationdiscounttype1" class="col-sm-4 control-label">Discount 1: </label>
<div class="col-sm-8">
<select class="form-control" name="registrationdiscounttype1" id="registrationdiscounttype1">
<option value="">Select Discount </option>
<option value="1">1 </option>
<option value="2">2 </option>
</select>
</div>
</div>
<div class="form-group">
<label for="registrationdiscounttype2" class="col-sm-4 control-label">Discount 2: </label>
<div class="col-sm-8">
<select class="form-control" name="registrationdiscounttype2" id="registrationdiscounttype2">
<option value="">Select Discount </option>
<option value="1">1 </option>
<option value="2">2 </option>
</select>
</div>
<div class="form-group" id="result">
</div>
Here you go with an example solution (if select element are siblings) https://jsfiddle.net/pvchxyup/1/
$('select').change(function(){
if($(this).val() === $(this).siblings('select').val() ){
console.log("Same value!!!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test5">Test 5</option>
</select>
<select>
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test7">Test 7</option>
</select>
If your element are not siblings, then follow https://jsfiddle.net/pvchxyup/2/
$('select').change(function(){
if($('#select1').val() === $('#select2').val() ){
console.log("Same value!!!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select id="select1">
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test5">Test 5</option>
</select>
</div>
<div>
<select id="select2">
<option value="test1">Test 1</option>
<option value="test2">Test 2</option>
<option value="test7">Test 7</option>
</select>
</div>
No need to use bind, simple and easy way to do that.
Try this:
$("#registrationdiscounttype2").change(function(){
if($(this).val()==$('#registrationdiscounttype1').val()){
alert("Already Selected");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label for="registrationdiscounttype1" class="col-sm-4 control-label">Discount 1: </label>
<div class="col-sm-8">
<select class="form-control" name="registrationdiscounttype1" id="registrationdiscounttype1">
<option value="">Select Discount </option>
<option value="sel1">sel1</option>
<option value="sel2">sel2</option>
</select>
</div>
</div>
<div class="form-group">
<label for="registrationdiscounttype2" class="col-sm-4 control-label">Discount 2: </label>
<div class="col-sm-8">
<select class="form-control" name="registrationdiscounttype2" id="registrationdiscounttype2">
<option value="">Select Discount </option>
<option value="sel1">sel1</option>
<option value="sel2">sel2</option>
</select>
</div>
Not sure what I'm doing wrong here, I put my code in a jsfiddle so it might be easier to read and debug. No matter what option I select from the list, it thinks it's the 'Single room' value that I've chosen. It is supposed to display odd numbers up to 5 if the room is a single room and , even number if double room selected (and < 7) and for the family room the numbers shown should only be 7.
Here's the fiddle, https://jsfiddle.net/35rchfup/
Thanks to anyone who can help in advance.
<div class="form-group">
<label class="col-md-4 control-label" for="chooseRoomType">Choose room
type:</label>
<div class="col-md-4">
<label class="select" for="chooseRoomType">
<div class="select">
<select class="form-control" runat="server" id="chooseRoomType" onchange="showValidRooms">
<option value="0">Choose room</option>
<option value="1">Single room</option>
<option value="2">Double room</option>
<option value="3">Family room</option>
</select>
</div>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="chooseRoomNo">Choose room number:
</label>
<div class="col-md-4">
<label class="select" for="chooseRoomNo">
<div class="select">
<select class="form-control" runat="server" id="chooseRoomNo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
</label>
</div>
<script>
document.getElementById("chooseRoomType").onchange = function() {
showRooms()
};
function showRooms() { //chooses single room every time
var select = document.getElementById("chooseRoomNo");
var selectedValue = select.options[select.selectedIndex].value;
if (selectedValue == 1) {
$('#chooseRoomNo')
.empty()
.append('<option value="1">1</option>', '<option value="3">3</option>',
'<option value="5">5</option>');
} else if (selectedValue == 2) {
$('#chooseRoomNo')
.empty()
.append('<option value="2">2</option>', '<option value="4">4</option>',
'<option value="6">6</option>');
} else if (selectedValue == 3) {
//show family room (number 7)
$('#chooseRoomNo')
.empty()
.append('<option value="7">7</option>');
} else if (selectedValue == 0) {
alert("You must choose a room type.");
}
console.log(selectedValue);//always 1
}
</script>
Changed your example: https://jsfiddle.net/35rchfup/2/
You had two issues:
1) You were referring to the wrong dropdown (var select = document.getElementById("chooseRoomNo");)
2) You were not calling the function onchange (<select class="form-control" runat="server" id="chooseRoomType" onchange="showValidRooms">) that is anyway useless because you bind your event through JavaScript
Here your example:
document.getElementById("chooseRoomType").onchange = function() {
showRooms()
};
function showRooms() { //chooses single room every time
var selectedValue = $("#chooseRoomType").val();
if (selectedValue == 1) {
$('#chooseRoomNo')
.empty()
.append('<option value="1">1</option>', '<option value="3">3</option>', '<option value="5">5</option>');
} else if (selectedValue == 2) {
$('#chooseRoomNo')
.empty()
.append('<option value="2">2</option>', '<option value="4">4</option>', '<option value="6">6</option>');
} else if (selectedValue == 3) {
//show family room (number 7)
$('#chooseRoomNo')
.empty()
.append('<option value="7">7</option>');
} else if (selectedValue == 0) {
alert("You must choose a room type.");
}
console.log(selectedValue);//always 1
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="form-group">
<label class="col-md-4 control-label" for="chooseRoomType">Choose room type:</label>
<div class="col-md-4">
<label class="select" for="chooseRoomType">
<div class="select">
<select class="form-control" runat="server" id="chooseRoomType">
<option value="0">Choose room</option>
<option value="1">Single room</option>
<option value="2">Double room</option>
<option value="3">Family room</option>
</select>
</div>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="chooseRoomNo">Choose room number:</label>
<div class="col-md-4">
<label class="select" for="chooseRoomNo">
<div class="select">
<select class="form-control" runat="server" id="chooseRoomNo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
</label>
</div>
</div>
Use var select = document.getElementById("chooseRoomType"); in your function showRooms() instead of var select = document.getElementById("chooseRoomNo");. Because you are getting value of the second dropdown which is always 1 by default.
It seems you are choosing the wrong DropDown:
function showRooms() { //chooses single room every time
var select = document.getElementById("chooseRoomNo");// This should be "chooseRoomType"
var selectedValue = select.options[select.selectedIndex].value;
if (selectedValue == 1) {
Basically you were calling roomnumber selector instead of roomtype.
Beside all the other answers pointing to your typo, here's how I'd do it:
using some clearly defined room-logic, and show/hide
All you need:
var roomLogic = {
0 : [1,2,3,4,5,6,7],
1 : [1,3,5],
2 : [2,4,6],
3 : [7]
};
$("#chooseRoomType").on("change", function() {
var type = this.value;
$("#chooseRoomNo").find("option").hide().filter(function() {
return $.inArray( +this.value, roomLogic[type] ) > -1;
}).show().eq(0).prop("selected", true);
});
Here's a full demo:
var roomLogic = {
0 : [1,2,3,4,5,6,7],
1 : [1,3,5],
2 : [2,4,6],
3 : [7]
}
$("#chooseRoomType").on("change", function() {
var type = this.value;
$("#chooseRoomNo").find("option").hide().filter(function() {
return $.inArray( +this.value, roomLogic[type] ) > -1;
}).show().eq(0).prop("selected", true);
// if (type==0) alert("You need to select a room");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-md-4 control-label" for="chooseRoomType">Choose room type:</label>
<div class="col-md-4">
<label class="select" for="chooseRoomType">
<div class="select">
<!-- onchange="showValidRooms" ??? -->
<select class="form-control" runat="server" id="chooseRoomType">
<option value="0">Choose room</option>
<option value="1">Single room</option>
<option value="2">Double room</option>
<option value="3">Family room</option>
</select>
</div>
</label>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="chooseRoomNo">Choose room number:</label>
<div class="col-md-4">
<label class="select" for="chooseRoomNo">
<div class="select">
<select class="form-control" runat="server" id="chooseRoomNo">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
</div>
</label>
</div>
</div>
One day, if your room logic changes, all you need to carelessly edit is the var roomLogic. Nothing else.
I have the following code to run my Dropdown box and field I want to disable when the value is not equal to value in dropdown.
My code is as follows.
document.getElementById('type').addEventListener('change', function() {
if (this.value == Hijacking) {
document.getElementById('hijacking').disabled = false;
} else {
document.getElementById('hijacking').disabled = true;
}
});
<div class="width-qrtr">
<label>Type of event</label>
<select name="Type" id="select">
<option value="">Select Type</option>
<option value="Fraud">Fraud</option>
<option value="Theft">Theft</option>
<option value="Accident">Accident</option>
<option value="Hijacking">Hijacking</option>
</select>
</div>
<div class="width-qrtr">
<label>Police Station</label>
<input id="textbox" disabled="true" type="text" name="Test" />
</div>
It keeps the field disabled. If i change the values to numerical it works but I need the Value for SQL to be inserted into my DB
document.getElementById works only if you put the corresponding id in defined by id="...". Also to compare string values you have to put them in quotes => this.value == 'Hijacking'.
The corrected code looks like this:
document.getElementById('select').addEventListener('change', function() {
if (this.value == 'Hijacking') {
document.getElementById('textbox').disabled = false;
} else {
document.getElementById('textbox').disabled = true;
}
});
<div class="width-qrtr">
<label>Type of event</label>
<select name="Type" id="select">
<option value="">Select Type</option>
<option value="Fraud">Fraud</option>
<option value="Theft">Theft</option>
<option value="Accident">Accident</option>
<option value="Hijacking">Hijacking</option>
</select>
</div>
<div class="width-qrtr">
<label>Police Station</label>
<input id="textbox" disabled="true" type="text" name="Test" />
</div>
Few bugs in your code , fixed as follows:
document.getElementById('select').addEventListener('change', function() {
if (this.value == "Hijacking") {
document.getElementById('textbox').disabled = false;
} else {
document.getElementById('textbox').disabled = true;
}
});
<div class="width-qrtr">
<label>Type of event</label>
<select name="Type" id="select">
<option value="">Select Type</option>
<option value="Fraud">Fraud</option>
<option value="Theft">Theft</option>
<option value="Accident">Accident</option>
<option value="Hijacking">Hijacking</option>
</select>
</div>
<div class="width-qrtr">
<label>Police Station</label>
<input id="textbox" disabled="true" type="text" name="Test" />
</div>
This code determines whether the form elements e.g. input fields, radio buttons and select fields have an attribute called required="required" then the jquery and add an error accordingly.
If the input field then has a value, then the change listener, should automatically remove the error.
The code works fine - However, its not been written well. There are lots of things being repeated.
What would be the best way of optimising the code?
$(document).ready(function() {
var count = 0;
$(".form-unique").attr('novalidate', "");
$('.form-unique').on('submit change', function(e) {
if (count > 0) {
$(this).find('.error-message').remove();
e.preventDefault();
console.log($('.supererror').length);
var dateField = $(".form-unique").find('#date-year').parent();
var _this = $(this);
var checkboxes = [];
_this.find(':input').each(function(i, val) {
$(this).css('border', 'transparent');
if ($(this).attr('required')) {
if ($(this).val() != '') {
$(this).removeClass('supererror');
if ($(this).attr('type') == "checkbox" || $(this).attr('type') == "radio") {
var checkboxName = $(this).attr('name');
if (checkboxes.indexOf(checkboxName) == -1) {
checkboxes.push(checkboxName);
var selector = "input:checked[type='radio'][name='" + $(this).attr('name') + "']";
if ($(selector).length == 0) {
$(this).parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
}
}
}
} else {
var superb = $(this).closest('div').find('label').text();
superb = superb.replace(/\*/g, '').replace(/\:/g, '');
$("input[type='checkbox'][name='submitted[yes_no]']").change(function() {
$(this).parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
});
$(this).addClass('supererror').css('border', '3px solid red');
$(this).parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
}
}
});
}
});
$('.form-unique').on('submit', function(e) {
count++;
if (count == 1) {
$(this).find('.myaccount-invalid-email-content').remove();
e.preventDefault();
console.log($('.supererror').length);
var _this = $(this);
var checkboxes = [];
_this.find(':input').each(function(i, val) {
$(this).css('border', 'transparent');
if ($(this).attr('required')) {
if ($(this).val() != '') {
$(this).removeClass('supererror');
if ($(this).attr('type') == "checkbox" || $(this).attr('type') == "radio") {
var checkboxName = $(this).attr('name');
if (checkboxes.indexOf(checkboxName) == -1) {
checkboxes.push(checkboxName);
var selector = "input:checked[type='radio'][name='" + $(this).attr('name') + "']";
if ($(selector).length == 0) {
$(this).parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
}
}
}
} else {
var superb = $(this).closest('div').find('label').text();
superb = superb.replace(/\*/g, '').replace(/\:/g, '');
$("input[type='checkbox'][name='submitted[yes_no]']").change(function() {
$(this).parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
});
$(this).addClass('supererror').css('border', '3px solid red');
$(this).parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
if ($(".moving-out-date-year").val() == "" || $(".moving-out-date-month").val() == "" || $(".moving-out-date-day").val() == "") {
$(".form-unique").find('.moving-out-date-year').parent().find(".myaccount-invalid-email-content").remove();
$(".form-unique").find('.moving-out-date-year').parent().prepend('<div class="error-message"><div class="messages error login-error-msg-div">ERROR - This is an error.</div></div>');
} else {
$(".form-unique").find('.moving-out-date-year').parent().find(".myaccount-invalid-email-content").remove();
}
}
}
});
}
if ($('.supererror').length == 0) {
$('.form-unique').off();
$('.form-unique').submit();
}
});
});
.supererror{
border: 3px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<form action="/" novalidate="" class="form-unique">
<div class="main-content">
<div class="new-markup">
<h3>Your contact details</h3>
</div>
<div class="name">
<label for="name">Full name: <span class="form-required">*</span></label>
<input id="name" required="required" type="text" name="submitted[name]" value="" class="form-text required"/>
</div>
<div class="new-e-mail-1">
<label for="e-mail-1">Email address: <span class="form-required">*</span></label>
<input id="e-mail-1" required="required" type="text" name="submitted[new_e_mail_1]" value="" class="form-text required"/>
</div>
<div class="phone-1">
<label for="phone-1">Phone number: <span class="form-required">*</span></label>
<input id="phone-1" required="required" type="text" name="submitted[phone_1]" value="" class="form-text required"/>
</div>
<div class="webform-component-markup moving-out">
<h3>Moving out</h3>
</div>
<div class="address-line-1">
<label for="address-line-1">House name/number: <span class="form-required">*</span></label>
<input id="address-line-1" required="required" type="text" name="submitted[address_line_1]" value="" class="form-text required"/>
</div>
<div class="address-line-2">
<label for="address-line-2">Street: <span class="form-required">*</span></label>
<input id="address-line-2" required="required" type="text" name="submitted[address_line_2]" value="" class="form-text required"/>
</div>
<div class="town-city">
<label for="town-city">District: </label>
<input id="town-city" type="text" name="submitted[town_city]" value="" class="form-text"/>
</div>
<div class="city">
<label for="city">City: </label>
<input id="city" type="text" name="submitted[city]" value="" class="form-text"/>
</div>
<div class="postcode2">
<label for="postcode2">Postcode: </label>
<input id="postcode2" type="text" name="submitted[postcode2]" value="" class="form-text"/>
</div>
<div class="webform-component-markup moving-date">
<h3>date</h3>
</div>
<div class="webform-component-date moving-out-date">
<label for="moving-out-date">Moving out date: <span class="form-required">*</span></label>
<div class="webform-container-inline webform-datepicker">
<label for="moving-out-date-year" class="element-invisible">Year </label>
<select id="moving-out-date-year" required="required" name="submitted[moving_out_date][year]" class="year form-select">
<option value="" selected="selected">Year</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
<label for="moving-out-date-month" class="element-invisible">Month </label>
<select id="moving-out-date-month" required="required" name="submitted[moving_out_date][month]" class="month form-select">
<option value="" selected="selected">Month</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<label for="moving-out-date-day" class="element-invisible">Day </label>
<select id="moving-out-date-day" required="required" name="submitted[moving_out_date][day]" class="day form-select">
<option value="" selected="selected">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<input id="dp1452155277044" type="image" src="/sites/all/modules/contrib/webform/images/calendar.png" alt="Open popup calendar" title="Open popup calendar" class="webform-calendar webform-calendar-start-2015-12-24 webform-calendar-end-2021-01-07 webform-calendar-day-0 hasDatepicker"/>
</div>
</div>
<div class="webform-component-markup new-address">
<h3>New address</h3>
</div>
<div class="addressnew-line-1">
<label for="addressnew-line-1">House name/number: </label>
<input id="addressnew-line-1" type="text" name="submitted[addressnew_line_1]" value="" class="form-text"/>
</div>
<div class="addressnew-line-2">
<label for="addressnew-line-2">Street: </label>
<input id="addressnew-line-2" type="text" name="submitted[addressnew_line_2]" value="" class="form-text"/>
</div>
<div class="town-city-new">
<label for="town-city-new">District: </label>
<input id="town-city-new" type="text" name="submitted[town_city_new]" value="" class="form-text"/>
</div>
<div class="county-new">
<label for="county-new">City: </label>
<input id="county-new" type="text" name="submitted[county_new]" value="" class="form-text"/>
</div>
<div class="postcode3">
<label for="postcode3">Postcode: </label>
<input id="postcode3" type="text" name="submitted[postcode3]" value="" class="form-text"/>
</div>
<div class="webform-component-markup take-us-with-you">
<h3>Take us with you</h3>
</div>
<div>
<label for="yes-no">yes?: </label>
<div id="yes-no" class="form-radios webform-radio-buttons">
<input id="yes-no-1" type="radio" name="submitted[yes_no]" value="1" class="webform-radio-buttons form-radio"/>
<label for="yes-no-1" class="option">No </label>
<input id="yes-no-2" type="radio" name="submitted[yes_no]" value="2" class="webform-radio-buttons form-radio"/>
<label for="yes-no-2" class="option">Yes </label>
</div>
</div>
<div class="form-actions">
<input type="submit" name="op" value="Submit" class="webform-submit button-primary form-submit"/>
</div>
</div>
</form>
$("form")[0].checkValidity() checks for form validity on modern browsers :P
Besides that it's indeed recommend to post this on codereview. There's nough to improve, too many ifs nested, full html variables in the code that can be replaced with a function which returns a html string that has a classname and text value input.