$('#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>
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>
I'm creating a program that rolls a certain amount of dice that the user picks randomly. A window pops up before you start, asking how many dice you want to roll but now I want to change that to a list drop box. I've tried just putting the listbox id as my value but that doesn't work. How do I exactly change the window prompt input to be in my list input?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
text-align: center;
}
img {
height: 150px;
}
.document{
text-size-adjust: 50px;
}
</style>
</head>
<body>
<p>
<label># of dice: </label>
<select id = "myList">
<option value = "0"> </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>
</select>
<button type="button" onclick="roll()">Click Me!</button>
<h1>Click the button to see the roll of a die randomly selected</h1>
<div id="dices"></div>
</p>
<hr>
<p id="display">--</p>
<script>
Val = window.prompt("Enter the number of dice to play with (1-5)");
//if user enters a number <= 1 val ==
if (Val < 1) {
Val = 1;
}
//if user enters anything thats not 1-4 val = 5
if (Val > 4) {
Val = 5
}
//Loop to show questionDie
for (i = 1; i <= Val; i++) {
let img = document.createElement('img');
img.src = "dieImages/question-mark-dice.jpg";
img.id = "dieImg" + i;
let dices = document.getElementById("dices");
dices.appendChild(img);
}
function roll() {
var randomDie = Math.floor(Val*Math.random()) + 1;
var RandomNum = Math.floor(6*Math.random()) + 1;
var diceElement = document.getElementById('dieImg' + randomDie);
document.getElementById('dieImg' + randomDie).setAttribute("src","dieImages/die" + RandomNum + ".jpg");
document.getElementById('dieImg' + randomDie).style.display="inline";
document.getElementById('display').innerHTML = "Die " + randomDie + " was selected and rolled to show " + RandomNum;
}
</script>
</body>
</html>
I've moved most of your code to methods. I've also changed your button click to call one of the methods I created, instead of the roll method. I also changed the case of your variable, but not in the Roll or SetUpDice methods, since I didn't want to risk missing one and spending too much time debugging that.
So here's why your code didn't work: you didn't have it add or remove the dice as per the dropdown, just had it re-roll the existing dice.
You now need to remove the existing dice, since it just keeps adding more and more every time you click the button. Oh, wait, I did that too. I moved the dices variable out of the loop, since it wasn't necessary to do it in the loop anyway, and then simply cleared out the HTML that was in it.
FYI, I changed the casing of your variable, since methods are supposed to start with uppercase and variables with lowercase. Well, that's a common convention, anyway.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
text-align: center;
}
img {
height: 150px;
}
.document{
text-size-adjust: 50px;
}
</style>
</head>
<body>
<p>
<label># of dice: </label>
<select id = "myList">
<option value = "0"> </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>
</select>
<button type="button" onclick="GetQty()">Click Me!</button>
<h1>Click the button to see the roll of a die randomly selected</h1>
<div id="dices"></div>
</p>
<hr>
<p id="display">--</p>
<script>
var val = window.prompt("Enter the number of dice to play with (1-5)");
SetUpDice(val);
function GetQty() {
var val = document.getElementById("myList").value;
SetUpDice(val);
}
function SetUpDice(Val) {
//if user enters a number <= 1 val ==
if (Val < 1) {
Val = 1;
}
//if user enters anything thats not 1-4 val = 5
if (Val > 4) {
Val = 5
}
let dices = document.getElementById("dices");
dices.innerHTML = "";
//Loop to show questionDie
for (i = 1; i <= Val; i++) {
let img = document.createElement('img');
img.src = "dieImages/question-mark-dice.jpg";
img.id = "dieImg" + i;
dices.appendChild(img);
}
Roll(Val);
}
function Roll(Val) {
var randomDie = Math.floor(Val*Math.random()) + 1;
var RandomNum = Math.floor(6*Math.random()) + 1;
var diceElement = document.getElementById('dieImg' + randomDie);
document.getElementById('dieImg' + randomDie).setAttribute("src","dieImages/die" + RandomNum + ".jpg");
document.getElementById('dieImg' + randomDie).style.display="inline";
document.getElementById('display').innerHTML = "Die " + randomDie + " was selected and rolled to show " + RandomNum;
}
</script>
</body>
</html>
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>
I have two droplist in html built using tag.
<select name="List1" id="List1" onclick="GetVal()">
<option value="1" selected="selected">Mercurio</option>
<option value="2">Venus</option>
<option value="3">Tierra</option>
<option value="4">Marte</option>
</select>
<select name="List2" id="List2">
<option value="1" selected="selected">Hg</option>
<option value="2">Ve</option>
<option value="3">Ti</option>
<option value="4">Ma</option>
</select>
I have written a script such as the selection of an element from List2 relies on the selection of the corresponding element of List1.
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetVal() {
var LSelect1 = document.getElementById('List1');
var LSelect2 = document.getElementById('List2');
switch (LSelect1.selectedIndex)
{
case 1:
LSelect2.selectedIndex = 1;
break;
case 2:
LSelect2.selectedIndex = 2;
break;
case 3:
LSelect2.selectedIndex = 3;
break;
default:
LSelect2.selectedIndex = 4;
}
}
// ]]>
</script>
However, the function works wrongly for the first element of the List1. Why?
selectedIndex is 0-based. A simpler way to do things might be like this:
<script language="javascript" type="text/javascript">
// <!CDATA[
function GetVal() {
var LSelect1 = document.getElementById('List1');
var LSelect2 = document.getElementById('List2');
LSelect2.selectedIndex = LSelect1.selectedIndex;
}
// ]]>
</script>