Using jQuery code, Want Input field on selecting other from the option? - html

$('#add_ent_button').click(function() {
entrance_counter = entrance_counter + 1;
$('#entrance_counter').val(entrance_counter);
var html = '';
html += '<hr class="hr-primary" />';
html += '<div class="form-row">';
html += '<div class="form-group col-md-2">';
html += '<label>Entrance Exam Name</label>';
html += '<select class="form-control" name="entrance_exam'+entrance_counter+'" onchange=showHideElement("txt-entrance_exam'+entrance_counter+'") id="entrance_exam'+entrance_counter+'">';
html += '<option value="">Select Entrance Exam</option>';
html += '<option>JEE</option>';
html += '<option>JEE Adv.</option>';
html += '<option>NEET</option>';
html += '<option>NATA</option>';
html += '<option value="other">other</option>';
html += '</select>';
html += '<input type="text" style="display:none;" name="txt-entrance_exam'+entrance_counter+'" id="txt-entrance_exam'+entrance_counter+'" class="form-control">';
html += '</div>';
This is the jQuery Code but in this line
html += '<select class="form-control" name="entrance_exam'+entrance_counter+'" onchange=showHideElement("txt-entrance_exam'+entrance_counter+'") id="entrance_exam'+entrance_counter+'">';
I am a bit confused I want to show the input field when the "other" option is selected from the dropdown. so when I choose "other" then it should call the function in onchange, but when I select other then it is not showing input fields I think the error is because of the quotes in the above jQuery line.

You Can Try This
This is Implemented in Raw JavaScript Convert To Jquery If Needed
var inp = document.getElementById('inp');
var other = document.getElementById('other');
other.onclick = function() {
inp.style.display = "block";
inp.focus();
document.getElementById('select').style.display = 'none';
}
inp.onblur = function() {
// if input has no value then it will be hidden and option will be active again
if (inp.value == '') {
document.getElementById('select').style.display = 'block';
inp.style.display = 'none';
}
}
<!doctype html>
<html>
<head>
<title>Other Click to inputr</title>
</head>
<body>
<div id="select-input">
<select name="" id="select">
<option value="A">A</option>
<option value="B">B</option>
<option value="other" id="other">Other</option>
<option value="C">C</option>
</select>
<input type="text" style="display:none;" value="" id="inp">
</div>
</body>
</html>

Related

HTML form radio conditional

¡Hello! I need to make this range start working when the check is pressed ¿Can I get some help? Thanks
`
<!DOCTYPE html>
<html>
<body>
<input type="checkbox" id="si" name="nivel" onclick="myFunction()"><label for="si">Si</label>
<input type="range"id="tickmarks" disabled="disabled" />
<datalist id="tickmarks">
<option value="bajo" label="Bajo"></option>
<option value="medio" label="Medio"></option>
<option value="alto" label="Alto"></option>
</datalist>
<script>
function myFunction() {
var nivel = document.getElementById("si");
var tickmarks = document.getElementById("tickmarks");
if (nivel.checked == true){
tickmarks.style.display = "block";
} else {
tickmarks.style.display = "none";
}
}
</script>
</body>
</html>
`
I tried to press the checkbox to make the range appear and it could be selected but when it appears it is disabled.
You can control whether an element is disabled by setting the element's disabled attribute to true/false.
<input type="checkbox" id="si" name="nivel" onclick="myFunction()">
<input type="range" id="tickmarks" disabled>
function myFunction() {
const nivel = document.getElementById("si");
const tickmarks = document.getElementById("tickmarks");
if (nivel.checked == true) {
tickmarks.disabled = false;
} else {
tickmarks.disabled = true;
}
}

Matching two ID attributes from cloned dependent dropdown list

In this code I have 2 dependent dropdown lists and a button to duplicate/clone the form. The color selection changes based on what is selected in item. When I duplicate the dropdown list the function didn't work. I tried changing the id of the duplicated dropdown list but still can't manage to match the id of 2 dropdown list. Is there any solution? Thanks.
var count = 1;
var duplicate_div = document.getElementById('duplicate_1');
function addRecord() {
var clone = duplicate_div.cloneNode(true);
clone.id = "duplicate_" + ++count;
duplicate_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0];
$(clone).find("*[id]").each(function() {
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength - 1], count);
$(this).attr('id', newId);
});
}
$(document).ready(function() {
$("#item_" + count).change(function() {
var val = $(this).val();
if (val == "shirt") {
$("#color_" + count).html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$("#color_" + count).html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$("#color_" + count).html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate" id="duplicate_1">
<br>
<label>item</label>
<select id="item_1">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select id="color_1">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button" onclick="addRecord()">add</button>
Since you've imported jQuery into the project, I suggest you fully use it.
It's recommended to use jQuery's .on method instead of onclick attribute.
The change event will not work on the dynamically created elements.
You should instead use "event delegation".
Last but not least, you can remove the ids if they serve as selectors. You can use jQuery to easily transverse the DOM
Try this
$(document).ready(function() {
var $cloned = $('.duplicate').first().clone(true);
var $container = $('.select-form');
$('#add-button').click(function() {
$container.append($cloned.clone());
})
$('.select-form').on('change', '.item', function() {
var val = $(this).val();
var $color = $(this).closest('.duplicate').find('.color');
if (val == "shirt") {
$color.html("<option>Black</option> <option>Gray</option>");
} else if (val == "pants") {
$color.html("<option>Blue</option> <option>Brown</option>");
} else if (val == "shoe") {
$color.html("<option>White</option> <option>Red</option>");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="select-form">
<div class="duplicate">
<br>
<label>item</label>
<select class="item">
<option value="template" disabled selected></option>
<option value="shirt">Shirt</option>
<option value="pants">Pants</option>
<option value="shoe">Shoe</option>
</select>
<label>color</label>
<select class="color">
<option disabled selected>Select item first</option>
</select>
</div>
</form>
<br><br>
<button type="button" id="add-button">add</button>

why select loop in HTML is not working or visible when fetched from AJAX

I have a JSON data retrieved from Spring boot controller as:
[
{
"surgeonId": 13505,
"surgeonNationalID": 308236823,
"surgeonFirstName": "Ali",
"surgeonLastName": "Zah",
"surgeonNationality": "UK",
"surgeonDateOfBirth": "1969-03-10T21:00:00.000+00:00",
"surgeonGender": "Male",
"surgeonAddress": "322 Diplomatic Dist.",
"surgeonConact": "02277469",
"surgeonEmailAddress": "ali#hotmail.com",
"surgeonSpeciality": "GS",
"departmentIdInSurgery": 31
},
{
"surgeonId": 13000,
"surgeonNationalID": 492487233,
"surgeonFirstName": "Sami",
"surgeonLastName": "Abdulkareem",
"surgeonNationality": "Canada",
"surgeonDateOfBirth": "1960-12-11T21:00:00.000+00:00",
"surgeonGender": "Male",
"surgeonAddress": "74 Aiano Dis.",
"surgeonConact": "02323322",
"surgeonEmailAddress": "sami#yahoo.com",
"surgeonSpeciality": "GS",
"departmentIdInSurgery": 31
}
]
And HTML as:
<td>
<div id="SurgeonId">
<select >
<option value="" disabled>Select Department First</option>
</select>
</div>
</td>
And this is the JavaScript code in the HTML page:
<script type ="text/javascript">
function showSurgeons(str) {
var xmlhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var ourData = JSON.parse(xmlhttp.responseText);
var innerHTMLTest = '<select th:field="${waitinglist.waitingListSurgeonId}"> ';
for(i=0; i<ourData.length; i++){
innerHTMLTest +=' <option th:value="'+ ourData[i].surgeonId + '" th:text="' + ourData[i].surgeonLastName + '"> </option>';
console.log('inside loop' + innerHTMLTest);
}
innerHTMLTest += ' </select>';
console.log(innerHTMLTest);
alert(document.getElementById("SurgeonId").innerHTML);
document.getElementById("SurgeonId").innerHTML = innerHTMLTest;
}
}
xmlhttp.open("GET", "/surgeon/" + str, false);
xmlhttp.send();
}
</script>
However, I do not get the expected outcome as you can see in the images below:
The database missing the surgeonId data!
Also, as you can see below, I tried to inspect the code which seems right!
Thank you for the time spent guys :)
JavaScript isn't parsed through the Thymeleaf interpreter. When you have this code in JavaScript:
'<option th:value="'+ ourData[i].surgeonId + '" th:text="' + ourData[i].surgeonLastName + '"> </option>'
The browser sees
<option th:value="13505" th:text="Zah"></option>
th:value isn't a valid HTML attribute, nor is th:text. Those attributes are only only understood by the Thymeleaf interpreter. If you want your JavaScript to work, you have to use regular HTML attributes.
'<option value="'+ ourData[i].surgeonId + '">' + ourData[i].surgeonLastName + '</option>'
Which will output:
<option value="13505">Zah</option>
You will have to fix th:field="${waitinglist.waitingListSurgeonId}" as well.
Thanx to Maksim Zagorodsky in his post here
I managed to solve it :)
The HTML code:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Add Procedure Form</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function sendAjaxRequest() {
var department = $("#department").val();
$.get(
"http://localhost:8080/surgerywaitinglist/getSurgeonsByDep?department="
+ department, function(data) {
$("#surgeonId").empty();
data.forEach(function(item, i) {
var option = "<option value = " + item + ">" + item
+ "</option>";
$("#surgeonId").append(option);
});
});
};
</script>
<script>
$(document).ready(function() {
$("#department").change(function() {
sendAjaxRequest();
});
});
</script>
</head>
<body>
<div class="container">
<br />
<h3>Add New Procedure</h3>
<br />
<hr />
<br />
<form th:action="#{/surgerywaitinglist/saveToWaitinList}" th:object="${waitinglist}"
method="POST">
<table class="table table-primary table-bordered table-striped"
id="employeeTable" style="width: 50%" align="center">
<tbody>
<tr>
<td>Department</td>
<td>
<div class="form-group">
<select name="departmentName"
th:with="departmentName = ${department.departmentName}"
class="form-control" id="department">
<option value="" th:selected="selected" th:disabled="disabled">select
option</option>
<option th:each="department: ${departments}"
th:value="${department.departmentName}"
th:text="${department.departmentName}"></option>
</select>
</div>
</td>
</tr>
<tr>
<td>Surgeon</td>
<td>
<div class="form-group">
<select th:field="${surgeon.surgeonLastName}"
class="form-control" id="surgeonId">
</select>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Now I do get the expected outcome as you can see in the images below:

Outputting Text After Dynamic Drop Down Selection HTML

I have the code for a dynamic dropdown (taken from this website), see below. However, I don't know how to make it generate text after you make the selections. I would like it after I choose my two options for it to have a filler sentence underneath that I can change later ("This is dummy text"). I need the text for each combination to be different text.
Also, if you know how to make my the two selections side-by-side instead of one on top of the other, that would be great, but not needed!
I am trying to create a website and have very minimal experience with HTML, and have been using a lot of code found online. I am knowledgable enough to edit code properly, just not create it. Any help would be amazing! Thank you.
<html>
<head>
<!- This is a comment->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" type="text/javascript">
function dynamicdropdown(listindex)
{
switch (listindex)
{
case "manual" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
break;
case "online" :
document.getElementById("status").options[0]=new Option("Select status","");
document.getElementById("status").options[1]=new Option("OPEN","open");
document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
break;
}
return true;
}
</script>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="category_div" id="category_div">Chapter:
<select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
<option value="">Select source</option>
<option value="manual">MANUAL</option>
<option value="online">ONLINE</option>
</select>
</div>
<div class="sub_category_div" id="sub_category_div">Lesson:
<script type="text/javascript" language="JavaScript">
document.write('<select name="status" id="status"><option value="">Select status</option></select>')
</script>
<noscript>
<select id="status" name="status">
<option value="open">OPEN</option>
<option value="delivered">DELIVERED</option>
</select>
</noscript>
</div>
</body>
Please checkout this code.
I haven't written the entire code, it would be too long.
Here if you would like to set custom text for each selection please edit the display() function (see the commented line in the javascript).
function dynamicList() {
var chapter = document.getElementById("chapter");
var lesson = document.getElementById("lesson");
switch (chapter.value) {
case "online":
lesson.length = 0;
var option = document.createElement("option");
option.value = "";
option.text = "Select status";
lesson.add(option);
var option = document.createElement("option");
option.value = "open";
option.text = "Open";
lesson.add(option);
option = document.createElement("option");
option.value = "delevered";
option.text = "Delevered";
lesson.add(option);
break;
case "manual":
lesson.length = 0;
var option = document.createElement("option");
option.value = "";
option.text = "Select status";
lesson.add(option);
var option = document.createElement("option");
option.value = "open";
option.text = "Open";
lesson.add(option);
option = document.createElement("option");
option.value = "delevered";
option.text = "Delevered";
lesson.add(option);
option = document.createElement("option");
option.value = "shipped";
option.text = "Shipped";
lesson.add(option);
break;
default:
display();
}
}
function display() {
var chapter = document.getElementById("chapter");
var lesson = document.getElementById("lesson");
var result = document.getElementById("result");
if (chapter.value != "" && lesson.value != "") {
result.innerHTML = "<span class='text'>You have selected " + chapter.value + " and " + lesson.value + "</span>";
} else {
result.innerHTML = "<span class='text'>Please select the both options</span>";
}
//for using custom combination of values use if statement and use the values as condition like this
// if(chapter.value=="online" && lesson.value=="open")
// {
// write the code here (when chapter value=online and lesson value=open)
// }
}
#result
{
margin-top: 15px;
float: left;
color:#0078d7;
}
.categories
{
float: left;
}
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<title>Dynamic Drop Down List</title>
<body>
<div class="categories">
Chapter:
<select id="chapter" onchange="dynamicList()" style="margin-right:25px">
<option value="">Select source</option>
<option value="online">Online</option>
<option value="manual">Manual</option>
</select>
lesson:
<select id="lesson" onchange="display()">
<option value="">Select status</option>
</select>
<br>
<div id="result"></div>
</div>
</body>

show selected option value info to other select tag [duplicate]

i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<select class="select" id="city" disabled>
<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>
this one is not visible, and acts as a container for all the elements filtered out by the selection:
<span id="option-container" style="visibility: hidden; position:absolute;"></span>
Finally, the script that filters:
<script>
function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip
It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle.
//Get html elements
var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
Fiddle Demo
I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
</script>
</head>
<body>1
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Japn</option>
<option>Shuidong</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
</body>
</html>
This is an example that I've done. I wish that will be useful for you.
$(document).ready(function(){
var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);
function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {
if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}
$("#cycles").change(function(){
remplirListNiveau(this.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>