Post data to 2 dimensional array javascript - javascript

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..

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.

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
});

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

Related

Take an input value and see if it equals the defined object

HTML:
<html>
<body>
<input type = "text" name = "name" id = "name"> </input>
<button type = "submit" id = "submit">Find Student </button>
<script type = "text/javascript" src="ObjectTest.js"></script>
</body>
</html>
Javascript:
var Matt = {
GPA: 4.0,
Faculty: "Science",
Year: 1
};
I have an object that I've defined with some values.
What I am trying to do is to allow text to be entered into the textbox.
When the submit button is hit, a javascript function will be run that grabs the value in the textbox and if it equals the object value, then it will console.log the properties.
Here is my better attempt:
function findStudent(){
var student = document.getElementById('name').value;
return student;
}
console.log(student);
Hard to know exactly what you're trying to achieve or where your object is coming from but your object probably needs to look something like:
var student = {
name:'Matt',
gpa:4.0,
faculty:'Science',
year: 1
}
Try something like:
function checkName(){
var name = document.getElementById('name').val();
if(name === student.name){
console.log('same');
}
else{
console.log('different');
}
}
Called in your button, with something like:
<button onclick="checkName()">Check Student</button>
You have to think about the structure. There should be a lot of students. It's not practical to set multiple objects for each student:
var st1 = { ... }
var st2 = { ... }
Instead it's more practical to declare one object with all students. And put the values in an array:
var students = {
"Matt": ["4.0", "science", "1.0"],
"Laura": ["3.0", "comedy", "2.2"],
...
}
You can output the array as an info to the corresponding student:
function findStudent() {
var info = [];
var student = document.getElementById("name").value;
for (name in students) {
if (name === student) {
info = students[name];
}
}
alert(info);
}
JSFiddle
If you want to use a submit button, it should be in a form. This also makes dealing with inputs easier, even if you don't want to submit the form. I've modified the object so that it has a name property.
var Matt = {
name: 'Matt',
GPA: 4.0,
Faculty: "Science",
Year: 1
};
function checkValue(form) {
if (form.studentName.value == Matt.name) {
form.output.value = ('Match');
} else {
form.output.value = ('Not a match');
}
return false;
}
<form onsubmit="return checkValue(this);">
<label for="studentName">Name: <input name="studentName" id="studentName"></label>
<button>Check the name</button>
<br>
<label for="output">Output: <input name="output" id="output"></label>
</form>
The body of the checkValue function could be:
form.output.value = form.studentName.value == Matt.name? 'Match' : 'Not a match';
However the longer version is simpler to understand.

Search in arrays with javascript on write

I have an html page with two input text boxes.
With javascript, I declare two arrays with numbers and names.
number - name:
1 - John
2 - Sarah
3 - Peter
When I write the number on input A, i need the name appears on input B, and if i write the name on input B i need the number appears on input A
Example: I write "Sarah" on input B and number "2" appears on input A
Example 2: I write "1" on input A and "John" appears on input B
if you're using pure js you need define a onkeyup event in your input and change the 2 array by a map(hash or dictionary) here the code:
<input id="name" type="text" onkeyup="SearchText(this.value)"/>
<input id="value" type="text" onkeyup="SearchId(this.value)"/>
<script>
function SearchText(val) {
txt = document.getElementById("value")
if (val.toLowerCase() in Persons) {
txt.value = Persons[val.toLowerCase()];
} else {
txt.value = '';
}
};
function SearchId(val) {
txt = document.getElementById("name");
for (p in Persons) {
if (Persons[p] == val){
txt.value = p;
break;
} else {
txt.value = '';
}
}
};
</script>
Persons is a map:
Persons = {
'john':1,
'sara':2,
'peter':3
};
this fiddle can help you:
Example Fiddle

Making a json file with an array of values to a key

I have many checkboxes in the html page. I have to send the json data to the server with an array of id's of all the checkboxes that are checked and also the label for these checkboxes.
I was thinking of using jquery with .each() function to check if a checkbox is checked and if it checked add it to the array.
The json file i am looking for is like this
{"checkbox id" : [1, 2, 3], "checkbox label" : ["check1", "check2", "check3"]}
If you want to keep the json structure, you can do the following:
var ids = [];
var labels = [];
$('input[type="checkbox"]').each(function () {
if ($(this).is(':checked')) {
var current_id = $(this).attr('id');
ids.push(current_id);
var current_label = $("label[for='" + $(this).attr('id') + "']").text();
labels.push(current_label);
}
});
var checkboxes = {
"checkbox_id": ids,
"checkbox_label": labels
};
var s_checkboxes = JSON.stringify(checkboxes);
Notice that you can't create a json file in the browser. You will have to do that in the server-side, once the data has been sent.
you can just use the jquery :checked selector to get all the checkboxes that are checked..
var checkedCheckBoxes = $( "input:checked" )
jQuery checked selector
Assuming this HTML:
<label for="checkBox">Label</label>
<input id="checkBox" type="checkbox" />
I would suggest this form of json:
var arr = [];
$('input[type="checkbox"]:checked').each(function() {
var that = $(this);
var id = that.attr('id');
var label = $('label[for="' + id + '"]').text();
var obj = {
id: id,
label: label
}
arr.push(obj);
});
And you would come up with this:
arr = [{id:"1",label:"labelOne"},{ ... }];
If you are looking for a way to format your JSON, I'd put all the information on the checked boxes inside an array looking like this:
{
"checked_boxes" :
[{"id": "1", "label": "checkbox1"},
{"id": "2", "label": "checkbox2"},
{"id": "3", "label": "checkbox3"]
}

Javascript for loop to change the name of textareas in a function

I have created 50 textareas with names def1,def2,def3.....,def50. In my body onLoad() function,I want the same value is set in all these textboxes.
Instead of writing the code 50 times, How can I write some Javascript code to set the value of the textarea, ie in a loop?
I suggest to read the MDC JavaScript guide, as loops and string concatenation are fairly basic operations:
for(var i = 1; i < 51; i++) {
var nameOfTextarea = 'def' + i;
// ...
}
I would give your textboxes ID's (not just names) if possible, and then do something like the following:
var namePrefix = "def";
for(var i = 1; i <= 50; ++i)
{
var textbox = getElementById(namePrefix + i);
// do something to textbox number i.
}
Try jquery for this:
<input type="text" id="t1"/>
<input type="text" id="t2"/>
<input type="text" id="t3"/>
The Jquery code:
var arr = [ "t1", "t2", "t3" ];
jQuery.each(arr, function() {
$("#"+this).val("hello");//$("#" + this).text("hello");
});
Here is the working demo
Try this.
var textareas = document.getElementsByTagName("textarea");
for(var i=0;i<textareas.length;i++){
if(textareas[i].id.indexOf("def") == 0){
textareas[i].value = textareas[i].id;
}
}
You can use tagname property but it will not work if you have some more textbox anywhere else in your page
function loader(){
for(var i=0;i<50;i++)
document.getElementsByName("def"+i)[0].value='Any Value';
}

how do i set a dynamic object in JS?

I want to keep a value from a form by a js function
with document.getElementById("form1")
but in the form there are dynamic inputs amount1 , amount2 ect... (i dont know how many - its from database)
how do i reach form1.amount (p)
when p is the index of the amount ?
thanks
You can retrieve it like this:
var frm = document.getElementById("form1");
if (frm) {
var valueA = frm["amount" + 1].value;
}
A more complete example:
<html>
<form id="f1">
<input name="input1" value="text" type="text" />
</form>
<script>
var f = document.getElementById("f1");
if(f)
{
alert(f["input"+1]);
alert(f["input"+1].value);
}
</script>
</html>
You can get all input elements of a form by use of "getElementsByTagName". Like this:
var form = document.getElementById("form1");
var inputs = form.getElementsByTagName("input");
That way the array "inputs" contains all input elements contained in your form.
Ioannis is pretty much there. To get the value of the ith amount input, use:
var value = document.forms['form1'].elements['amount' + i].value;
A little more robustly:
function getIthAmount(i) {
var o = document.forms['form1'];
o = o && o.elements['amount' + i];
if (o) {
return o.value;
}
}

Categories