In my JavaScript program, I get values from a form through its elements and then print them in order, in an alert. This works fine in Firefox, but in Chrome the order is wacky and it ends with the "Submit" button.
I tried getting rid of the fieldset and adjusting the numbers, and it worked, but I liked the fieldset! Also, I can't just make an array and iterate through it because the fields are tab-order adjusted and I want to print them accordingly. Any suggestions?
Upon trying to validate I found that I do indeed need the fieldset for XHTML Strict. I've been storing the elements in an array, like so:
var $ = function (id) { return document.getElementById(id); }
function check() {
var x = $("myForm");
var user = new Array();
user[0] = x.elements[0].value;
user[1] = x.elements[2].value;
user[2] = x.elements[4].value;
user[3] = x.elements[1].value;
user[4] = x.elements[3].value;
user[5] = x.elements[5].value;
And then checking them using another couple of arrays and displaying the results in a pop-up:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
if (user[i] == "") {
display[i] = "You entered nothing.";
}
else if (user[i] == answers[i]) {
display[i] = "Correct!";
}
else {
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
}
WebKit bug (https://bugs.webkit.org/show_bug.cgi?id=48193).
I think you'll be better off using IDs:
<form ...>
<input ... id="q0" />
<input ... id="q1" />
<input ... id="q2" />
</form>
So you can write this JavaScript code:
var answers = new Array();
answers[0] = "sample1";
answers[1] = "sample2";
answers[2] = "sample3";
answers[3] = "sample4";
answers[4] = "sample5";
answers[5] = "sample6";
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display[i] = "You entered nothing.";
else if (user == answers[i])
display[i] = "Correct!";
else
display[i] = "Wrong. The correct answer is \"" + answers[i] + "\".";
}
alert(display[0] + "\n" + display[1] + "\n" + display[2] + "\n" + display[3] + "\n" + display[4] + "\n" + display[5]);
Your code can receive a lot of improvement, too:
var answers = [ "sample1", "sample2", "sample3", "sample4", "sample5", "sample6" ];
var display = new Array();
for (var i=0;i<6;i++) {
var user = $('q' + i).value;
if (user == "")
display.push( "You entered nothing." );
else if (user == answers[i])
display.push( "Correct!" );
else
display.push ( "Wrong. The correct answer is \"" + answers[i] + "\"." );
}
alert(display.join('\n'));
Related
I am working on an assignment that I feel like I am very close to finishing, but something is going wrong. When I try to print each employee to the table at the end, nothing happens. my array for the "new employee" is returning an empty array.
please help explain your code if you correct mine. it is a little bit of a long code, but i appreciate the help! everything was working until i added the deptSearch stuff, and everything underneath it.
i left out the removeChildren() and selectedValue() because they were pre-coded for me and they work with no issue
lastly, the only code i was supposed to write for this assignment is within the eventListener ("click") function
/* Constructor function for the employee class */
function employee(id, firstName, lastName, dept, position, email, phone, photo) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dept = dept;
this.position = position;
this.email = email;
this.phone = phone;
this.photo = photo;
}
/* Object literal for search results */
var searchResult = {
employees : [],
sortById : function() {
this.employees.sort(function(a,b) {
if (a.id < b.id) {return -1;}
else {return 1;}
});
}
};
/* Event listener to retrieve and display employee records matching the search condition */
document.getElementById("searchButton").addEventListener("click", function() {
var tableBody = document.querySelector("table#staffTable tbody");
var tableCaption = document.querySelector("table#staffTable caption");
tableBody.removeChildren();
searchResult.employees = [];
staff.directory.forEach(function (record){
var nameSearch = document.getElementById("nameSearch").value;
var nameSearchType = document.getElementById("nameSearchType").selectedValue();
var positionSearch = document.getElementById("positionSearch").value;
var positionSearchType = document.getElementById("positionSearchType").selectedValue();
var deptSearch = document.getElementById("deptSearch").selectedValue();
// nameSearch switch
switch (nameSearchType) {
case "contains":
var nameRegExp = new RegExp(nameSearch, 'i');
break;
case "beginsWith":
var nameRegExp = new RegExp('^' + nameSearch, 'i');
break;
case "exact":
var nameRegExp = new RegExp('^' + nameSearch + '$', 'i');
break;
} // end of nameSearch switch
var foundName = nameRegExp.test((record.lastName));
// positionSearch switch
switch (positionSearchType) {
case "contains":
var positionRegExp = new RegExp(positionSearch, 'i');
break;
case "beginsWith":
var positionRegExp = new RegExp('^' + positionSearch, 'i');
break;
case "exact":
var positionRegExp = new RegExp('^' + positionSearch + '$', 'i');
break;
} // end of positionSearch switch
var foundPosition = positionRegExp.test((record.position));
// deptSearch if statement
if (deptSearch == "" || deptSearch == record.dept.valueOf()) {
var foundDept = true;
}
if (foundName && foundPosition && foundDept) {
searchResult.employees.push(new employee(record.id, record.firstName, record.lastName, record.dept, record.position, record.email, record.phone, record.photo));
}
console.log(searchResult.employees);
});
tableCaption.textContent = searchResult.employees.length + " records found";
searchResult.sortById();
searchResult.employees.forEach(function () {
tableBody.innerHTML += "<tr>\
<td><img src=" + searchResult.employees.employee.photo + " /></td>\
<td>" + searchResult.employees.firstName + " " + searchResult.employees.lastName + "</td>\
<td>" + searchResult.employees.dept + "</td>\
<td>" + searchResult.employees.position + "</td>\
<td><a href='mailto:" + searchResult.employees.email + "'>" + searchResult.employees.email + "</a></td>\
<td><a href='tel:" + searchResult.employees.phone + "'>" + searchResult.employees.phone + "</a></td>\
</tr>"
});
});
I currently have two arrays, nameArray and markArray which are added to when users input their name and mark. I want to display all names and marks at the click of a button but have what mark belongs to who obvious. My attempts are below creating displayInfo but whenever I try to output it to HTML it only shows the last one in each array.
if (Array.isArray(nameArray) && nameArray.length) {
console.log("display all working");
// var displayName = nameArray.toString();
// var displayMark = markArray.toString();
for(let i=0; i < nameArray.length; i++){
var displayInfo = "";
//var displayInfo = nameArray[i] + "<br/>" + markArray[i];
//console.log(displayInfo)
//document.getElementById("result").innerHTML = displayInfo;
displayInfo += nameArray[i] + "<br/>" + markArray[i] + "";
}
document.getElementById("result").innerHTML = displayInfo
}else{
document.getElementById("result").innerHTML = "No result's have been entered! Please enter results before display them!"
}
} ```
var name = document.getElementById("name").value;
var mark = document.getElementById("mark").value;
if(name == "" || mark == ""){
document.getElementById("result").innerHTML = "An input field is empty please try again."
}else{
nameArray.push(name);
markArray.push(mark);
console.log(nameArray);
document.getElementById("result").innerHTML = name + "'s " + "results have been added to the system!"
}
}```
The output should look something like John-4 Jack-6, just any way in which it is clear whos result it is.
if (Array.isArray(nameArray) && nameArray.length) {
console.log("display all working");
var displayInfo = [];
// var displayName = nameArray.toString();
// var displayMark = markArray.toString();
for(let i=0; i < nameArray.length; i++){
//var displayInfo = nameArray[i] + "<br/>" + markArray[i];
//console.log(displayInfo)
//document.getElementById("result").innerHTML = displayInfo;
displayInfo.push(nameArray[i] + "<br/>" + markArray[i] + "");
}
displayInfo.forEach(single => {
document.getElementById("result").innerHTML = single;
})
}else{
document.getElementById("result").innerHTML = "No result's have been entered! Please enter results before display them!"
}
You are overwriting your variable inside your loop until the loop ends, which is why you get the last element of the array. Try my code.
I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>
In PHP it's easy to create variables.
for($i=1; $i<=$ges; $i++) {
${"q" . $i} = $_POST["q".i];
${"a" . $i} = $_POST["a".i];
}
The result is $a1 = $_POST["q1];
How is the right way for that in jQuery?
I need to create it dynamicly for an ajax dataset.
for (var i = 1; i < ges; ++i) {
var finalVar = "input[name='a" + i + "']:checked";
var qtext = $("#q"+ i).text();
if ($(finalVar).val() == null) {
qvar = 0
} else {
qvar = $(finalVar).val();
}
//write question text and value in q1, a1, q2, a2,...
//generate ajax data
params = params + "q" + i + ":" + "q" + i + ", " + "a" + i + ":" + "a" + i + ","
}
I want to set the question text in q1 and the answer in a1.
Well if am not wrong you want to accumulate answers related to questions from the HTML and want to send the data through ajax..
So u can do something like this:
var QnA = {};
$('.eventTrigger').click(function(e) {
e.preventDefault();
$('#parent').find('.QnA').each(function() {
QnA[$(this).find('.Que').text()] = $(this).find('.Ans').val();
})
console.log(QnA);
})
https://jsfiddle.net/jt4ow335/1/
The only thing you can do about it, is:
var obj = {}
for(var i = 0; i < 10; i++)
obj['cell'+i] = i
console.log(obj)
and pass obj as data
I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...