Case in Switch statement involving array with conditions - javascript

I have an array which is to be iterated and depending on the condition execute task
I have done this with if else and trying it out with Switch.And the condition is if (1 && 2) (then execute A) else if (1) (then execute B) else if (2) (then execute c) else if (none) (then execute D)
function showFiletRelateddata(selectedFilter) {
/*if (selectedFilter.length === 0) {
console.log("No data");
} else if (
selectedFilter.includes("Request") &&
selectedFilter.includes("Reservation")
) {
console.log("RequestReservation");
} else if (selectedFilter.includes("Request")) {
console.log("Request");
} else if (selectedFilter.includes("Reservation")) {
console.log("Reservation");
}*/
var filt = selectedFilter;
for (var i = 0; i < filt.length; i++) {
var supp = filt[i];
switch (supp) {
case "Request":
case "Reservation":
console.log("RequestReservation");
break;
case "Request":
console.log("Request");
break;
case "Reservation":
console.log("Reservation");
break;
default:
console.log("No data");
}
}
}
The if else is working fine however what correction needs to be made for Switch statement
For ref =
Javascript switch case with array or strings

function showFiletRelateddata(selectedFilter) {
var filt = selectedFilter;
var supp = ""
for (var i = 0; i < filt.length; i++) { //loop over length of array
supp = supp + filt[i]; // concat elements of array
}
switch (supp) {
case "RequestReservation": // if case contains one of the condition
case "ReservationRequest":
console.log("RequestReservation");
break;
case "Request":
console.log("Request");
break;
case "Reservation":
console.log("Reservation");
break;
default:
console.log("No data");
}
}
var a = ["Reservation", "Request"];
var b = ["Request","Reservation"];
var c = ["Reservation"];
var d = ["Request"];
showFiletRelateddata(a);
showFiletRelateddata(b);
showFiletRelateddata(c);
showFiletRelateddata(d);

Related

Submit form via AJAX using plain Javascript without Jquery get checked radio button value

I do have HTML form submitting via AJAX using plain Javascript:
function XMLhttp(){
var formInputs = document.getElementById(formID).querySelectorAll("input, textarea");
var selectFormGebdat = formID;
var toCheckDatesFields = document.getElementsByClassName("checkDate");
for (var i = 0; i < toCheckDatesFields.length; i++) {
if(toCheckDatesFields.item(i).value != '') {
var returnValue = validatedate(toCheckDatesFields.item(i));
if(returnValue == false) {
return false;
}
}
}
var httpRequest = new XMLHttpRequest();
var formData = new FormData();
for( var i=0; i < formInputs.length; i++ ){
formData.append(formInputs[i].name, formInputs[i].value);
}
httpRequest.onreadystatechange = function(){
if ( this.readyState == 4 && this.status == 200 ) {
resultData = JSON.parse(this.responseText);
if(resultData.success == true) {
document.getElementById('resultok').className += ' show';
}
else {
document.getElementById('resulterror').className += ' show';
};
}
};
httpRequest.open(formMethod, formAction);
httpRequest.send(formData);
}
selectButton.onclick = function(){
XMLhttp();
}
selectForm.onsubmit = function(){
return false;
}
My problem is, that I have radio buttons and select-box. But the selected values are not submitted. F.ex.
<input type="radio" name="typ" value="anfrage"><input type="radio" name="typ" value="reservierung">
If anfrage is checked, the script is not submitting this value - there is always reservierung submitting.
Thanks for help!
Martin
I could solve this by:
var formData = new FormData();
if (!form || form.nodeName !== "FORM") {
return;
}
var i, j, q = [];
for (i = form.elements.length - 1; i >= 0; i = i - 1) {
if (form.elements[i].name === "") {
continue;
}
switch (form.elements[i].nodeName) {
case 'INPUT':
switch (form.elements[i].type) {
case 'text':
case 'hidden':
case 'password':
case 'button':
case 'reset':
case 'submit':
formData.append(form.elements[i].name, form.elements[i].value);
break;
case 'checkbox':
case 'radio':
if (form.elements[i].checked) {
formData.append(form.elements[i].name, form.elements[i].value);
}
break;
case 'file':
break;
}
break;
case 'TEXTAREA':
formData.append(form.elements[i].name, form.elements[i].value);
break;
case 'SELECT':
switch (form.elements[i].type) {
case 'select-one':
formData.append(form.elements[i].name, form.elements[i].value);
break;
case 'select-multiple':
for (j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
if (form.elements[i].options[j].selected) {
formData.append(form.elements[i].name, form.elements[i].value);
}
}
break;
}
break;
case 'BUTTON':
switch (form.elements[i].type) {
case 'reset':
case 'submit':
case 'button':
formData.append(form.elements[i].name, form.elements[i].value);
break;
}
break;
}
}

Array with JSON Objects inside that are written starting and ending with curly braces error

I am given an "array" with JSON Objects inside like so (it's not an actual array since it begins with curly braces):
{{"x1","x2"},{"y1","y2"},{"z1","z2"}}
How can I make it so that the first and last { curly braces } becomes square braces [ ]?
Javascript does not recognize the above example as an array and throws an error. Calling JSON.stringify or JSON.parse does not work either since the above is not actual JSON/Array. Only when it has [ square brackets ] does it actually work since then it is an array with JSON objects inside it. Like so:
[{"x1","x2"},{"y1","y2"},{"z1","z2"}]
I was thinking of making it into a string first, then replacing the first and last char with [ and ] respectively, but calling String(value), where value is the first "array", simply doesn't cut it as it thinks it is a JSON and throws unexpected token if I even declare it.
If you're trying to create an array of JSON objects, you could do as follow:
const object = new Array(
{ 'x1': 'x2' },
{ 'y1': 'y2' },
{ 'z1': 'z2' }
);
console.log( object[0] );
expecting in the console the following result:
{
x1: "x2"
}
Hope it helps.
As it was already pointed out in comments, your input JSON isn't really JSON at all - you'll want a custom parser for it. Here's something quickly scrambled from Haxe's haxe.format.JsonParser:
var Std = function() { };
Std.parseInt = function(x) {
if(x != null) {
var _g = 0;
var _g1 = x.length;
while(_g < _g1) {
var i = _g++;
var c = x.charCodeAt(i);
if(c <= 8 || c >= 14 && c != 32 && c != 45) {
var nc = x.charCodeAt(i + 1);
var v = parseInt(x,nc == 120 || nc == 88 ? 16 : 10);
if(isNaN(v)) {
return null;
} else {
return v;
}
}
}
}
return null;
};
var StringBuf = function() {
this.b = "";
};
var JsonParser = function(str) {
this.str = str;
this.pos = 0;
};
JsonParser.prototype = {
doParse: function() {
var result = this.parseRec();
var c;
while(true) {
c = this.str.charCodeAt(this.pos++);
if(!(c == c)) {
break;
}
switch(c) {
case 9:case 10:case 13:case 32:
break;
default:
this.invalidChar();
}
}
return result;
}
,parseRec: function() {
while(true) switch(this.str.charCodeAt(this.pos++)) {
case 9:case 10:case 13:case 32:
break;
case 34:
return this.parseString();
case 123:
var arr = [];
var comma = null;
while(true) switch(this.str.charCodeAt(this.pos++)) {
case 9:case 10:case 13:case 32:
break;
case 44:
if(comma) {
comma = false;
} else {
this.invalidChar();
}
break;
case 125:
if(comma == false) {
this.invalidChar();
}
return arr;
default:
if(comma) {
this.invalidChar();
}
this.pos--;
arr.push(this.parseRec());
comma = true;
}
break;
default:
this.invalidChar();
}
}
,parseString: function() {
var start = this.pos;
var buf = null;
var prev = -1;
while(true) {
var c = this.str.charCodeAt(this.pos++);
if(c == 34) {
break;
}
if(c == 92) {
if(buf == null) {
buf = new StringBuf();
}
var s = this.str;
var len = this.pos - start - 1;
buf.b += len == null ? s.substr(start) : s.substr(start,len);
c = this.str.charCodeAt(this.pos++);
if(c != 117 && prev != -1) {
buf.b += String.fromCodePoint(65533);
prev = -1;
}
switch(c) {
case 34:case 47:case 92:
buf.b += String.fromCodePoint(c);
break;
case 98:
buf.b += String.fromCodePoint(8);
break;
case 102:
buf.b += String.fromCodePoint(12);
break;
case 110:
buf.b += String.fromCodePoint(10);
break;
case 114:
buf.b += String.fromCodePoint(13);
break;
case 116:
buf.b += String.fromCodePoint(9);
break;
case 117:
var uc = Std.parseInt("0x" + this.str.substr(this.pos,4));
this.pos += 4;
if(prev != -1) {
if(uc < 56320 || uc > 57343) {
buf.b += String.fromCodePoint(65533);
prev = -1;
} else {
buf.b += String.fromCodePoint(((prev - 55296 << 10) + (uc - 56320) + 65536));
prev = -1;
}
} else if(uc >= 55296 && uc <= 56319) {
prev = uc;
} else {
buf.b += String.fromCodePoint(uc);
}
break;
default:
throw new ("Invalid escape sequence \\" + String.fromCodePoint(c) + " at position " + (this.pos - 1));
}
start = this.pos;
} else if(c != c) {
throw new ("Unclosed string");
}
}
if(prev != -1) {
buf.b += String.fromCodePoint(65533);
prev = -1;
}
if(buf == null) {
return this.str.substr(start,this.pos - start - 1);
} else {
var s1 = this.str;
var len1 = this.pos - start - 1;
buf.b += len1 == null ? s1.substr(start) : s1.substr(start,len1);
return buf.b;
}
}
,invalidChar: function() {
this.pos--;
throw "Invalid char " + this.str.charCodeAt(this.pos) + " at position " + this.pos;
}
};
JsonParser.parse = function(s) {
return new JsonParser(s).doParse();
}
If someone is giving you this you really ought to go back to the source and inform them that they are NOT providing you with a valid input.
I avoid having to hack around poor source data.
Fix it at the source and not have to deal with it everywhere that it is used.

After finding a word in html body, replace it with another one

i have this code that finds a word in the entire body of a html page
var word = "active",
queue = [document.body],
curr
;
while (curr = queue.pop()) {
if (!curr.textContent.match(word)) continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE : // 3
if (curr.childNodes[i].textContent.match(word)) {
console.log("Found!");
console.log(curr);
// you might want to end your search here.
word.replace('active', 'test');
}
break;
case Node.ELEMENT_NODE : // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
And what i'm trying to do is if active is found, replace it with something else but i have tried some ways and i wasnt able to do it. What i'm doing wrong?
This would give the result you are looking for (I decided to skip of 'SCRIPT' nodeName's so you do not accidentally modify any code:
let word = "active";
let queue = [document.body];
let curr;
while (curr = queue.pop()) {
if (!curr.textContent.match(word) || curr.nodeName === 'SCRIPT') continue;
for (var i = 0; i < curr.childNodes.length; ++i) {
if (curr.childNodes[i].nodeName === 'SCRIPT') continue;
switch (curr.childNodes[i].nodeType) {
case Node.TEXT_NODE: // 3
if (curr.childNodes[i].textContent.match(word)) {
console.log("Found!", `'${curr.childNodes[i].textContent}'`);
curr.childNodes[i].textContent = curr.childNodes[i].textContent.replace('active', 'test');
}
break;
case Node.ELEMENT_NODE: // 1
queue.push(curr.childNodes[i]);
break;
}
}
}
<div>asdf</div>
<span>active</span>
<div>asdf</div>
Hope this helps,

Multiple Files check extension is Pdf

How can we get multiple uploaded files has pdf if yes then enable Div
case 1: when I am trying to upload pdf file pdf checkbox is enabled
Case 2: upload docx or any other file checkbox gets hides
Case 3: When trying to upload different files such as txt, docx, pdf it is not showing checkbox
Please suggest how can we check extensions for multiple uploaded files and if there is pdf extension show checkbox div.
if (extn == 'pdf' || extn=='PDF') {
$('#<%=chkAddPdfPassword.ClientID%>').removeAttr('checked');
$("#chkPdf").show();
} else {
$("#chkPdf").hide();
$("#divPasswordField").hide();
}
Thanks in Advance
var files = $('#<%=uploadFile.ClientID %>')[0].files;
for (var i = 0; i < files.length; i++) {
var a = checkFileExtension(files[i].name);
if ((a == "pdf") || (typeof a !== "undefined")) {
console.log('check pdf');
$("#chkPdf").show();
break;
}
else {
$("#chkPdf").hide();
}
}
function checkFileExtension(file) {
var extension = file.substr((file.lastIndexOf('.') + 1));
var fileExtn;
switch (extension) {
case 'pdf':
console.log('was pdf');
fileExtn = 'pdf';
break;
default:
console.log('who knows');
fileExtn = 'default';
}
return fileExtn;
};
Solution :
var files = $('#<%=uploadFile.ClientID %>')[0].files;
for (var i = 0; i < files.length; i++) {
var a = openFile(files[i].name);
if ((a == "pdf") || (typeof a !== "undefined")) {
console.log('check pdf');
$("#chkPdf").show();
break;
}
else {
$("#chkPdf").hide();
$("#divPasswordField").hide();
}
}
function openFile(file) {
var extension = file.substr((file.lastIndexOf('.') + 1));
var fileExtn;
switch (extension) {
case 'jpg':
case 'png':
case 'txt':
console.log('was txt'); // There's was a typo in the example where
break; // the alert ended with pdf instead of gif.
case 'zip':
case 'docx':
console.log('was docx');
break;
case 'pdf':
console.log('was pdf');
fileExtn = 'pdf';
break;
default:
console.log('who knows');
fileExtn = 'default';
}
return fileExtn;
};

How to find a word within an href link in a div element using jquery

There is a div element that always contain one of the array words inside an a href element. Depending on what the word is, I need the web page to redirect to a different page. I'm not sure what I a missing.
http://jsfiddle.net/5Legahgn/5/
if ($('.container-fluid:contains("It looks something like this")').length > 0 || ($('.container-fluid:contains("Have you visited")').length > 0)) {
var uTest = ["Saggitarius", "Quentin", "Cinthia", "Maleria", "Pete", "Library", "wizard"];
var aTest = uTest.length;
var i = 0;
for (i; i < aTest; i++) {
if ($('.container-fluid:contains("'+uTest[i]+'")').length > 0) {
var mTest = uTest[i];
if (mTest != null || undefined) {
switch (mTest) {
case "Saggitarius":
window.location.href = 'https://subeta.net/quests.php/saggitarius';
break;
case "Quentin":
window.location.href = '...';
break;
case "Cinthia":
window.location.href = '...';
break;
case "Maleria":
window.location.href = '...';
break;
case "Pete":
alert("Pete");
break;
case "Library":
window.location.href = '...';
break;
case "wizard":
window.location.href = '...';
break;
case "Mori":
window.location.href = '...';
break;
}
} else {
alert("done");
}
}
}
}

Categories

Resources