What's wrong in this script? - javascript

When I submit the form and I try to get the Roomsno input value its showing like
this-
Array ( [0] => 1,2 ); why???
How can I send it so that it will come as a real array means like this-
Array([0]=>1 [1]=>2)
<input type="hidden" class="form-control" name="Roomsno" id="Roomsno" required>
<script>
var rmidarray = []; // new Array()
var rmnoarray = [];
$('.roomtype').change(function() {
roomss_id = $(this).attr('data-id');
no_room = $(this).val();
var check = rmidarray.includes(roomss_id);
if (check == true) {
// alert('hi')
index = rmidarray.indexOf(roomss_id);
// alert(index);
rmnoarray.splice(index, 1, no_room);
// rmnoarray[index].push(no_room);
} else if (check == false) {
// alert('by');
rmidarray.push(roomss_id);
rmnoarray.push(no_room);
} else {
alert('No rooms Selected!!!')
}
$("#Roomsno").val(rmnoarray);
});
</script>

As the value is in array format so Rather than setting the value directly use jason.stringfy-
Ex.
$("#Roomsno").val(rmnoarray); //Instead of this one
$('#Roomsno').val(JSON.stringify(rmnoarray)); //This one worked for me
And when i try to get the value i use json.decode and the value will come as array and we can use it normally as we use array. The array will come like- Array([0]=>1[1]=>2)

Related

How do I use an HTML text box value as a JavaScript parameter or variable and call the JavaScript Function with the text box value?

I have a JavaScript function that works on its own, however, I am having difficulty getting it to function correctly inside of an HTML web page (no server backend). The function that works correctly by itself is:
function decodeUrlDefensev3(link) {
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
var link = "https://urldefense.com/v3/__https://files.bitsight.com/e3t/Ctc/LR*113/c1NcF04/VWyThK1lvg49W724nRX2d04lQW1xTZ7Q4QfX7gN6fpSV75nCTJV3Zsc37CgZP4N95fbTLz6L-gW48j6gR3bC3zwW6L_GnH7kDhzMW9418Rb3hJ605W2HjF587SWBXyW8RmYtF6fgdWYW5XQmQn1bFttzW5qPlhD5h_TCqW4-gDCr8x7fD0N4M_DVGdxFD9W2T0jhF4j9YsWW7603Qw8dF3j7W36QBsz4RM6hNW6Hpcdy8Qtmw4W8y5VBz2TLWGhVTNFr45gN7FDW7m9S0M1tvjXNW7vLHnj2945hZW437Z0x5Vd_ZcW7MjgJC89gYB6W2Y3sH14zDDZvW39S6bT1pFgM2W8gn9pV4HdltbW3MTVMS59VlW-VBQkF74S69PWW5yn7jz6PhmVLW4sYpYl4yDVH4W3dkf3v6S141VW3Sqpcn7xkSPcW33N24p3R1FxPW3y04W03TWHN4N2wvRyC4j7X83p5G1__;Kw!!HhY5bxTJhQ!vdj_DUrp0JIWgTw61Vg8M1chEvhp0k7XlLFiomq0Wu1rCrze9dzn2inIIVKchdRRP6HqJshCEuIHCbwCa1ha0FPyFA$"
console.log(decodeUrlDefensev3(link))
Expected output:
https://files.bitsight.com/e3t/Ctc/LR*113/c1NcF04/VWyThK1lvg49W72*nRX2d04lQW1xTZ7Q4QfX7gN6fpSV75nCTJV3Zsc37CgZP4N95fbTLz6L-gW48j6gR3bC3zwW6L_GnH7kDhzMW9418Rb3hJ605W2HjF587SWBXyW8RmYtF6fgdWYW5XQmQn1bFttzW5qPlhD5h_TCqW4-gDCr8x7fD0N4M_DVGdxFD9W2T0jhF4j9YsWW7603Qw8dF3j7W36QBsz4RM6hNW6Hpcdy8Qtmw4W8y5VBz2TLWGhVTNFr45gN7FDW7m9S0M1tvjXNW7vLHnj2945hZW437Z0x5Vd_ZcW7MjgJC89gYB6W2Y3sH14zDDZvW39S6bT1pFgM2W8gn9pV4HdltbW3MTVMS59VlW-VBQkF74S69PWW5yn7jz6PhmVLW4sYpYl4yDVH4W3dkf3v6S141VW3Sqpcn7xkSPcW33N24p3R1FxPW3y04W03TWHN4N2wvRyC4j7X83p5G1
The above code will return a correctly decoded website URL in the console. This works for technical people however, I am trying to create a basic HTML with a text box for users to enter the encoded URL, click a button, then return the decoded URL on their screen.
Using the below code:
function decodeUrlDefensev3(link) {
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
var link = document.getElementById('textbox1').value;
console.log(link)
<input type="text" id="textbox1" value="https://www.google.com" />
<input type="button" value="button1" onclick="decodeUrlDefensev3(link)" />
<input type="button" value="button2" onclick="function2()" />
The console.log(link) returns the true variable saved above. However, when I click the button, I get an error "Uncaught TypeError: Cannot read properties of null (reading '1')".
How do I pass the textbox input and properly call my function so that whatever is entered inside of textbox1 is parsed using my JavaScript function?
An example of what I am trying to do can be found here:https://jsfiddle.net/37phxda8/1/
I need to use my function above, not the function on that JS Fiddle.
You aren't passing the parameter to the decodeurl function. Try it like this:
function decodeUrlDefensev3(link) {
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
function handleClick() {
var link = document.getElementById('textbox1').value;
decodeUrlDefensev3(link);
}
Then in your html:
<input type="button" value="button1" onclick="handleClick()"/>
The error is probably because there are no results from the link.match function (for "https://www.google.com"), let alone 3 [2nd and 3rd items of the result are used for decode_pile and chars_pile respectively]. You should either change the RegExp for the match or provide and error message like the commented if block in the edited code below.
Also, your function is not taking updated input from textbox1 - only the initial value of "https://www.google.com" set in html. You should retrieve it within the function like:
function decodeUrlDefensev3() {
var link = document.getElementById('textbox1').value;
var matches = link.match(new RegExp('v3/__(.+?)__;(.*?)!'))
/*if (!matches || matches.length < 3) {
alert("Invalid input, could not decode");
return null;
}*/
// love me a mutable array
var decode_pile = Array.from(matches[1]);
var chars_pile = Array.from(atob(matches[2])).reverse();
for (var match of link.matchAll(/\*/g)) {
decode_pile[match.index] = match.pop()
}
return decode_pile.join('')
}
And then your HTML for the button can simply be:
<input type="button" value="button1" onclick="decodeUrlDefensev3()"/>

How to convert select2 array output to single string?

How to convert select2 array output to single string (separated by comma)? Just like this "task_owner":"Administrator,abc2". Current output is separated by comma but in single array "task_owner":["Administrator","abc2"]. This is because the DB is received by string, not array.
Another question, how to re-convert back to array since during editing, Ajax will send that String from DB and I maybe need to convert back to Array for display purpose.
I was referred to this Link but not working.
<form id="myForm">
<select type="text" class="form-control myClass" id="myID" multiple="multiple"></select>
</form>
$('.myClass').select2({
tags: true
});
$('#btnSubmit').on('click',function(){
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $('#myID').val();
if (owner.val() !== null && owner.val().length > 0){
var testOutput = $('#myID') = owner.val().join(',');
testOutput = Object.assign({}, {task_owner: testOutput.task_owner.join(",")})
}
// parameter that need to send to API
var obj = {
task_owner : testOutput,
// Another parameter...
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});
As dicussed:
$(".myClass").select2({
tags: true
});
$("#btnSubmit").on("click", function() {
var testOutput = ""; // I put this because an error appear so I create a new var but the output is = "null", why?
var owner = $("#myID").val(); //
if (Array.isArray(owner) && owner.length) {
testOutput = owner.join(",");
}
var obj = {
task_owner: testOutput
};
var params = JSON.stringify(obj);
$.ajax({
// My Ajax Condition...
});
});

Searching For Existing Values in Array

I have been trying to search for an existing value in an array like below
var values = []
values.push(localStorage.getItem('items'));
console.log(values);
if (values.includes(2)) {
alert('Already Exists.');
}
When i console the array values i have output as ["1,2,3,4,5,6"] so the code treats the array as having just one index which is index[0] which makes the search quite challenging for me.
My challenge is how to find the value 2 in the array values ?
localStorage can only hold strings. As such you need to convert the value you retrieve in to an array, which can be done using split().
Also note that the resulting array will contain string values, so you need to use includes('2'). Try this:
var values = "1,2,3".split(','); // just for this demo
//var values = localStorage.getItem('items').split(',');
console.log(values);
if (values.includes("2")) {
console.log('Already Exists.');
}
Hope this help you.
var names_arr = '["1,2,3,4,5,6"]';
names_arr = names_arr.replace("'",'');
function checkValue(value,arr){
var status = 'Not exist';
for(var i=0; i<arr.length; i++){
var name = arr[i];
if(name == value){
status = 'Exist';
break;
}
}
return status;
}
console.log('status : ' + checkValue('3', names_arr) );
console.log('status : ' + checkValue('10', names_arr) );
First of all, this isn't jQuery, it's vanilla JS.
Second, after doing localStorage.setItem("items", [1,2,3,4,5,6]);, items in local storage will equal to "1,2,3,4,5,6", which is no longer the appropriate format.
Rather, save your array with localStorage.setItem("items", JSON.stringify([1,2,3,4,5,6]));. When you want to retrieve those items, write let vals = JSON.parse(localStorage.getItem("items"));, and search in vals with
vals.includes(2) for a true/false answer,
vals.find(val => val === 2) for 2 or undefined,
val.indexOf(2) to get the index of the
first element equal to 2.
Hope this helps.
firstly get the values from local storage store it in a variable, split it using the split
function, then check if the number is inside the array, alert the message if it returns true
var values =localStorage.getItem('items')
var spliter = values.split(',')
console.log(spliter);
if (spliter.includes('2') == true) {
alert('Already Exists.');
}

How to Remove or avoid duplicate values in LocalStorage

When user click on button it will store some value in LocalStorage and if user click same button again it will store same value again in LocalStorage, How can i remove or avoid duplicates same values in LocalStorage ?!
Can anyone please help me :)
HTML:
<a onclick="AddToCart('ae90ac1a-64c4-49a7-b588-ae6b69a37d47');">Add to Cart</a>
<a onclick="AddToCart('3e58aa74-4585-4bee-b2e0-ed39a1d95442');">Add to Cart</a>
JavaScript:
function AddToCart(varer) {
var itemsLocalStorage = JSON.parse(localStorage.getItem("itemsline") || "[]");
itemsLocalStorage.push(varer);
localStorage.setItem("itemsline", JSON.stringify(itemsLocalStorage));
}
LocalStorage (Before user click) :
[]
LocalStorage (When user click ):
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
LocalStorage (When user click again):
["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
I tried with filter but for some reason it's not going to work:
itemsLocalStorage = itemsLocalStorage.filter(e => e === varer);
Grab the array from localStorage, push the value to the array if it's not found in that array already, and then update localStorage if we pushed.
var array = JSON.parse(window.localStorage.getItem("itemsline")) || [];//the "|| []" replaces possible null from localStorage with empty array
var value = "some value";
if(array.indexOf(value) == -1){
array.push(value);
window.localStorage.setItem("itemsline", JSON.stringify(array));
}
Here's a version of this same code that is more explanatory of how it works:
//All values stored in localStorage are strings.
//Grab our itemsline string from localStorage.
var stringFromLocalStorage = window.localStorage.getItem("itemsline");
//Then parse that string into an actual value.
var parsedValueFromString = JSON.parse(stringFromLocalStorage);
//If that value is null (meaning that we've never saved anything to that spot in localStorage before), use an empty array as our array. Otherwise, just stick with the value we've just parsed out.
var array = parsedValueFromString || [];
//Here's the value we want to add
var value = "some value";
//If our parsed/empty array doesn't already have this value in it...
if(array.indexOf(value) == -1){
//add the value to the array
array.push(value);
//turn the array WITH THE NEW VALUE IN IT into a string to prepare it to be stored in localStorage
var stringRepresentingArray = JSON.stringify(array);
//and store it in localStorage as "itemsline"
window.localStorage.setItem("itemsline", stringRepresentingArray);
}
Take temp array and then check for duplicate values.
var arr = ["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"]
function squash(arr){
var tmp = [];
for(var i = 0; i < arr.length; i++){
if(tmp.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
return tmp;
}
console.log(squash(arr));
You could use filter
array.filter((item, index) => array.indexOf(item) === index)
const array = ["ae90ac1a-64c4-49a7-b588-ae6b69a37d47","ae90ac1a-64c4-49a7-b588-ae6b69a37d47"];
const filteredArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(filteredArray)
You can use Set object of js it always add value only when it is unique
var array = JSON.parse(localStorage.getItem("items")) || [];
let set =new Set(array)
set.add(newValue)
const toArr=Array.from(set)
localStorage.setImem("items",JSON.stringify(toArr))

Separate array of elements by attribute

Let's say I've got a form with several inputs, and I use a pretty standard jQuery statement to get them all:
var inputs = $("#some-form").find("input")
Now, I'd like to act on those inputs, but let's say I want to treat the radio button and/or checkbox groups as a single thing. How can I split inputs out into elements grouped by an attribute, say name. Note, that I don't know what the name is going to be when the processing starts.
In human terms, I need the logic do do something along the lines of:
Let me iterate over the list of inputs. For each input, let me check
to see if it's already been added to a placeholder array. If so,
leave it alone. If not, add it and everything with it's name to said
placeholder array (as a sub array).
Essentially, I'd like something like this:
[[<input type="text" name="name1">], [<input type="radio" name="name2">,<input type="radio" name="name2">]]
Try using attribute selector inside a filter.
var $formInput = $('#some-form').find('input');
var inputText = $formInput.filter('[type=text]')
var otherInput = $formInput.filter("[type=radio]")
.add($formInput.filter('[type=checkbox]'));
or even better
var otherInput = $formInput.filter(function () {
return this.type == 'radio' || this.type == 'checkbox';
});
DEMO: http://jsfiddle.net/utwaf/
How can I split inputs out into elements grouped by an attribute, say name
var elements = []; //elements by name
var $formInput = $('#some-form').find('input');
elements.push($formInput.filter(function() {
return this.name == 'name1';
});
elements.push($formInput.filter(function() {
return this.name == 'name2';
});
Note: All elements pushed into the array are jQuery objects.
function getInputsPartitioned(formEl) {
var inputEls = formEl.querySelectorAll("input");
var inputsByName = Object.create(null);
for (var i = 0; i < inputEls.length; ++i) {
var inputEl = inputEls[i];
var name = inputEl.name;
if (!(name in inputsByName)) {
inputsByName[name] = [];
}
inputsByName[name].push(inputEl);
}
// `inputsByName` now looks like this:
// {
// name1: [<input type="text" name="name1">],
// name2: [<input type="radio" name="name2">, <input type="radio" name="name2">]
// }
// To get it into arrays:
return Object.keys(inputsByName).map(function (name) {
return inputsByName[name];
});
}
Bonus: no jQuery needed.

Categories

Resources