Pseudoternary Encoding

How to parse input[] values and put them into a Javascript Array

How can i get the values of array inputs within the form foo and put them into an associative array/object like this:

By «Pure JavaScript» I take it you mean «Without using JavaScript written by other people, such as the jQuery or YUI teams»? (As opposed to «Without Flash» or «Without DOM»?)

Technically, jQuery is «pure JavaScript.» Do you want to understand how read form elements with plain-old DOM or do you want to be more productive and Get Stuff Done?

querySelectorAll is as impure as DOM, it is an API that browsers expose to JS, not part of JS itself.

5 Answers 5

I needed to do this myself and after finding this question I didn’t like any of the answers: I don’t like regex and the others are limited.

You can get the data variable many ways. I’ll be using jQuery’s serializeArray method when I implement this.

function parseInputs(data) < var ret = <>; retloop: for (var input in data) < var val = data[input]; var parts = input.split('['); var last = ret; for (var i in parts) < var part = parts[i]; if (part.substr(-1) == ']') < part = part.substr(0, part.length - 1); >if (i == parts.length - 1) < last[part] = val; continue retloop; >else if (!last.hasOwnProperty(part)) < last[part] = <>; > last = last[part]; > > return ret; > var data = < "nom": "123", "items[install][item_id_4]": "4", "items[install][item_id_5]": "16", "items[options][takeover]": "yes" >; var out = parseInputs(data); console.log('\n***Moment of truth:\n'); console.log(out); 

Источник

Читайте также:  Java parameters main class

get data from input to array

ALL CODE: http://jsfiddle.net/tZPg4/1420/ Is possible click on Get all and get all data from all inputs and next use them with loop each and get data: this.one (first input(text)), this.two (second input(checkbox)), this.three (third input — hidden )? for example:

$("#getall").click(function()< //here get all data to array, but how? array.each(function(i)< var html = $("this.onethis.twothis.three").appendTo("#myTable"); >); >) 

You need to remove the id attribute from the elements you are cloning. With the code you have now, you’re getting repeated ids everywhere, which is not good.

2 Answers 2

Something like this should work?

$("#getall").click(function() < var myRow = document.createElement("tr"); var array = new Array() $.each($("#p_scents").find("p"), function(ind, elem) < var inputCol = new Array(); console.log("Adding row"); $.each($(elem).find("input"), function(ind2, inputElem) < if ($(inputElem).attr("type") != "checkbox") < inputCol [inputCol .length] = $(inputElem).val(); >else < inputCol [inputCol .length] = $(inputElem).is(":checked"); >>); array[array.length] = inputCol; >); console.log("Outputting results"); for (var i in array) < console.log("Row: "+i); for (var j in array[i]) < console.log("Input: "+j + " = mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)">edited Feb 28, 2012 at 15:49
answered Feb 28, 2012 at 14:03
4
    jsfiddle.net/tZPg4/1425 please add new row and fill in. i have error: elem.val is not a function array[array.length] = elem.val();
    – Gryz Oshea
    Feb 28, 2012 at 14:12
    Edited my answer appropriately - using a class on your inputs to make sure I only get the inputs you are actually after - see jsfiddle.net/tZPg4/1434 for full working jsFiddle
    – Matt Fellows
    Feb 28, 2012 at 14:57
    thanks, but in this example i dont know where input values are related. for example in first line input can be only two values, and in second line can be three values. i would like have each line in seperately variables, for example for each: this.one, this.two, this.three
    – Gryz Oshea
    Feb 28, 2012 at 15:27
    all data from first line (input, checkbox, input) should be one subarray, all data from second line (input, checkbox, input) should be one subarray etc. now all data are in array - i dont know relation between this. now is array = . i would like array = , array[1] = >
    – Gryz Oshea
    Feb 28, 2012 at 15:37
Add a comment|
0
var arr = new Array(); $( 'input' ).each(function(index) < arr[arr.length] = $(this).val(); >)

Источник

JavaScript - Add Value from input box to array

The objective is to add another item to the array, and make an array like ["Car", "House" , "Boat"] etc. What is happening is when i console log, i only have one item in my array and not all the values i submit from form. This is my form

You mean the user enters multiple values into the “box” input field? So is this about splitting the string into tokens?

also you want to do

and end the function with return false; to not start with an empty item each time due to a reloaded page

3 Answers 3

Your items array is within the scope of your guardarNumeros function and will get declared every time guardarNumeros is called, if you want it to persist it needs to be outside:

var items = []; function guardarNumeros()

As mentioned in the comments a form submission will refresh the page by default, to prevent this you need to return false:

I just used this answer to fix my own problem, I was called the equivalent variable in my code to boxvalue outside of the function and getting a blank string in the array.

By including the items inside the scope of your functions you were declaring the array every time.

var items = []; function guardarNumeros() < boxvalue = document.getElementById('box').value; items.push(boxvalue); console.log(items); return false; // stop submission >

You have to declare the array outside the function. because whenever you hit the submit button a new array object is being created and the previous one is being lost because of scope.

You know if we declare a variable inside any function this variable is only visible in this function. Outside this function we can't access it. In your case you declare an array inside the function, then push value to it and also log it. But if you try to access this array from outside the function you will get error if you use strict mode.

Just declare the array in global scope, or also you can pass the array as an argument. this will solve your problem..

var items = []; function guardarNumeros()

Or use this. But make sure you declare the array anywhere in parent function where you call the function.

function guardarNumeros(items)

In this case you also have to check some condition.

Источник

Take the values of a text input and store them into an array

My code can be found here: https://www.w3schools.com/code/tryit.asp?filename=FHC2UOT0RQX6
The program accepts an array var array=[1,0,1,0,1,1,0,0,0] and solves the pseudoternary encoding scheme. All i want to do is simple. Insead of changing the elements of the array(when i want to insert a different input), i want to use the input text and take the values from it and when i press enter or the submit button, it will solve the problem depending on the user inputs. Is that possible to take the values of the text input and make them act as an array ?
Here is the script below but it is better to see the whole code, use the link above.

   

because i want to take each number one by one to solve the problem, it is not just a number,i check each of the elements.

2 Answers 2

Actually you want to write your code inside a function and call the function onload and onclick respectively. Try this, http://www.w3schools.com/code/tryit.asp?filename=FALV2XZQ7V36

var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here var text = ""; function loading() < for (var b = 0; b < array.length; b++) < text += array[b]; >document.getElementById('enc').innerHTML = text; pseudo(array); > function pseudo(a) //function pseudo < var pulse = false; var count = 0; var output = ''; var b = 0; for (b = 0; b < a.length; b++) if (a[b] === 1) < count++; //document.write('

'+'Step '+count+': No line'+'
'+'

'); //document.write(''); output += ''; > else if (a[b] === 0) < count++; pulse = !pulse; //toggles boolean value each time it finds zero if (pulse === true) //pulse shows up < //document.write('

'+'Step: '+count+' goes up'+'
'+'

'); //document.write(''); output += ''; > else < // document.write('

'+'Step: '+count+' goes down'+'
'+'

'); //document.write(''); output += ''; > > document.getElementById("js").innerHTML = output; > function gettext() < var inputText = document.getElementById("tf").value; var inparray = [inputText.length]; for (i in inputText) < inparray[i] = parseInt(inputText[i]); >document.getElementById('enc').innerHTML = inputText; pseudo(inparray); >
   --> 

Use this input

Illustration of pseudoternary encoding scheme

Encode

Note, element is self-closing. element should be child nodes of element instead of element. id of element in document should be unique. Replace duplicate "tf" id at input elements with unique values. Remove element from being child node of div element. Place element before closing tag. Substitute concatenating .innerHTML for document.write()

Attach click event to input type="button" , use String.prototype.split() with parameter "" to create an array from input type="text" .value , Array.prototype.map() with parameter Number to convert String to Number values. Assign resulting array to array variable. Set #js .innerHTML to empty string before calling function again with array as parameter.

    body <> .pad < padding-top: 20%; >.inline < display: inline; >.down    

Use this input

Illustration of pseudoternary encoding scheme

Encode

var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here var text = ""; var enc = document.getElementById("enc"); var button = document.getElementById("button"); var tf = document.getElementById("tf"); var center = document.getElementById("js"); for (var b = 0; b < array.length; b++) < text += array[b]; >enc.innerHTML = text; pseudo(array); function pseudo(a) < var pulse = false; var count = 0; for (var b = 0; b < array.length; b++) if (a[b] === 1) < count++; center.innerHTML += ''; > else if (a[b] === 0) < count++; pulse = !pulse; //toggles boolean value each time it finds zero if (pulse === true) //pulse shows up < center.innerHTML += ''; > else < center.innerHTML += ''; > > > button.onclick = function()

Источник

Value from input field into array - Javascript, localstorage

i'm trying to insert values from input field into an array then store it in localstorage, but the problem is every time i insert a new value it replaces the old value, rather i want it to be added to the existing values . bear with me if it's a silly question, i am a newbie 🙂

Pretty sure you can't store an array in localStorage . I think you need to JSON.stringify() and JSON.parse() .

Also, every time myFunction() is ran, you re-create the array sports . You only need to do that if it doesn't already exist in localStorage .

4 Answers 4

Your sports variable is local to the function, so it gets reinitialized every time the function runs. To fix it, move the declaration outside of the function.

Also, as @RocketHazmat pointed out, you can only store a string. Therefore, your new code snippet should look like:

var sports = ["soccer", "baseball"]; //global scope function myFunction() < var newSport = document.getElementById('textInput').value; sports.push(newSport) window.localStorage.setItem("sportskey", JSON.stringify(sports)); // store as a string document.getElementById('output').innerHTML = window.localStorage.getItem('sportskey'); >

the problem is in the scope of the variables. Your sports array must be declared outside of the myFunction() function

 var sports = ["soccer", "baseball"]; function myFunction() 

Aaargh. im too late with my answer 😉

Yes you re create the array everytime the method is called and you should call JSON.stringify(Array) on storing the item and JSON.parse(string_from_localStore) when loading the item from localStore.

But you should wrap the stringify in an try and catch block, because it can be some reasons when the json string is not well formed that your stringify method crashes the function and it stops working.

var myFunc = function() < //load it at first from localstorage var sports = ["soccer", "baseball"]; var localSports = []; try < localSports = JSON.parse(window.localStorage.getItem('sportskey')); if( localSports == null) localSports = sports; >catch(ex) < console.log("something wrong"); localSports = sports; //fallback >var newSport = document.getElementById('textInput').value; localSports.push(newSport); //this is an array //insert the array with JSON.stringify so you can take it later out and rework with it window.localStorage.setItem("sportskey", JSON.stringify(localSports)); output.innerHTML = window.localStorage.getItem('sportskey'); >; 

Here is the link to the jsfiddle:

Источник

Оцените статью