Javascript Multiple Dependant Dropdowns - javascript

I am new to javascript and I'm struggling with the following code that will be in a form for registration of multiple candidates.
It creates 2 dependant select boxes (country and area) for each candidate.
Clicking the button 'Add Candidate' once allows the dependant boxes to work fine but clicking the button again stops it working. Accessing the selected values from the form when there is more than one candidate is also impossible as they will overwrite each other.
I have tried creating the select names as arrays using a count variable which I increment each time the ff function is called but I can't get it to work.
All help will be much appreciated!
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<title>Select Populate Test</title>
<script>
var UnitedStates = new Array();
UnitedStates[0] = "Texas";
UnitedStates[1] = "California";
UnitedStates[2] = "Arizona";
UnitedStates[3] = "Nevada";
UnitedStates[4] = "Florida";
var UnitedKingdom = new Array();
UnitedKingdom[0] = "Surrey";
UnitedKingdom[1] = "Kent";
UnitedKingdom[2] = "Dorset";
UnitedKingdom[3] = "Hampshire";
function populateDropdown(arry)
{
document.myForm.stateSelect.options.length = 0;
for (var i = 0; i < arry.length; i++)
{
document.myForm.stateSelect.options[i] = new Option(arry[i], arry[i]);
}
}
function updateDropdown(str)
{
var stateArray
var selectedCountry;
var countryDropdown = document.myForm.countrySelect;
for (var i = 0; i < countryDropdown.options.length; i++)
{
if (countryDropdown.options[i].selected)
{
selectedCountry = countryDropdown.options[i].value;
}
}
if (selectedCountry == 1)
{
stateArray = UnitedStates;
populateDropdown(stateArray);
}
if (selectedCountry == 2)
{
stateArray = UnitedKingdom;
populateDropdown(stateArray);
}
}
counter = 0;
function ff()
{
counter++;
var box = document.getElementById("details"+counter);
var cselectBox = document.createElement("Select");
cselectBox.name="countrySelect";
cselectBox.onchange = function()
{
updateDropdown();
}
var option1 = document.createElement("OPTION");
option1.text="United States";
option1.value=1;
cselectBox.options.add(option1);
var option2 = document.createElement("OPTION");
option2.text="United Kingdom";
option2.value=2;
cselectBox.options.add(option2);
document.getElementById("details"+counter).innerHTML+="</p><p>"+counter+". Candidate Country";
box.appendChild(cselectBox);
var box2 = document.getElementById("detailsx"+counter);
var ccselectBox = document.createElement("Select");
ccselectBox.name="stateSelect";
document.getElementById("detailsx"+counter).innerHTML+="</p><p>"+counter+". Candidate City";
box2.appendChild(ccselectBox);
}
</script>
</head>
<body>
<form name="myForm" >
<input type="button" value="Add Candidate" onClick="ff(); populateDropdown(UnitedStates);"">
<!--- Note: 6 Candidates will be the maximum. -->
<div id="details1"><b></b></div>
<div id="detailsx1"><b></b></div>
<div id="details2"><b></b></div>
<div id="detailsx2"><b></b></div>
<div id="details3"><b></b></div>
<div id="detailsx3"><b></b></div>
<div id="details4"><b></b></div>
<div id="detailsx4"><b></b></div>
<div id="details5"><b></b></div>
<div id="detailsx5"><b></b></div>
<div id="details6"><b></b></div>
<div id="detailsx6"><b></b></div>
</form>
</body>
</html>

There are multiple problems here. We'll tackle the one you're dealing with first.
When you name multiple controls with the same name, like stateSelect, you'll get the first one each time you try to reference it. If you instead set the id to 'stateSelect' + counter, you'll get a unique id, which you can then retrieve with document.getElementById(). So in the function to populate the dropdown would look like this:
function populateDropdown(arry)
{
var stateSelect = document.getElementById('stateSelect'+counter);
stateSelect.options.length = 0;
for (var i = 0; i < arry.length; i++)
{
stateSelect.options[i] = new Option(arry[i], arry[i]);
}
}
here is the fiddle I used to verify those changes.
You'll also need to add an event to each country dropdown to repopulate the state dropdown when it changes, and the structure needs a little work for that. If you're not opposed to frameworks, knockout would make this incredibly simple to run.
Here is the fiddle with everything working correctly and comments added at key changes
Update: Added link to the fiddle(s)

Related

put a save code in a text box and than change a variable to that save code

I'm back and i tried it but is doesn't work anyone that can help??? i have already put in the save mechanism.
(i had to add extra text so this has nothing to do with the script itself)
this is the code that i used to test the save mechanism.
<!DOCTYPE html>
<html>
<body>
<button onclick="point();">points</button>
<button onclick="upgrade()">upgrade</button>
<script language="javascript">
var pointcount = 0;
var totalcliks = 0;
var upgrades = 0;
function point() {
pointcount++;
totalcliks++;
}
function upgrade() {
upgrades++;
pointcount--;
}
function load() {
var testerload = document.getElementById("savecodetextbox").value;
document.getElementById("saveshow").innerHTML = testerload;
}
var pointcounterclock = setInterval(function() {pointcounter()},100);
function pointcounter(){
document.getElementById("points-screen").innerHTML = pointcount+" points";
document.getElementById("clicktotal").innerHTML = totalcliks+" totalcliks";
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
}
let savecode = "1a1a1"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[1];
updates = codes[2];
pointcount = codes[3];
}
</script>
<h3 id="points-screen"></h3>
<h3 id="clicktotal"></h3>
<h3 id="savecode"></h3>
<textarea name="text_area" id="savecodetextbox" rows="4" cols="40"></textarea> <button onclick="load()">load</button>
<h3 id="saveshow"></h3>
</body>
</html>
I'm going to alter your save code so I don't have to confuse you with regular expressions or funky splits:
document.getElementById("savecode").innerHTML = totalcliks+"a"+ pointcount+"a"+ upgrades;
Which means your save code could look something like: 4a6a9
Do a simple split:
let savecode = "4a5a6"; //grab the input for savecode here
let codes = savecode.split("a");
if(codes.length == 3){ //verify the length is correct
totalcliks = codes[0];
upgrades = codes[1];
pointcount = codes[2];
}
As for implementing the variables, reload the game after

find values of custom attribute in html using Jquery

Click here for code
Inside loop of {listOfValue}
i want to find different column values filtered by data-week = {listofvalueObject}
and want to add data in each row based on column segregated by this data-week attributes value.
I have assigned the values form a list so it every column has different data-week value.
I have tried :
var allColumnValClass = j$('.columnVal').filter('[data-week]');
var allColumnValClass = j$('.columnVal').filter('[data-week='Something dynamic ']');
You should be able to select them like this:
var allColumnValClass = j$('.columnVal[data-week]')
and
var allColumnValClass = j$('.columnVal[data-week="' + Something dynamic + '"]')
Hope this helps.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='columnVal' data-week="1"></div>
<div class='columnVal' data-week="2"></div>
<div class='columnVal' data-week="3"></div>
<script>
var dataList = $(".columnVal").map(function () {
return $(this).data("week");
}).get();
for (var i = 0; i < dataList.length; i++) {
console.log(dataList[i]);
}
</script>
cheers

Adding a checkbox next to each list item using a for loop

I'm trying to build a todo list using javascript and this is what I've got so far:
HTML
<!DOCTYPE html>
<html>
<head>
<title>To Do List</title>
</head>
<body>
<div id='TodoTable-wrapper'>
<ul id='TodoTable'>
</ul>
</div>
<input type="text" placeholder= "What needs to be done?" id="todoText">
<button class="btn" id="addTodo">Add</button>
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT
var inputField = document.getElementById('todoText');
var todoList = new Array();
var uList = document.getElementById('TodoTable');
var addButton = document.getElementById('addTodo');
var listItemCheckbox = document.createElement('input');
listItemCheckbox.type = 'checkbox';
var addTodo = function (todoText) {
addToArray(todoText);
refreshList();
};
var addToArray = function(text) {
todoList.push(inputField.value);
}
var refreshList = function() {
uList.innerHTML = "";
var listItem;
for (var i = 0; i<todoList.length; i++) {
listItem = document.createElement('li');
listItem.innerHTML = todoList[i];
uList.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
}
}
addButton.addEventListener('click', function(e){
var todoText = inputField.value;
addTodo(todoText);
});
The problem I have is that as a new list item is created, only the last item in the list has a checkbox next to it (the previews ones get deleted). I have an inkling that this happens because the function refreshList creates a new list every time the array 'todoList' is updated and the 'listItem.appendChild' only runs once in the for loop.
Is there a way for me to get it run every time a list item is created, as well as find a way to associate it with the corresponding list item? (so I can create a function to delete individual list items later).
Thanks alot in advance for any input!
You are reusing the same checkbox object.
You should create a new checkbox everytime you need to add one, otherwise you are just moving it from one place to another.

Having a difficulty adding a new form in each new <div>

In my adventure to create a To-Do list application, I've run into another problem. In my code, every time a user clicks New Category a new div will appear with their custom name and number of forms.
However, when another div is created, its' forms are given to the previous div. Here's that code:
<script src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type='text/javascript' src="script.js"></script>
<script>
$(function() {
$("#new").click(function() {
var canContinue = true;
var newCategory = prompt("Enter the name you want for your category:");
if(newCategory.length === 0){
confirm("A new category can not be created - nothing was entered in the text area.");
canContinue = false;
}
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
$("body").append("<div id = \"newDiv\"><p>" + newCategory + "</p></div>");
}
for(var i = 0; i < categorySections; i++){
$("#newDiv").append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
</script>
So, I tried creating a separate function using the this keyword where the forms were created after the div was ready, but now no forms are created at all!
Here's that code:
$(function(){
$("#newDiv").ready(function() {
for(var i = 0; i < categorySections; i++){
$(this).append("<form> Thing to do: <input type = \"text\"></form><br>");
}
});
});
So, how do I create forms for each separate div?
You're repeatedly creating divs with the same ID. (a) that's not legal and (b) if you do it anyway, your $(#newDiv) selector will always apply to the first one.
Also, you're appending to #newDiv outside the if (canContinue) check.
Try:
if(canContinue){
var categorySections = prompt("Enter the number of sections needed for this category:");
var newDiv = $("<div>").appendTo($(document.body));
var header = $('<p>').text(newCategory).appendTo(newDiv);
for(var i = 0; i < categorySections; i++){
newDiv.append("<form> Thing to do: <input type = \"text\"></form><br>");
}
}
jsFiddle
You can't use the ID newDiv multiple times, HTML IDs must be unique. Additionally, your flow can be cleaned up a bit, as below.
$(function () {
$("#new").click(function () {
var newCategory = prompt("Enter the name you want for your category:");
if (newCategory.length === 0) {
confirm("A new category can not be created - nothing was entered in the text area.");
return false;
}
var categorySections = prompt("Enter the number of sections needed for this category:");
var $div = $("<div />", {
html: "<p>" + newCategory + "</p>"
});
$("body").append($div);
for (var i = 0; i < categorySections; i++) {
$div.append("<form> Thing to do: <input type='text'/></form><br>");
}
});
});

Dynamically generating a button using DOM and editing onclick event

I trying to generate an input (type="button") and setting the onclick-Event to a function, which should hand over a parameter. The whole object should be appended to a div and thats it. Basically this is my try, but I can't see why it does not work.
I pasted the code to jsfiddle, hence its easier for you to reproduce. Click here.
What am I'm doing wrong? I'm learning it by trial and error, so please explain whats wrong. Thanks a lot!
[edit] for the case jsfiddle will be down one day, here is the code I tried to run... :)
<!doctype html>
<html>
<head>
<title>onclick event example</title>
<script type="text/javascript" language="javascript">
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
var h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}​
</script>
</head>
<body>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
</body>
</html>
Here is the fixed fiddle for you.
var h[i] = ... is invalid JavaScript.
What you write in the "JavaScript" frame on jsfiddle is executed onload, so this code is not yet present when the HTML you provide is executed (and neither is the addButton() function).
<script>
var i = 0;
var h = new Array();
function addButton() {
i++;
var container = document.getElementById("check0");
h[i] = document.createElement("input");
h[i].type = 'button';
h[i].name = 'number' + i;
h[i].value = "number" + i;
h[i].id = 'number' + i;
h[i].onclick = function() {
showAlert(i)
};
container.appendChild(h[i]);
}
function showAlert(number) {
alert("You clicked Button " + number);
}
</script>
<div id="check0">
<input type="button" value="klick mich" id="number0" onclick="addButton()"/>
</div>​
Try using h.push(...) instead of trying to send to a non created element in the array
var x = document.getElementById('pagination');//pagination is an empty div in html
var y ='';
for(var i = 0; i <= (pageMax); i++){
y = y+"<a id ='pageNumber"+i+"' onclick='changePage("+(i+1)+");'>"+(i+1)+"</a>\n ";
} x.innerHTML=y }
i used this to make a pagination for a table. The function will create a row of numbers until button max. 'changePage("+(i+1)+"); ... will call a function and send the i index(number that the page is) of the pagenumber. also i dynamically create a id unique for each number.

Categories