0

I have an array:

var array = [
    {id: "X", numberA: 1, numberB: 2, dif: 1},
    {id: "Y", numberA: 2, numberB: 3, dif: 1},
    {id: "Z", numberA: 3, numberB: 5, dif: 2},
]

I also have a form:

<form id="agenda_form">
    <p>ID</p>
    <input type="text" id="id">
    <p>Start<p>
    <input type="number" id="numberA">
    <p>End</p>
    <input type="number" id="numberB">
    <input type="submit" value="Submit" id="submitForm">
</form>

I'm trying to use that form to create an object and push that object into my array. Dif I can calculate by subtracting numberB from number A.

I've tried with jQuery and .val() but can't seem to figure it out. How would I do this?

Thank you!

3
  • I tried a version of Will's example from below. The submit button wasn't working and with his it's still not working. I'll try the other answer too. Commented Mar 2, 2015 at 2:32
  • Please add what you've tried to your post. That will help us diagnose your issue. Commented Mar 2, 2015 at 2:38
  • jsve - Got it to work! The issue was actually outside of the push method. It was caused by something else I was attempting. Thanks though! Commented Mar 2, 2015 at 2:41

2 Answers 2

3

How about something like this?

var array = [
    {id: "X", numberA: 1, numberB: 2, dif: 1},
    {id: "Y", numberA: 2, numberB: 3, dif: 1},
    {id: "Z", numberA: 3, numberB: 5, dif: 2},
]

$("#agenda_form").on("submit", function(e) {
  
  var numA = $("#numberA").val(),
      numB = $("#numberB").val();
  
  var obj = {
    id: "", //whatever you need,
    numberA: numA,
    numberB: numB,
    dif: numB - numA
  };
  
  array.push(obj);
  
  //Prevent page from submitting
  return false;
  
});

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

Comments

0

Try this one.Put this into your page.

HTML CODE

<form id="agenda_form">
<p>ID</p>
<input type="text" id="id">
<p>Start<p>
<input type="number" id="numberA">
<p>End</p>
<input type="number" id="numberB">
<input type="button" value="Submit" id="submitForm">
</form>

JS CODE

$(document).ready(function() {
var array = [
{id: "X", numberA: 1, numberB: 2, dif: 1},
{id: "Y", numberA: 2, numberB: 3, dif: 1},
{id: "Z", numberA: 3, numberB: 5, dif: 2},
];

$('#submitForm').on('click', function(){
  var id = $('#id'),
  numberA = $('#numberA'),
  numberB = $('#numberB');

 var k =  {id:'', numberA: '', numberB: '', dif: ''};
  k.id = id.val();
  k.numberA = numberA.val();
  k.numberB = numberB.val();
  k.dif = parseInt(k.numberB) - parseInt(k.numberA);
  array.push(k);

 });
});

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.