3

I have source, like this :

<label>Name:</label>
<input type="text" name="text1"/>
<label>Weight:</label>
<input type="text" name="text2"/>
<button onclick="myfunction">Add</button>

<p id="demo"></p>

<script>
var array = new Array();

function myFunction() {
    var text1 = document.getElementById("text1").value;
    var text2 = document.getElementById("text2").value;

    if(text1 == "" || text2 == ""){
        alert("Empty!!");
    }else{
        array = {'data' : [{"Text1" : text1, "Text2" : text2}]}
    }
}
</script>

My question is, how do i post value each of text to 2 dimensional array in java script? technically, we can post value to 2D array again and again, so the array will looks like:

var data = {{text1,text2},....,{text-n,text-n+1}}

Then figure it out in table based on 2D array. I have tried, but still not work. I'm not proficient with javascript. Really need help..

3 Answers 3

1

You can push a new element to your array every time the button is clicked. The use this array.

var array = [];

function change() {
    var text1 = document.getElementById("text1").value;
    var text2 = document.getElementById("text2").value;

    if (text1 == "" || text2 == "") {
        alert("Empty!!");
        return;
    }

    array.push({
        'data': {
            "Text1": text1,
            "Text2": text2
        }
    });

    console.log(array);
}

Also, you are trying to get element by Id but no Id is assigned to input elements. I corrected that in the this Fiddle. This is working, take a look.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to use Jquery for this

  var array = {
    'x': { a: 'aaa', c: 'xxx' },
    'y': { b: 'bbb', d: 'yyy' }
   };

Use Jquery here

  $.post( '/herp.php', array, function(d) {
     // process response here
  });

4 Comments

Vivek Gupta, Thanks for reply, your answer looks like using JSON?. Next question is, how if we want to add more text dinamically and implementing your example especially about array to case like me?
hei @Vivek Gupta, my name is Ugy not ugly :). But thanks for your reply. Btw, I was edit my question and my code. please look once again. is this the right way to dynamically add objects?
Sorry Ugy my mistake, I deleted that comment
It should be array = {'data' : {'Text1' : text1, 'Text2' : text2}}
0

Put your input in a form, then use serializeArray in jquery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.